<?php
require_once __DIR__ . '/includes/initialize.php';
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: 0');
if (is_logged_in()) {
    redirect('/dashboard.php');
}
$err = '';
$login_id = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $login_id = trim((string)($_POST['login_id'] ?? ''));
    $pw = (string)($_POST['password'] ?? '');
    if (!verify_csrf($_POST['csrf'] ?? null)) {
        $err = 'Invalid request. Please refresh and try again.';
    } elseif ($login_id === '' || $pw === '') {
        $err = 'Please enter username and password.';
    } else {
        $stmt = $con->prepare('SELECT id,name,username,email,mobile_no,password_hash,role,role_id,status,failed_login_count,locked_until,force_password_change,mfa_enabled FROM jos_admin_users WHERE status=1 AND username=? LIMIT 1');
        $stmt->bind_param('s', $login_id);
        $stmt->execute();
        $u = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        $locked = $u && !empty($u['locked_until']) && strtotime($u['locked_until']) > time();
        if ($locked) {
            $err = 'Account temporarily locked. Try again later.';
            log_login_attempt((int)$u['id'], $login_id, false, 'locked');
        } elseif ($u && password_verify($pw, $u['password_hash'])) {
            session_regenerate_id(true);
            unset($u['password_hash']);
            $_SESSION['admin_user'] = $u;
            $ip = client_ip();
            $id = (int)$u['id'];
            $up = $con->prepare('UPDATE jos_admin_users SET failed_login_count=0, locked_until=NULL, last_login_at=NOW(), last_login_ip=? WHERE id=?');
            $up->bind_param('si', $ip, $id);
            $up->execute();
            $up->close();
            remember_session($id);
            log_login_attempt($id, $login_id, true, 'success');
            audit_log('login', 'admin_user', (string)$id);
            redirect('/dashboard.php');
        } else {
            $err = 'Invalid username or password.';
            log_login_attempt($u['id'] ?? null, $login_id, false, 'bad_credentials');
            if ($u) {
                $id = (int)$u['id'];
                $fails = (int)$u['failed_login_count'] + 1;
                $lock = $fails >= 5 ? ', locked_until=DATE_ADD(NOW(), INTERVAL 15 MINUTE)' : '';
                $con->query("UPDATE jos_admin_users SET failed_login_count=$fails $lock WHERE id=$id");
            }
        }
    }
}
$csrf = csrf_token();
?><!doctype html>
<html lang="en"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Enterprise Portal - Attendance Box</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="/assets/js/login.tailwind.config.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/assets/css/login.css">
</head><body>
<div class="min-h-screen flex flex-col px-6 py-7">
<header class="flex items-center justify-between"><div class="flex items-center gap-3"><div class="w-11 h-11 rounded-xl bg-blue-600 text-white grid place-items-center shadow-lg"><i class="fa-solid fa-cube"></i></div><div class="text-xl font-extrabold text-slate-900">Attendance Box</div></div><div class="hidden sm:flex items-center gap-2 bg-white border border-slate-200 rounded-full px-4 py-2 text-xs font-extrabold tracking-widest text-slate-800 shadow-sm"><span>🇮🇳</span> MADE IN INDIA</div></header>
<main class="flex-1 grid place-items-center"><section class="w-full max-w-[445px] text-center"><div class="inline-flex items-center gap-2 bg-white/80 border border-slate-200 rounded-full px-4 py-2 text-sm text-slate-700 shadow-sm"><i class="fa-solid fa-building text-blue-500"></i> Workspace: <strong class="text-blue-700">Inventive Infotech</strong></div><h1 class="mt-7 text-3xl font-extrabold text-slate-950">Sign in to console</h1><p class="mt-3 text-blue-700 font-bold tracking-wide">Biometric Precision, Flawless Compliance.</p>
<form method="post" autocomplete="off" class="mt-10 bg-white rounded-[28px] shadow-2xl border border-slate-100 text-left px-10 py-9 relative overflow-hidden"><div class="absolute top-0 left-0 right-0 h-1.5 bg-blue-600"></div><input type="hidden" name="csrf" value="<?= h($csrf) ?>">
<?php if ($err): ?><div class="mb-5 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm font-semibold text-red-700"><?= h($err) ?></div><?php endif; ?>
<label for="login-username" class="block text-xs font-extrabold tracking-[.22em] text-slate-500 mb-2">USERNAME</label><div class="relative mb-6"><i class="fa-solid fa-user absolute left-4 top-1/2 -translate-y-1/2 text-slate-400"></i><input id="login-username" name="login_id" value="<?= h($login_id) ?>" class="w-full h-14 rounded-2xl border border-slate-200 pl-12 pr-4 text-slate-800 outline-none focus:border-blue-500 focus:ring-4 focus:ring-blue-100" placeholder="Enter your username" required autocomplete="username"></div>
<div class="flex items-center justify-between mb-2"><label for="login-password" class="block text-xs font-extrabold tracking-[.22em] text-slate-500">PASSWORD</label><a href="#" class="text-xs font-bold text-blue-600">Forgot?</a></div><div class="relative mb-6"><i class="fa-solid fa-lock absolute left-4 top-1/2 -translate-y-1/2 text-slate-400"></i><input id="login-password" name="password" type="password" class="w-full h-14 rounded-2xl border border-slate-200 pl-12 pr-12 text-slate-800 outline-none focus:border-blue-500 focus:ring-4 focus:ring-blue-100" placeholder="********" required autocomplete="current-password"><button id="password-toggle" type="button" class="absolute right-4 top-1/2 -translate-y-1/2 text-slate-400"><i class="fa-regular fa-eye"></i></button></div>
<label class="inline-flex items-center gap-3 text-sm text-slate-600 mb-6"><input type="checkbox" name="remember" class="w-4 h-4 rounded border-slate-300"> Keep me signed in</label><button type="submit" class="w-full h-14 rounded-2xl bg-slate-950 text-white font-extrabold shadow-xl shadow-slate-300 hover:bg-blue-700 transition">Sign In Securely <i class="fa-solid fa-arrow-right ml-2"></i></button>
</form><div class="mt-8 text-xs text-slate-500"><i class="fa-solid fa-shield-halved text-blue-500"></i> Protected by Enterprise Security</div></section></main></div>
<script>document.getElementById('password-toggle')?.addEventListener('click',function(){const p=document.getElementById('login-password');p.type=p.type==='password'?'text':'password';this.querySelector('i').className=p.type==='password'?'fa-regular fa-eye':'fa-regular fa-eye-slash';});</script>
</body></html>
