<?php
session_start();
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

// Already logged in — go to dashboard
if (isset($_SESSION['user_id'])) {
    header('Location: index.php');
    exit();
}

$error_message   = '';
$success_message = '';

require_once __DIR__ . '/layouts/dbconn.php';
require_once __DIR__ . '/includes/iscms_layout.php';

$login_has_username = false;
$login_has_must_change_password = false;
if (isset($conn) && $conn instanceof mysqli && $conn->connect_errno === 0) {
    $login_has_username = iscms_column_exists($conn, 'users', 'username');
    $login_has_must_change_password = iscms_column_exists($conn, 'users', 'must_change_password');
}

$login_id_label = $login_has_username ? 'Email Address or Username' : 'Email Address';
$login_id_placeholder = $login_has_username
    ? 'e.g. john@ssbs.gov.ss or john.deng'
    : 'e.g. john@ssbs.gov.ss';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $identifier = trim($_POST['identifier'] ?? '');
    $password   = $_POST['password']   ?? '';

    if (empty($identifier) || empty($password)) {
        $error_message = $login_has_username
            ? 'Email/username and password are required.'
            : 'Email and password are required.';
    } else {
        $ip_address = filter_var(
            $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'],
            FILTER_VALIDATE_IP
        ) ?: $_SERVER['REMOTE_ADDR'];
        $user_agent = substr($_SERVER['HTTP_USER_AGENT'] ?? '', 0, 500);

        try {
            // Fetch user by email (and username when that column exists — v2 schema)
            $selectUserCols = "u.id, u.org_id, u.role_id, u.dept_id, u.employee_number";
            if ($login_has_username) {
                $selectUserCols .= ", u.username";
            }
            $selectUserCols .= ", u.first_name, u.last_name, u.email,
                           u.password_hash, u.phone, u.user_type, u.designation,
                           u.profile_photo, u.status, u.email_verified,
                           u.failed_logins, u.locked_until";
            if ($login_has_must_change_password) {
                $selectUserCols .= ", u.must_change_password";
            }
            $whereLogin = $login_has_username
                ? '(u.email = ? OR u.username = ?)'
                : 'u.email = ?';

            $sql = "SELECT {$selectUserCols},
                           r.role_name, r.role_code,
                           d.dept_name, d.dept_code
                    FROM   users u
                    INNER JOIN roles       r ON u.role_id = r.id AND r.is_active = 1
                    LEFT  JOIN departments d ON u.dept_id = d.id
                    WHERE  {$whereLogin}
                    LIMIT  1";

            $stmt = $conn->prepare($sql);
            if (!$stmt) {
                throw new RuntimeException('Login query prepare failed: ' . $conn->error);
            }
            if ($login_has_username) {
                $stmt->bind_param('ss', $identifier, $identifier);
            } else {
                $stmt->bind_param('s', $identifier);
            }
            $stmt->execute();
            $result = $stmt->get_result();

            if ($result->num_rows === 1) {
                $user = $result->fetch_assoc();

                // ── 1. Status gate ────────────────────────────────────────
                if ($user['status'] === 'inactive') {
                    $error_message = 'Your account has been deactivated. Contact the administrator.';

                } elseif ($user['status'] === 'pending_verification') {
                    $error_message = 'Your account is pending verification. Check your email or contact support.';

                } elseif ($user['status'] === 'locked' ||
                          ($user['locked_until'] !== null &&
                           strtotime($user['locked_until']) > time())) {

                    $unlock_at = $user['locked_until']
                        ? date('H:i', strtotime($user['locked_until']))
                        : 'later';
                    $error_message = "Account locked due to too many failed attempts. Try again after {$unlock_at} or contact the administrator.";

                } else {
                    // ── 2. Password check ─────────────────────────────────
                    if (password_verify($password, $user['password_hash'])) {

                        // ── 3. Unlock & update login stamp ─────────────────
                        $upd = $conn->prepare(
                            "UPDATE users
                             SET failed_logins = 0,
                                 locked_until  = NULL,
                                 last_login    = NOW(),
                                 last_ip       = ?
                             WHERE id = ?"
                        );
                        $upd->bind_param('ss', $ip_address, $user['id']);
                        $upd->execute();
                        $upd->close();

                        // ── 4. Create user_sessions record ─────────────────
                        $raw_token  = bin2hex(random_bytes(32));
                        $token_hash = hash('sha256', $raw_token);

                        // Read session lifetime from settings (default 8h)
                        $lifetime_h = 8;
                        $cfg = $conn->query("SELECT setting_value FROM system_settings WHERE setting_key = 'session_lifetime_hours' LIMIT 1");
                        if ($cfg && $row = $cfg->fetch_assoc()) {
                            $lifetime_h = max(1, (int)$row['setting_value']);
                        }
                        $expires_at = date('Y-m-d H:i:s', strtotime("+{$lifetime_h} hours"));

                        $sess_id = '';
                        $ins = $conn->prepare(
                            "INSERT INTO user_sessions (id, user_id, token_hash, ip_address, user_agent, expires_at)
                             VALUES (UUID(), ?, ?, ?, ?, ?)"
                        );
                        $ins->bind_param('sssss', $user['id'], $token_hash, $ip_address, $user_agent, $expires_at);
                        $ins->execute();
                        // Retrieve the generated UUID
                        $sess_row = $conn->query("SELECT id FROM user_sessions WHERE token_hash = '" . $conn->real_escape_string($token_hash) . "' LIMIT 1");
                        if ($sess_row) {
                            $sess_id = $sess_row->fetch_assoc()['id'] ?? '';
                        }
                        $ins->close();

                        // ── 5. Audit log ────────────────────────────────────
                        $log_data = json_encode([
                            'event'       => 'LOGIN_SUCCESS',
                            'role'        => $user['role_code'],
                            'user_type'   => $user['user_type'],
                            'session_id'  => $sess_id,
                        ]);
                        $log = $conn->prepare(
                            "INSERT INTO audit_logs
                               (id, user_id, session_id, action, module,
                                entity_type, entity_id, new_values,
                                ip_address, user_agent, request_method, request_path)
                             VALUES (UUID(), ?, ?, 'LOGIN', 'authentication',
                                     'user', ?, ?, ?, ?, 'POST', '/login.php')"
                        );
                        $log->bind_param('ssssss',
                            $user['id'], $sess_id,
                            $user['id'], $log_data,
                            $ip_address, $user_agent
                        );
                        $log->execute();
                        $log->close();

                        // ── 6. Regenerate session to prevent fixation ───────
                        session_regenerate_id(true);

                        // ── 7. Store session data ───────────────────────────
                        $_SESSION['user_id']        = $user['id'];
                        $_SESSION['email']          = $user['email'];
                        $_SESSION['username']       = ($login_has_username && isset($user['username']))
                            ? (string) $user['username']
                            : '';
                        $_SESSION['first_name']     = $user['first_name'];
                        $_SESSION['last_name']      = $user['last_name'];
                        $_SESSION['full_name']      = trim($user['first_name'] . ' ' . $user['last_name']);
                        $_SESSION['phone']          = $user['phone'];
                        $_SESSION['role_id']        = $user['role_id'];
                        $_SESSION['role_name']      = $user['role_name'];
                        $_SESSION['role_code']      = $user['role_code'];
                        $_SESSION['user_type']      = $user['user_type'];
                        $_SESSION['designation']    = $user['designation'];
                        $_SESSION['dept_id']        = $user['dept_id'];
                        $_SESSION['dept_name']      = $user['dept_name'];
                        $_SESSION['dept_code']      = $user['dept_code'];
                        $_SESSION['org_id']         = $user['org_id'];
                        $_SESSION['employee_number']= $user['employee_number'];
                        $_SESSION['profile_photo']  = $user['profile_photo'];
                        $_SESSION['login_time']     = time();
                        $_SESSION['session_db_id']  = $sess_id;
                        $_SESSION['session_token']  = $raw_token;
                        $_SESSION['must_change_pw'] = ($login_has_must_change_password && !empty($user['must_change_password']));

                        $stmt->close();
                        $conn->close();

                        // ── 8. Role-based redirect ──────────────────────────
                        if ($login_has_must_change_password && !empty($user['must_change_password'])) {
                            header('Location: change_password.php?forced=1');
                        } else {
                            $redirect = match($user['role_code']) {
                                'SUPER_ADMIN'   => 'index.php',
                                'ADMIN'         => 'index.php',
                                'CERT_OFFICER'  => 'certifications.php',
                                'INSPECTOR'     => 'inspections.php',
                                'LAB_OFFICER'   => 'laboratory.php',
                                'ENF_OFFICER'   => 'enforcement.php',
                                'MKT_OFFICER'   => 'market_surveillance.php',
                                'STD_OFFICER'   => 'standards.php',
                                'CLIENT'        => 'client_portal.php',
                                'REVIEWER'      => 'applications.php',
                                'FINANCE'       => 'finance.php',
                                default         => 'index.php',
                            };
                            header("Location: {$redirect}");
                        }
                        exit();

                    } else {
                        // ── Wrong password ─────────────────────────────────
                        $new_fails = $user['failed_logins'] + 1;

                        // Read lockout threshold from settings (default 5)
                        $max_attempts = 5;
                        $cfg2 = $conn->query("SELECT setting_value FROM system_settings WHERE setting_key = 'max_login_attempts' LIMIT 1");
                        if ($cfg2 && $r2 = $cfg2->fetch_assoc()) {
                            $max_attempts = max(1, (int)$r2['setting_value']);
                        }

                        $lock_until = null;
                        if ($new_fails >= $max_attempts) {
                            $lockout_min = 30;
                            $cfg3 = $conn->query("SELECT setting_value FROM system_settings WHERE setting_key = 'account_lockout_minutes' LIMIT 1");
                            if ($cfg3 && $r3 = $cfg3->fetch_assoc()) {
                                $lockout_min = max(1, (int)$r3['setting_value']);
                            }
                            $lock_until = date('Y-m-d H:i:s', strtotime("+{$lockout_min} minutes"));
                        }

                        $upd2 = $conn->prepare(
                            "UPDATE users SET failed_logins = ?, locked_until = ? WHERE id = ?"
                        );
                        $upd2->bind_param('iss', $new_fails, $lock_until, $user['id']);
                        $upd2->execute();
                        $upd2->close();

                        // Audit log for failed attempt
                        $fail_data = json_encode([
                            'event'    => 'LOGIN_FAILED',
                            'reason'   => 'invalid_password',
                            'attempts' => $new_fails,
                        ]);
                        $log2 = $conn->prepare(
                            "INSERT INTO audit_logs
                               (id, user_id, action, module, entity_type, entity_id,
                                new_values, ip_address, user_agent, request_method, request_path)
                             VALUES (UUID(), ?, 'LOGIN_FAILED', 'authentication',
                                     'user', ?, ?, ?, ?, 'POST', '/login.php')"
                        );
                        $log2->bind_param('sssss',
                            $user['id'], $user['id'],
                            $fail_data, $ip_address, $user_agent
                        );
                        $log2->execute();
                        $log2->close();

                        $remaining = max(0, $max_attempts - $new_fails);
                        if ($lock_until) {
                            $error_message = 'Account locked due to too many failed attempts. Try again in 30 minutes.';
                        } elseif ($remaining > 0) {
                            $error_message = $login_has_username
                                ? "Invalid email/username or password. {$remaining} attempt(s) remaining before lockout."
                                : "Invalid email or password. {$remaining} attempt(s) remaining before lockout.";
                        } else {
                            $error_message = $login_has_username
                                ? 'Invalid email/username or password.'
                                : 'Invalid email or password.';
                        }
                    }
                }
            } else {
                // User not found — log without revealing the fact
                $fail_data = json_encode([
                    'event'  => 'LOGIN_FAILED',
                    'reason' => 'user_not_found',
                ]);
                $log3 = $conn->prepare(
                    "INSERT INTO audit_logs
                       (id, action, module, new_values, ip_address, user_agent,
                        request_method, request_path)
                     VALUES (UUID(), 'LOGIN_FAILED', 'authentication',
                             ?, ?, ?, 'POST', '/login.php')"
                );
                $log3->bind_param('sss', $fail_data, $ip_address, $user_agent);
                $log3->execute();
                $log3->close();

                $error_message = $login_has_username
                    ? 'Invalid email/username or password.'
                    : 'Invalid email or password.';
            }

            $stmt->close();

        } catch (Exception $e) {
            error_log('SSBS login error: ' . $e->getMessage());
            $error_message = 'A system error occurred. Please try again or contact support.';
        }

        if (isset($conn) && $conn instanceof mysqli && $conn->connect_errno === 0) {
            $conn->close();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sign In — South Sudan Bureau of Standards</title>
    <meta name="description" content="SSBS Integrated Standards and Compliance Management System">
    <meta name="robots" content="noindex, nofollow">

    <!-- Bootstrap 5 -->
    <link rel="stylesheet" href="assets/libs/bootstrap/css/bootstrap.min.css">
    <!-- Remix Icons -->
    <link rel="stylesheet" href="assets/libs/remixicon/remixicon.css">
    <!-- SweetAlert2 -->
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <link  rel="stylesheet" href="assets/libs/sweetalert2/sweetalert2.min.css">

    <style>
        :root {
            --ssbs-blue:       #1a3a6b;
            --ssbs-blue-light: #2a5298;
            --ssbs-blue-dark:  #0d1f3c;
            --ssbs-gold:       #c8a92b;
            --ssbs-gold-light: #e6c84a;
            --ssbs-green:      #1a6e2e;
            --ssbs-green-light:#28a745;
            --ssbs-red:        #c0392b;
            --bg-light:        #f0f4f8;
            --white:           #ffffff;
            --border:          #d0d7de;
            --text-dark:       #1c2b4a;
            --text-muted:      #6b7280;
        }

        * { box-sizing: border-box; }

        body {
            background: linear-gradient(135deg, #0d1f3c 0%, #1a3a6b 50%, #1a4a2e 100%);
            min-height: 100vh;
            font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        /* ── Card ─────────────────────────────────── */
        .auth-card {
            width: 100%;
            max-width: 960px;
            border-radius: 20px;
            overflow: hidden;
            box-shadow: 0 25px 60px rgba(0,0,0,.4);
            display: flex;
        }

        /* ── Left panel ───────────────────────────── */
        .auth-panel-left {
            flex: 1;
            background: linear-gradient(160deg, var(--ssbs-blue-dark) 0%, var(--ssbs-blue) 60%, var(--ssbs-green) 100%);
            padding: 48px 40px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            text-align: center;
            position: relative;
            overflow: hidden;
        }

        .auth-panel-left::before {
            content: '';
            position: absolute;
            inset: 0;
            background: url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23ffffff' fill-opacity='0.03'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E");
        }

        .auth-panel-left .emblem {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            background: rgba(255,255,255,.12);
            border: 3px solid rgba(255,255,255,.25);
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 24px;
            font-size: 48px;
            position: relative;
            z-index: 1;
        }

        .auth-panel-left h2 {
            color: var(--white);
            font-size: 1.4rem;
            font-weight: 700;
            margin-bottom: 8px;
            position: relative;
            z-index: 1;
        }

        .auth-panel-left .sub {
            color: rgba(255,255,255,.75);
            font-size: .875rem;
            margin-bottom: 32px;
            position: relative;
            z-index: 1;
        }

        .flag-bar {
            display: flex;
            height: 8px;
            width: 80%;
            border-radius: 4px;
            overflow: hidden;
            margin: 0 auto 32px;
            position: relative;
            z-index: 1;
        }
        .flag-bar span { flex: 1; }
        .flag-bar .f-black  { background: #000000; }
        .flag-bar .f-red    { background: #DD1C1A; }
        .flag-bar .f-green  { background: #007A3D; }
        .flag-bar .f-blue   { background: #003893; }

        .feature-item {
            background: rgba(255,255,255,.08);
            border: 1px solid rgba(255,255,255,.12);
            border-radius: 12px;
            padding: 14px 16px;
            margin-bottom: 12px;
            display: flex;
            align-items: center;
            gap: 12px;
            text-align: left;
            position: relative;
            z-index: 1;
            width: 100%;
        }
        .feature-item i {
            font-size: 20px;
            color: var(--ssbs-gold-light);
            flex-shrink: 0;
        }
        .feature-item .feature-text small {
            display: block;
            color: var(--white);
            font-weight: 600;
            font-size: .8rem;
        }
        .feature-item .feature-text span {
            font-size: .72rem;
            color: rgba(255,255,255,.6);
        }

        /* ── Right panel ──────────────────────────── */
        .auth-panel-right {
            flex: 1;
            background: var(--white);
            padding: 48px 44px;
            display: flex;
            flex-direction: column;
            justify-content: center;
        }

        .auth-panel-right h3 {
            color: var(--ssbs-blue);
            font-size: 1.5rem;
            font-weight: 700;
            margin-bottom: 4px;
        }
        .auth-panel-right .welcome-sub {
            color: var(--text-muted);
            font-size: .875rem;
            margin-bottom: 28px;
        }

        /* ── Form elements ────────────────────────── */
        .form-label {
            color: var(--text-dark);
            font-weight: 600;
            font-size: .85rem;
            margin-bottom: 6px;
        }

        .input-group-text {
            background: #f8fafc;
            border: 2px solid var(--border);
            border-right: none;
            color: var(--ssbs-blue);
        }

        .form-control {
            border: 2px solid var(--border);
            border-left: none;
            padding: 10px 14px;
            font-size: .9rem;
            color: var(--text-dark);
            transition: border-color .2s;
        }
        .form-control:focus {
            border-color: var(--ssbs-blue);
            box-shadow: none;
        }
        .form-control:focus ~ .input-group-text,
        .input-group:focus-within .input-group-text {
            border-color: var(--ssbs-blue);
        }
        .input-group:focus-within .input-group-text {
            border-color: var(--ssbs-blue);
        }

        .btn-signin {
            background: linear-gradient(135deg, var(--ssbs-blue) 0%, var(--ssbs-blue-light) 100%);
            border: none;
            color: var(--white);
            font-weight: 700;
            font-size: .95rem;
            padding: 12px;
            border-radius: 8px;
            width: 100%;
            transition: all .25s;
            letter-spacing: .3px;
        }
        .btn-signin:hover {
            background: linear-gradient(135deg, var(--ssbs-blue-dark) 0%, var(--ssbs-blue) 100%);
            transform: translateY(-1px);
            box-shadow: 0 6px 20px rgba(26,58,107,.35);
            color: var(--white);
        }
        .btn-signin:disabled {
            opacity: .75;
            transform: none;
        }

        .btn-toggle-pw {
            border: 2px solid var(--border);
            border-left: none;
            background: #f8fafc;
            color: var(--text-muted);
        }
        .btn-toggle-pw:hover { color: var(--ssbs-blue); background: #f0f4f8; }

        /* ── Alert ────────────────────────────────── */
        .alert-ssbs-error {
            background: #fff1f0;
            border: 1px solid #ffa39e;
            border-left: 4px solid var(--ssbs-red);
            color: #820014;
            border-radius: 8px;
            padding: 12px 16px;
            font-size: .875rem;
            display: flex;
            align-items: flex-start;
            gap: 10px;
        }

        /* ── Divider ──────────────────────────────── */
        .divider {
            border: none;
            border-top: 1px solid var(--border);
            margin: 20px 0;
        }

        /* ── Info box ─────────────────────────────── */
        .info-box {
            background: #f0f6ff;
            border: 1px solid #c5d8f8;
            border-radius: 10px;
            padding: 14px 16px;
            font-size: .78rem;
            color: #374151;
        }
        .info-box .info-title {
            font-weight: 700;
            color: var(--ssbs-blue);
            margin-bottom: 6px;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        /* ── Footer ───────────────────────────────── */
        .auth-footer {
            text-align: center;
            margin-top: 24px;
            font-size: .78rem;
            color: var(--text-muted);
        }
        .auth-footer a { color: var(--ssbs-blue); text-decoration: none; }
        .auth-footer a:hover { text-decoration: underline; }

        /* ── Responsive ───────────────────────────── */
        @media (max-width: 767px) {
            .auth-card { flex-direction: column; border-radius: 14px; }
            .auth-panel-left { padding: 32px 24px; }
            .auth-panel-right { padding: 32px 24px; }
            .auth-panel-left .feature-item { display: none; }
        }
    </style>
</head>
<body>

<div class="auth-card">

    <!-- ── Left panel ──────────────────────────────────────── -->
    <div class="auth-panel-left">
        <div class="emblem">🏛️</div>

        <h2>South Sudan Bureau<br>of Standards</h2>
        <p class="sub">Integrated Standards &amp; Compliance<br>Management System (SSBS-ISCMS)</p>

        <!-- South Sudan flag colours -->
        <div class="flag-bar">
            <span class="f-black"></span>
            <span class="f-red"></span>
            <span class="f-green"></span>
            <span class="f-blue"></span>
        </div>

        <div class="feature-item">
            <i class="ri-shield-star-line"></i>
            <div class="feature-text">
                <small>Product Certification</small>
                <span>Issue &amp; manage conformity certificates</span>
            </div>
        </div>
        <div class="feature-item">
            <i class="ri-search-2-line"></i>
            <div class="feature-text">
                <small>Inspection Management</small>
                <span>Schedule, conduct &amp; track inspections</span>
            </div>
        </div>
        <div class="feature-item">
            <i class="ri-flask-line"></i>
            <div class="feature-text">
                <small>Laboratory Services</small>
                <span>Sample testing &amp; result management</span>
            </div>
        </div>
        <div class="feature-item">
            <i class="ri-ship-line"></i>
            <div class="feature-text">
                <small>Import/Export Control</small>
                <span>Border compliance &amp; clearance permits</span>
            </div>
        </div>
    </div>

    <!-- ── Right panel ─────────────────────────────────────── -->
    <div class="auth-panel-right">
        <h3>Welcome Back</h3>
        <p class="welcome-sub">Sign in to your SSBS-ISCMS account</p>

        <?php if (!empty($error_message)): ?>
            <div class="alert-ssbs-error mb-4" role="alert">
                <i class="ri-error-warning-line" style="font-size:18px; flex-shrink:0; margin-top:1px"></i>
                <span><?php echo htmlspecialchars($error_message); ?></span>
            </div>
        <?php endif; ?>

        <form id="login-form" method="POST" action="login.php" novalidate autocomplete="off">
            <!-- Hidden CSRF token -->
            <input type="hidden" name="csrf_token" value="<?php
                if (empty($_SESSION['csrf_token'])) {
                    $_SESSION['csrf_token'] = bin2hex(random_bytes(16));
                }
                echo htmlspecialchars($_SESSION['csrf_token']);
            ?>">

            <!-- Identifier -->
            <div class="mb-3">
                <label for="identifier" class="form-label"><?php echo htmlspecialchars($login_id_label); ?></label>
                <div class="input-group">
                    <span class="input-group-text"><i class="ri-user-3-line"></i></span>
                    <input type="text"
                           class="form-control"
                           id="identifier"
                           name="identifier"
                           placeholder="<?php echo htmlspecialchars($login_id_placeholder); ?>"
                           value="<?php echo isset($_POST['identifier']) ? htmlspecialchars($_POST['identifier']) : ''; ?>"
                           required
                           autofocus>
                </div>
            </div>

            <!-- Password -->
            <div class="mb-3">
                <div class="d-flex justify-content-between align-items-center mb-1">
                    <label for="password" class="form-label mb-0">Password</label>
                    <a href="forgot_password.php" class="text-decoration-none" style="font-size:.8rem; color:var(--ssbs-blue)">
                        <i class="ri-lock-unlock-line me-1"></i>Forgot password?
                    </a>
                </div>
                <div class="input-group">
                    <span class="input-group-text"><i class="ri-lock-2-line"></i></span>
                    <input type="password"
                           class="form-control"
                           id="password"
                           name="password"
                           placeholder="Enter your password"
                           required>
                    <button class="btn btn-toggle-pw" type="button" id="toggle-pw" tabindex="-1">
                        <i class="ri-eye-line" id="pw-icon"></i>
                    </button>
                </div>
            </div>

            <!-- Remember me -->
            <div class="form-check mb-4">
                <input class="form-check-input" type="checkbox" id="remember" name="remember" value="1">
                <label class="form-check-label" for="remember" style="font-size:.85rem; color:var(--text-muted)">
                    Keep me signed in on this device
                </label>
            </div>

            <button type="submit" class="btn-signin" id="signin-btn">
                <i class="ri-login-circle-line me-2"></i>Sign In
            </button>
        </form>

        <hr class="divider">

        <div class="info-box">
            <div class="info-title">
                <i class="ri-information-line"></i> Access Levels
            </div>
            <div class="row g-1">
                <div class="col-6">🏛️ <strong>SSBS Staff</strong> — Admin, Certifiers, Inspectors</div>
                <div class="col-6">🔬 <strong>Technical</strong> — Lab Officers, Reviewers</div>
                <div class="col-6">⚖️ <strong>Enforcement</strong> — Enforcement &amp; Market Officers</div>
                <div class="col-6">🏢 <strong>Clients</strong> — Industry &amp; Trade Organisations</div>
            </div>
        </div>

        <div class="auth-footer">
            <p class="mb-1">
                &copy; <?php echo date('Y'); ?> South Sudan Bureau of Standards (SSBS).
                All rights reserved.
            </p>
            <p class="mb-0">
                Need help? <a href="mailto:support@ssbs.gov.ss">support@ssbs.gov.ss</a>
                &nbsp;|&nbsp; <a href="tel:+211920000000">+211-920-000-000</a>
            </p>
        </div>
    </div>

</div><!-- /.auth-card -->

<script src="assets/libs/bootstrap/js/bootstrap.bundle.min.js"></script>
<script>
const LOGIN_HAS_USERNAME = <?php echo $login_has_username ? 'true' : 'false'; ?>;
// Password visibility toggle
document.getElementById('toggle-pw').addEventListener('click', function () {
    const pw   = document.getElementById('password');
    const icon = document.getElementById('pw-icon');
    if (pw.type === 'password') {
        pw.type    = 'text';
        icon.className = 'ri-eye-off-line';
    } else {
        pw.type    = 'password';
        icon.className = 'ri-eye-line';
    }
});

// Client-side validation + loading state
const form      = document.getElementById('login-form');
const signinBtn = document.getElementById('signin-btn');
let submitting  = false;

form.addEventListener('submit', function (e) {
    if (submitting) { e.preventDefault(); return; }

    const id = document.getElementById('identifier').value.trim();
    const pw = document.getElementById('password').value;

    if (!id || !pw) {
        e.preventDefault();
        Swal.fire({
            icon: 'warning',
            title: 'Required Fields',
            text: LOGIN_HAS_USERNAME
                ? 'Please enter your email or username and password.'
                : 'Please enter your email and password.',
            confirmButtonColor: '#1a3a6b'
        });
        return;
    }

    submitting = true;
    signinBtn.disabled = true;
    signinBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2" role="status"></span>Signing in…';
});

// Re-enable on back navigation
window.addEventListener('pageshow', function () {
    submitting = false;
    signinBtn.disabled = false;
    signinBtn.innerHTML = '<i class="ri-login-circle-line me-2"></i>Sign In';
});

// Logout success notice
const params = new URLSearchParams(window.location.search);
if (params.get('logout') === '1') {
    Swal.fire({
        icon: 'success',
        title: 'Signed Out',
        text: 'You have been securely signed out.',
        timer: 2500,
        showConfirmButton: false,
        confirmButtonColor: '#1a3a6b'
    });
}

// Clear password before page unload (security)
window.addEventListener('beforeunload', function () {
    document.getElementById('password').value = '';
});
</script>

</body>
</html>
