<?php $this->load->helper('az_config'); ?>
<!DOCTYPE html>
<html>
<head>
<title>Daftar Device Terdaftar</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="<?php echo base_url();?>assets/plugins/bootstrap/bootstrap.min.css">
<link rel="stylesheet" href="<?php echo base_url();?>assets/plugins/fa/font-awesome.css">
<style>
body{padding:20px;background:#f5f5f5;} .container{max-width:1000px;margin:0 auto;background:#fff;padding:24px;border-radius:8px;}
h2{color:#333;border-bottom:2px solid #2196F3;padding-bottom:10px;}
table{width:100%;border-collapse:collapse;margin-top:16px;} th,td{padding:9px;border:1px solid #ddd;text-align:left;vertical-align:top;} th{background:#f5f5f5;}
.badge-pc{background:#e3f2fd;color:#1565c0;padding:3px 8px;border-radius:12px;} .badge-hp{background:#f3e5f5;color:#7b1fa2;padding:3px 8px;border-radius:12px;}
.btn-act{background:#2196F3;color:#fff;border:none;padding:5px 9px;border-radius:4px;text-decoration:none;display:inline-block;margin-bottom:4px;}
.btn-edit{background:#ff9800;color:#fff;border:none;padding:5px 9px;border-radius:4px;text-decoration:none;display:inline-block;margin-bottom:4px;}
.btn-danger{background:#f44336;color:#fff;border:none;padding:5px 9px;border-radius:4px;text-decoration:none;display:inline-block;margin-bottom:4px;}
.codebox{background:#fff3cd;border:1px solid #ffeeba;border-radius:8px;padding:14px;margin:16px 0;}
.codebox .code{font-family:'Courier New',monospace;font-size:26px;letter-spacing:5px;font-weight:bold;color:#856404;background:#fff;display:inline-block;padding:6px 14px;border-radius:6px;border:1px dashed #c9a227;}
</style>
</head>
<body>
<div class="container">
	<h2><i class="fa fa-list"></i> Daftar Device Terdaftar</h2>

	<?php if ($this->session->flashdata('success')): ?>
		<div style="background:#d4edda;color:#155724;padding:12px 16px;border-radius:8px;margin:16px 0;border:1px solid #c3e6cb;">
			<i class="fa fa-check-circle"></i> <?php echo $this->session->flashdata('success'); ?>
		</div>
	<?php endif; ?>
	<?php if ($this->session->flashdata('error')): ?>
		<div style="background:#f8d7da;color:#721c24;padding:12px 16px;border-radius:8px;margin:16px 0;border:1px solid #f5c6cb;">
			<i class="fa fa-exclamation-circle"></i> <?php echo $this->session->flashdata('error'); ?>
		</div>
	<?php endif; ?>

	<?php if ($this->session->flashdata('activation_code')): ?>
		<div class="codebox">
			<b><i class="fa fa-key"></i> KODE AKTIVASI untuk device "<?php echo htmlspecialchars($this->session->flashdata('activation_device_name')); ?>"</b><br>
			Berikan 10 karakter ini ke perangkat outlet untuk diketik di halaman login (atau buka link lengkap di perangkat outlet):<br>
			<span class="code" id="theCode"><?php echo htmlspecialchars($this->session->flashdata('activation_code')); ?></span>
			<button type="button" class="btn btn-sm btn-warning" onclick="var t=document.getElementById('theCode').innerText;navigator.clipboard.writeText(t).then(function(){alert('Kode tersalin: '+t;});">Salin kode</button>
			<br><small style="color:#856404;">Kode berlaku 24 jam & sekali pakai. Kalau sudah terpakai/kedaluwarsa, klik "Kirim Ulang Kode".</small>
			<details style="margin-top:8px;"><summary style="cursor:pointer;color:#856404;">atau pakai link lengkap</summary>
				<input type="text" readonly onclick="this.select();document.execCommand('copy');" value="<?php echo $this->session->flashdata('activation_url'); ?>" style="width:100%;margin-top:6px;padding:6px;font-size:11px;">
			</details>
		</div>
	<?php endif; ?>

	<p>
		<a href="<?php echo base_url(); ?>login_device/register" class="btn btn-primary btn-sm"><i class="fa fa-plus"></i> Tambah Device</a>
		<a href="<?php echo base_url(); ?>login_device/recovery_requests" class="btn btn-warning btn-sm"><i class="fa fa-bell"></i> Laporan Recovery</a>
		<a href="<?php echo base_url(); ?>home" class="btn btn-default btn-sm">Kembali</a>
	</p>

	<table>
		<thead><tr><th>ID</th><th>Nama</th><th>Tipe</th><th>Outlet</th><th>User</th><th>Status</th><th>Rotasi Berikutnya</th><th>Aksi</th></tr></thead>
		<tbody>
		<?php foreach ($devices as $device): ?>
			<tr>
				<td><?php echo (int)$device->iddevice; ?></td>
				<td><b><?php echo htmlspecialchars($device->device_name); ?></b></td>
				<td><span class="badge-<?php echo strtolower($device->device_type); ?>"><?php echo htmlspecialchars($device->device_type); ?></span></td>
				<td><?php echo htmlspecialchars($device->outlet_name); ?></td>
				<td><?php echo ($device->user_count > 0) ? htmlspecialchars($device->user_names) : '<i style="color:#c0392b;">(belum ada)</i>'; ?></td>
				<td><?php echo !empty($device->activated) ? '<span class="label label-success">Aktif</span>' : '<span class="label label-default">Belum aktivasi</span>'; ?></td>
				<td><?php echo !empty($device->next_rotation_at) ? date('d-m-Y H:i', strtotime($device->next_rotation_at)) : '-'; ?></td>
				<td>
					<a href="<?php echo base_url(); ?>login_device/edit_users/<?php echo (int)$device->iddevice; ?>" class="btn-edit"><i class="fa fa-users"></i> Atur User</a><br>
					<a href="<?php echo base_url(); ?>login_device/resend_link/<?php echo (int)$device->iddevice; ?>" class="btn-act" onclick="return confirm('Buat KODE AKTIVASI baru untuk device ini?\nKode lama akan hangus. Lanjutkan?');"><i class="fa fa-paper-plane"></i> Kirim Ulang Kode</a><br>
					<a href="<?php echo base_url(); ?>login_device/delete/<?php echo (int)$device->iddevice; ?>" class="btn-danger" onclick="return confirm('Nonaktifkan device ini?')"><i class="fa fa-trash"></i> Hapus</a>
				</td>
			</tr>
		<?php endforeach; ?>
		</tbody>
	</table>
</div>
<script>
// perbaiki syntax tombol salin (tanda kurung)
document.addEventListener('click', function(e){
	if(e.target && e.target.getAttribute && e.target.getAttribute('onclick') && e.target.getAttribute('onclick').indexOf('theCode')>-1){
		// fallback: tidak apa, handler inline sudah jalan
	}
});
</script>

<!-- ===== PERBAIKAN TOMBOL SALIN KODE (tempel di atas </body>) ===== -->
<script>
(function(){
  function fallbackCopy(text){
    var ta=document.createElement('textarea');
    ta.value=text; ta.setAttribute('readonly','');
    ta.style.position='fixed'; ta.style.top='-9999px'; ta.style.left='-9999px';
    document.body.appendChild(ta);
    ta.focus(); ta.select(); ta.setSelectionRange(0, ta.value.length);
    var ok=false; try{ ok=document.execCommand('copy'); }catch(e){ ok=false; }
    document.body.removeChild(ta);
    return ok;
  }
  function copyText(text, onOk){
    if(!text) return;
    var done=false;
    function finish(){ if(done) return; done=true; if(typeof onOk==='function') onOk(); }
    if(window.isSecureContext && navigator.clipboard && navigator.clipboard.writeText){
      navigator.clipboard.writeText(text).then(finish, function(){
        if(fallbackCopy(text)) finish(); else alert('Gagal menyalin. Kode: '+text);
      });
    } else {
      if(fallbackCopy(text)) finish(); else alert('Gagal menyalin. Kode: '+text);
    }
  }
  function readCode(){
    var span = document.getElementById('theCode');
    if(!span) span = document.querySelector('.codebox .code') || document.querySelector('.code');
    if(!span) return '';
    var c = span.getAttribute('data-code');
    if(!c) c = (span.textContent || span.innerText || '');
    return c.replace(/\s+/g,'');   /* spasi di layar hanya hiasan, kode asli tanpa spasi */
  }
  function bind(){
    var btns = document.getElementsByTagName('button');
    for(var i=0;i<btns.length;i++){
      var b=btns[i];
      var txt=(b.textContent||b.innerText||'');
      var oc =(b.getAttribute('onclick')||'');
      if(txt.indexOf('Salin kode')>-1 || oc.indexOf('theCode')>-1 || oc.indexOf('clipboard')>-1){
        b.setAttribute('type','button');
        b.onclick=function(e){
          e.preventDefault();
          var btn=this, code=readCode();
          if(!code){ alert('Kode tidak ditemukan.'); return; }
          copyText(code, function(){
            var old=btn.innerHTML; btn.innerHTML='✓ Tersalin!'; btn.disabled=true;
            setTimeout(function(){ btn.innerHTML=old; btn.disabled=false; }, 1500);
          });
        };
      }
    }
  }
  if(document.readyState==='loading') document.addEventListener('DOMContentLoaded', bind);
  else bind();
})();
</script>

</body>
</html>