<?php
$this->load->helper('az_config');
$this->load->helper('az_device_helper');
$device_check   = az_check_device();
$device_allowed = !empty($device_check['allowed']);
$device_type    = az_get_device_type();
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<link rel="shortcut icon" href="<?php echo base_url() . AZAPP . 'assets/images/logo.png'; ?>" />
<title><?php echo az_get_config('app_name'); ?> - LOGIN</title>
<link rel="stylesheet" href="<?php echo base_url(); ?>assets/plugins/bootstrap/bootstrap.min.css">
<link rel="stylesheet" href="<?php echo base_url(); ?>assets/plugins/az-core/az-core.css">
<link rel="stylesheet" href="<?php echo base_url(); ?>assets/plugins/az-core/az-core-left-theme.css">
<link rel="stylesheet" href="<?php echo base_url() . AZAPP; ?>assets/plugins/az_theme/az_theme.css">
<link rel="stylesheet" href="<?php echo base_url(); ?>assets/plugins/fa/font-awesome.css">
<script src="<?php echo base_url(); ?>assets/plugins/jquery/jquery.min.js"></script>
<style>
.txt-info-login{font-size:12px;}
.device-badge{display:inline-block;padding:4px 10px;border-radius:12px;font-size:11px;font-weight:bold;margin-bottom:10px;}
.device-badge.pc{background:#e3f2fd;color:#1565c0;} .device-badge.hp{background:#f3e5f5;color:#7b1fa2;}
.device-registered{background:#e8f5e9;color:#2e7d32;padding:10px;border-radius:8px;margin-bottom:15px;text-align:center;}
.device-not-registered{background:#fff3e0;color:#e65100;padding:10px;border-radius:8px;margin-bottom:15px;text-align:center;}
.act-box{background:#eef3fb;border:1px solid #cdd9ee;border-radius:8px;padding:12px;margin-bottom:12px;}
.act-box label{font-size:12px;font-weight:bold;color:#333;display:block;margin-bottom:6px;}
#activation_code{font-family:'Courier New',monospace;font-size:18px;letter-spacing:3px;text-align:center;text-transform:none;}
</style>

<!-- ===== PERBAIKAN TEKS TOMBOL MELUBER (tempel di atas </head>) ===== -->
<style>
.act-box, .act-box *, #device_extra, #device_extra *{ box-sizing:border-box; }
.act-box button, .act-box .btn, .act-box input[type=submit],
#device_extra button, #device_extra .btn{
  white-space:normal !important;     /* izinkan teks turun ke baris baru */
  word-break:break-word !important;
  overflow-wrap:anywhere !important;
  height:auto !important;            /* tinggi menyesuaikan jumlah baris */
  min-height:0 !important;
  line-height:1.35 !important;
  max-width:100% !important;
  padding:10px 12px !important;
  font-size:13px !important;
}
.act-box #activation_code{ letter-spacing:2px !important; text-align:center; }
</style>

</head>
<body style="width:100%;overflow-x:hidden;" class="container-body-login">
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4">
<div class="login-container"><div class="box-login-wrapper"><div class="box-login">
	<img width="100px" src="<?php echo base_url() . AZAPP; ?>assets/images/logo.png">
	<h3><?php echo az_get_config('app_name'); ?></h3>

	<div class="device-badge <?php echo strtolower($device_type); ?>">
		<i class="fa fa-<?php echo $device_type == 'PC' ? 'desktop' : 'mobile'; ?>"></i> Device: <?php echo $device_type; ?>
	</div>

	<?php if ($device_allowed && $device_check['device']): ?>
		<?php $device_users = az_get_device_users($device_check['device']->iddevice); ?>
		<div class="device-registered">
			<i class="fa fa-check-circle"></i> Device Terdaftar: <b><?php echo htmlspecialchars($device_check['device']->device_name); ?></b>
		</div>
		<?php if (count($device_users) == 0): ?>
			<div class="device-not-registered">Device ini belum dikaitkan ke user. Hubungi administrator.</div>
		<?php else: ?>
			<?php if (count($device_users) > 1): ?><div class="txt-info-login" style="text-align:center;margin-bottom:8px;">Pilih akun untuk login otomatis:</div><?php endif; ?>
			<?php foreach ($device_users as $du): ?>
				<form method="POST" action="<?php echo app_url(); ?>login_device/auto_device" style="margin-bottom:6px;">
					<input type="hidden" name="iduser" value="<?php echo (int)$du->iduser; ?>">
					<button type="submit" class="btn btn-success btn-login" style="width:100%;white-space:normal;line-height:1.25;padding:8px 10px;">
						<i class="fa fa-sign-in"></i>
						<?php echo (count($device_users) > 1 ? 'Login sebagai ' : 'Login Otomatis: ') . htmlspecialchars($du->name); ?>
						<small style="display:block;opacity:.8;font-size:10px;margin-top:2px;">(<?php echo htmlspecialchars($du->username); ?>)</small>
					</button>
				</form>
			<?php endforeach; ?>
			<hr><div class="txt-info-login" style="text-align:center;">Atau login manual di bawah:</div>
		<?php endif; ?>

	<?php else: ?>
		<div class="device-not-registered" id="device_unknown_box">
			<i class="fa fa-exclamation-triangle"></i> Device belum dikenal di browser ini.
		</div>

		<!-- ===== KOTAK INPUT KODE 10 KARAKTER (FITUR BARU) ===== -->
		<div class="act-box">
			<label><i class="fa fa-key"></i> Aktifkan perangkat dengan kode 10 karakter</label>
			<form method="POST" action="<?php echo app_url(); ?>login_device/activate_by_code">
				<input type="text" name="activation_code" id="activation_code" class="form-control"
					autocomplete="off" autocapitalize="off" autocorrect="off" spellcheck="false"
					placeholder="cth: aB3@kL9#Qz" maxlength="12" required>
				<small style="display:block;margin:6px 0;color:#666;">Ketik persis kode dari admin (perhatikan huruf besar/kecil & simbol).</small>
				<button type="submit" class="btn btn-primary btn-login" style="width:100%;">
					<i class="fa fa-check"></i> Masukkan token untuk mengaktifkan perangkat
				</button>
			</form>
		</div>
		<div id="device_extra"></div>
	<?php endif; ?>

	<form method="POST" action="<?php echo app_url(); ?>login/process">
		<?php $err_login = $this->session->flashdata("error_login"); if (strlen($err_login) > 0) echo "<div class='login-error-message' style='color:#c0392b;background:#fdecea;padding:8px;border-radius:6px;margin-bottom:8px;'>".$err_login."</div>"; ?>
		<div class="field-login"><i class="fa fa-user"></i><input type="text" name="username" class="form-control" placeholder="Username"></div>
		<div class="field-login"><i class="fa fa-key"></i><input type="password" name="password" class="form-control" placeholder="Password"></div>
		<div class="txt-right"><button type="submit" class="btn btn-info btn-login">Login</button></div>
		<div class="login-copyright">Copyright &copy; <?php echo Date('Y'); ?> <a target="_blank" href="">MANAJEMEN</a></div>
	</form>
</div></div></div>
</div>
</div>
<script>
setTimeout(function(){ jQuery(".login-error-message").hide("slow"); }, 5000);

(function(){
	var deviceAllowed = <?php echo $device_allowed ? 'true' : 'false'; ?>;
	var appUrl = <?php echo json_encode(app_url()); ?>;
	function getRecovery(){ try{ return localStorage.getItem('az_recovery_token')||''; }catch(e){ return ''; } }
	function saveRecovery(t){ try{ localStorage.setItem('az_recovery_token', t); }catch(e){} }

	function showReportButton(){
		var box = document.getElementById('device_extra'); if(!box) return;
		var wrap = document.createElement('div');
		wrap.style.cssText = 'text-align:center;margin-bottom:12px;';
		var btn = document.createElement('button');
		btn.type='button'; btn.className='btn btn-warning btn-sm';
		btn.innerHTML='<i class="fa fa-bell"></i> Lapor admin untuk registrasi ulang';
		btn.onclick=function(){
			btn.disabled=true; btn.innerHTML='Mengirim...';
			fetch(appUrl+'login_device/request_recovery',{method:'POST',headers:{'Content-Type':'application/json'},
				body:JSON.stringify({device_name:navigator.platform+' - '+navigator.userAgent.substring(0,80)})})
			.then(function(r){return r.json();}).then(function(res){
				if(res.err_code==0){ alert('Laporan terkirim. Minta KODE AKTIVASI baru ke admin, lalu ketik di kotak di atas.'); }
				else { alert('Gagal mengirim laporan.'); btn.disabled=false; btn.innerHTML='<i class="fa fa-bell"></i> Lapor admin untuk registrasi ulang'; }
			}).catch(function(){ alert('Gagal mengirim laporan.'); btn.disabled=false; btn.innerHTML='<i class="fa fa-bell"></i> Lapor admin untuk registrasi ulang'; });
		};
		wrap.appendChild(btn); box.appendChild(wrap);
	}

	if(!deviceAllowed){
		var recovery = getRecovery();
		if(recovery){
			fetch(appUrl+'login_device/recover_device',{method:'POST',headers:{'Content-Type':'application/json'},
				body:JSON.stringify({recovery_token:recovery})})
			.then(function(r){return r.json();}).then(function(res){
				if(res.err_code==0){ if(res.recovery_token) saveRecovery(res.recovery_token); location.reload(); }
				else showReportButton();
			}).catch(function(){ showReportButton(); });
		} else { showReportButton(); }
	}
})();
</script>

<script>
    // Daftarkan Service Worker untuk menangani mode Offline
    if ('serviceWorker' in navigator) {
        window.addEventListener('load', function() {
            // Path ke sw.js (sesuaikan jika struktur folder berbeda)
            // Karena base_url Anda .../RahmatAllah/, maka sw.js harus diakses dari sana
            var swUrl = '<?php echo base_url(); ?>sw.js';
            
            navigator.serviceWorker.register(swUrl)
                .then(function(registration) {
                    console.log('ServiceWorker registration successful with scope: ', registration.scope);
                })
                .catch(function(err) {
                    console.log('ServiceWorker registration failed: ', err);
                });
        });
    }
</script>

</body>
</html>