<?php
require_once __DIR__ . '/../includes/init.php';

if (isLoggedIn()) {
    redirect(BASE_URL . '/modules/dashboard/index.php');
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!validateCsrfToken($_POST['csrf_token'] ?? '')) {
        $error = 'Invalid request. Please try again.';
    } else {
        $username = trim($_POST['username'] ?? '');
        $password = trim($_POST['password'] ?? '');

        if ($username === '' || $password === '') {
            $error = 'Please enter username and password.';
        } else {
            try {
                $db   = getDBConnection();
                $user = dbRow($db, "SELECT * FROM users WHERE username = ? LIMIT 1", [$username]);

                if ($user && $user['is_active'] && password_verify($password, $user['password'])) {
                    // Regenerate session on login
                    session_regenerate_id(true);

                    $_SESSION['user_id']   = $user['id'];
                    $_SESSION['full_name'] = $user['full_name'];
                    $_SESSION['username']  = $user['username'];
                    $_SESSION['role']      = $user['role'];
                    $_SESSION['division']  = $user['division'];
                    $_SESSION['is_active'] = (bool)$user['is_active'];
                    $_SESSION['_init']     = time();

                    redirect(BASE_URL . '/modules/dashboard/index.php');
                } elseif ($user && !$user['is_active']) {
                    $error = 'Your account has been disabled. Contact administrator.';
                } else {
                    $error = 'Invalid username or password.';
                }
            } catch (PDOException $e) {
                $error = 'Database error. Please try again.';
            }
        }
    }
}

// Disabled account redirect message
if (isset($_GET['err']) && $_GET['err'] === 'disabled') {
    $error = 'Your account is disabled. Contact the administrator.';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login — <?= APP_NAME ?></title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <link rel="stylesheet" href="../assets/css/style.css">
</head>
<body>
<div class="auth-page">
    <div class="auth-box" style="max-width:420px;width:100%;">

        <!-- Logo / Brand -->
        <div class="text-center mb-2">
            <div class="auth-logo-wrap">
                <i class="bi bi-lightning-charge-fill" style="font-size:2.2rem;color:var(--erp-primary);"></i>
            </div>
            <h4 class="fw-bold mb-0" style="color:var(--erp-primary);"><?= APP_NAME ?></h4>
            <p class="text-muted" style="font-size:.82rem;"><?= APP_FULL ?></p>
        </div>

        <?php if ($error): ?>
        <div class="alert alert-danger d-flex align-items-center gap-2 py-2" style="font-size:.88rem;">
            <i class="bi bi-exclamation-circle-fill flex-shrink-0"></i>
            <?= h($error) ?>
        </div>
        <?php endif; ?>

        <form method="POST" novalidate>
            <input type="hidden" name="csrf_token" value="<?= generateCsrfToken() ?>">

            <div class="mb-3">
                <label class="form-label fw-semibold" style="font-size:.88rem;">Username</label>
                <div class="input-group">
                    <span class="input-group-text"><i class="bi bi-person-fill text-muted"></i></span>
                    <input type="text" name="username" class="form-control"
                           placeholder="Enter username"
                           value="<?= h($_POST['username'] ?? '') ?>"
                           autocomplete="username" required autofocus>
                </div>
            </div>

            <div class="mb-3">
                <label class="form-label fw-semibold" style="font-size:.88rem;">Password</label>
                <div class="input-group">
                    <span class="input-group-text"><i class="bi bi-lock-fill text-muted"></i></span>
                    <input type="password" name="password" id="passwordInput" class="form-control"
                           placeholder="Enter password" autocomplete="current-password" required>
                    <button type="button" class="input-group-text bg-white border-start-0"
                            onclick="togglePass()" style="cursor:pointer;">
                        <i class="bi bi-eye" id="passToggleIcon"></i>
                    </button>
                </div>
            </div>

            <button type="submit" class="btn btn-erp w-100 mt-1">
                <i class="bi bi-box-arrow-in-right me-2"></i>Login
            </button>
        </form>

        <div class="text-center mt-2">
            <a href="<?= BASE_URL ?>/auth/login_otp.php"
               class="btn w-100" style="background:#25d366;color:#fff;border-radius:8px;font-size:.9rem;min-height:44px;display:flex;align-items:center;justify-content:center;gap:8px;">
                <i class="bi bi-whatsapp"></i>WhatsApp OTP se Login karo
            </a>
        </div>
    </div>
</div>
<script>
function togglePass() {
    const inp = document.getElementById('passwordInput');
    const ico = document.getElementById('passToggleIcon');
    if (inp.type === 'password') { inp.type = 'text'; ico.className = 'bi bi-eye-slash'; }
    else { inp.type = 'password'; ico.className = 'bi bi-eye'; }
}
</script>
</body>
</html>
