<?php
require_once '../config/db.php';
require_once '../config/auth.php';
require_once '../config/functions.php';

if (isLoggedIn()) {
    header("Location: " . BASE_URL . (isAdmin() ? '/admin/dashboard.php' : '/user/dashboard.php'));
    exit;
}

$error = '';

// CAPTCHA handled by captcha.php (session-based)


if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email    = sanitize($conn, $_POST['email']);
    $password = $_POST['password'];
    $captcha_input  = strtoupper(trim($_POST['captcha'] ?? ''));
    $captcha_answer = $_SESSION['captcha_code'] ?? '';
    unset($_SESSION['captcha_code']); // invalidate after use

    // Regenerate is handled by captcha.php on next load

    if ($captcha_input !== $captcha_answer || empty($captcha_answer)) {
        $error = 'Incorrect CAPTCHA. Please try again.';
    } else {
        $result = $conn->query("SELECT * FROM users WHERE email = '$email'");
        if ($result->num_rows === 1) {
            $user = $result->fetch_assoc();
            if (password_verify($password, $user['password'])) {
                if ($user['role'] === 'admin') {
                    $_SESSION['user_id'] = $user['id'];
                    $_SESSION['name']    = $user['name'];
                    $_SESSION['role']    = $user['role'];
                    $_SESSION['gender']  = $user['gender'];
                    header("Location: " . BASE_URL . "/admin/dashboard.php");
                    exit;
                } elseif (($user['account_status'] ?? 'pending') === 'pending') {
                    $error = 'Your account is pending admin approval. Please wait for activation.';
                } elseif (($user['account_status'] ?? 'pending') === 'rejected') {
                    $error = 'Your account has been rejected. Please contact the administrator.';
                } else {
                    $_SESSION['user_id'] = $user['id'];
                    $_SESSION['name']    = $user['name'];
                    $_SESSION['role']    = $user['role'];
                    $_SESSION['gender']  = $user['gender'];
                    header("Location: " . BASE_URL . "/user/dashboard.php");
                    exit;
                }
            } else {
                $error = 'Invalid email or password.';
            }
        } else {
            $error = 'Invalid email or password.';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login - RELINK</title>
<link rel="stylesheet" href="<?= BASE_URL ?>/assets/css/style.css?v=2">
</head>
<body>
<div class="auth-wrapper" style="background: url('<?= BASE_URL ?>/cyn.png') center/cover no-repeat fixed;">
<div class="auth-card" style="max-width:520px;">
        <div class="auth-logo">
            <div style="display:flex;align-items:center;justify-content:center;gap:12px;margin-bottom:12px">
                <img src="../cyn_logo.png" alt="Cauayan City Hall" style="width:52px;height:52px;object-fit:contain;flex-shrink:0">
                <div style="text-align:left">
                    <h1 style="margin:0">🔗 RELINK</h1>
                    <p style="margin:0;font-size:12px">Lost & Found Management System</p>
                    <p style="margin:0;font-size:11px;color:rgba(255,255,255,.55)">Cauayan City Hall</p>
                </div>
            </div>
        </div>
        <?php if($error): ?><div class="alert alert-danger"><?= htmlspecialchars($error) ?></div><?php endif; ?>
        <form method="POST">
            <div class="form-group">
                <label>Email Address</label>
                <input type="email" name="email" class="form-control" placeholder="Enter your email" required
                       value="<?= htmlspecialchars($_POST['email'] ?? '') ?>">
            </div>
            <div class="form-group">
                <label>Password</label>
                <input type="password" name="password" class="form-control" placeholder="Enter your password" required>
            </div>
            <div class="form-group">
                <label>Security Check — Type the characters you see</label>
                <div style="display:flex;align-items:center;gap:10px;margin-bottom:8px">
                    <img id="captchaImg" src="<?= BASE_URL ?>/auth/captcha.php" alt="CAPTCHA"
                         style="border-radius:6px;cursor:pointer;height:60px"
                         title="Click to refresh">
                    <button type="button" onclick="document.getElementById('captchaImg').src='<?= BASE_URL ?>/auth/captcha.php?r='+Math.random()"
                            style="background:none;border:none;cursor:pointer;font-size:20px;color:rgba(255,255,255,.7)" title="Refresh CAPTCHA">🔄</button>
                </div>
                <input type="text" name="captcha" class="form-control" placeholder="Enter characters above"
                       required autocomplete="off" maxlength="5" style="letter-spacing:4px;text-transform:uppercase">
            </div>
            <button type="submit" class="btn btn-primary btn-block">Sign In</button>
        </form>
        <p style="text-align:center;margin-top:16px;font-size:13px;color:#fff">
            Don't have an account? <a href="<?= BASE_URL ?>/auth/register.php" style="color:#d4f06a;font-weight:600">Register</a>
        </p>
        <p style="text-align:center;margin-top:8px;font-size:12px;color:rgba(255,255,255,.6)">
            <a href="<?= BASE_URL ?>/index.php" style="color:rgba(255,255,255,.6)">← Back to Home</a>
        </p>
    </div>
</div>
</body>
</html>
