<?php

declare(strict_types=1);

session_start();

require_once __DIR__ . '/config/app.php';
require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/includes/csrf.php';
require_once __DIR__ . '/includes/activity_log.php';

$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['login'])) {
    if (!hash_equals($_SESSION['csrf_token'] ?? '', $_POST['csrf_token'] ?? '')) {
        $message = 'Invalid request. Please try again.';
    } else {
        $email = trim((string)($_POST['email'] ?? ''));
        $password = (string)($_POST['password'] ?? '');

        if (!filter_var($email, FILTER_VALIDATE_EMAIL) || $password === '') {
            $message = 'Invalid email or password.';
        } else {
            $stmt = mysqli_prepare(
                $conn,
                "SELECT id, email, fullname, password, role, zone_name
                 FROM users
                 WHERE email = ?
                   AND status = 'Active'
                 LIMIT 1"
            );

            if (!$stmt) {
                error_log('Login prepare error: ' . mysqli_error($conn));
                $message = 'Unable to sign in at this time.';
            } else {
                mysqli_stmt_bind_param($stmt, 's', $email);
                mysqli_stmt_execute($stmt);

                $result = mysqli_stmt_get_result($stmt);
                $user = mysqli_fetch_assoc($result);

                mysqli_stmt_close($stmt);

                if ($user && password_verify($password, $user['password'])) {
                    session_regenerate_id(true);

                    $_SESSION['user_id'] = (int)$user['id'];
                    $_SESSION['email'] = (string)$user['email'];
                    $_SESSION['fullname'] = (string)$user['fullname'];
                    $_SESSION['role'] = (string)$user['role'];
                    $_SESSION['zone_name'] = (string)($user['zone_name'] ?? '');

                    logActivity(
                        $conn,
                        'Authentication',
                        'Login',
                        'Successful login.'
                    );

                    header('Location: ' . BASE_URL . 'dashboard.php');
                    exit();
                }

                $message = 'Invalid email or password.';
            }
        }
    }
}

include __DIR__ . '/includes/header.php';
?>

<div class="container">
    <div class="row justify-content-center align-items-center" style="height:100vh;">
        <div class="col-md-5">
            <div class="card shadow">
                <div class="card-body p-4">

                    <h2 class="text-center mb-4">
                        School Survey System
                    </h2>

                    <?php if ($message !== ''): ?>
                        <div class="alert alert-danger">
                            <?= htmlspecialchars($message, ENT_QUOTES, 'UTF-8') ?>
                        </div>
                    <?php endif; ?>

                    <form method="post">

                        <input
                            type="hidden"
                            name="csrf_token"
                            value="<?= htmlspecialchars(
                                $_SESSION['csrf_token'],
                                ENT_QUOTES,
                                'UTF-8'
                            ) ?>"
                        >

                        <div class="mb-3">
                            <label for="email" class="form-label">
                                Email Address
                            </label>

                            <input
                                type="email"
                                name="email"
                                id="email"
                                class="form-control"
                                required
                                autocomplete="email"
                            >
                        </div>

                        <div class="mb-3">
                            <label for="password" class="form-label">
                                Password
                            </label>

                            <input
                                type="password"
                                name="password"
                                id="password"
                                class="form-control"
                                required
                                autocomplete="current-password"
                            >
                        </div>

                        <button
                            type="submit"
                            name="login"
                            class="btn btn-primary w-100"
                        >
                            Login
                        </button>

                        <div class="mt-3">
                            <a href="<?= BASE_URL ?>forgot_password.php">
                                Forgot Password?
                            </a>
                        </div>

                        <div class="text-center mt-3">
                            <a href="<?= BASE_URL ?>register.php">
                                Create New Account
                            </a>
                        </div>

                    </form>

                </div>
            </div>
        </div>
    </div>
</div>

<?php include __DIR__ . '/includes/footer.php'; ?>
