<?php

declare(strict_types=1);

require_once __DIR__ . '/../includes/bootstrap.php';

$config = require __DIR__ . '/../config/config.php';

auth_start_session();

if (auth_is_logged_in()) {
    header('Location: ' . auth_default_dashboard_path());
    exit;
}

$title = 'Login';

$email = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim((string)($_POST['email'] ?? ''));
    $password = (string)($_POST['password'] ?? '');

    if ($email === '' || $password === '') {
        $error = 'Email and password are required.';
    } else {
        try {
            $pdo = Database::pdo();
            $stmt = $pdo->prepare('SELECT user_id, email, password_hash, full_name, user_type, is_active FROM users WHERE email = :email LIMIT 1');
            $stmt->execute(['email' => $email]);
            $user = $stmt->fetch();

            if (!$user || (int)$user['is_active'] !== 1 || !auth_verify_password($password, (string)$user['password_hash'])) {
                $error = 'Invalid credentials.';
            } else {
                auth_login($user);

                $pdo->prepare('UPDATE users SET last_login = CURRENT_TIMESTAMP WHERE user_id = :id')->execute(['id' => (int)$user['user_id']]);

                header('Location: ' . auth_default_dashboard_path());
                exit;
            }
        } catch (Throwable $e) {
            $error = 'Login failed: ' . $e->getMessage();
        }
    }
}

ob_start();
?>
<div class="mx-auto max-w-md">
    <div class="rounded-xl border bg-white p-6">
        <h1 class="text-xl font-semibold">Sign in</h1>
        <p class="mt-1 text-sm text-slate-600">Use your account email and password.</p>

        <?php if ($error !== ''): ?>
            <div class="mt-4 rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
                <?= e($error) ?>
            </div>
        <?php endif; ?>

        <form class="mt-6 space-y-4" method="post" action="">
            <div>
                <label class="block text-sm font-medium" for="email">Email</label>
                <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-slate-900" id="email" name="email" type="email" value="<?= e($email) ?>" required>
            </div>
            <div>
                <label class="block text-sm font-medium" for="password">Password</label>
                <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-slate-900" id="password" name="password" type="password" required>
            </div>

            <button class="w-full rounded-lg bg-slate-900 px-4 py-2 text-sm font-medium text-white hover:bg-slate-800" type="submit">Login</button>
        </form>
    </div>
</div>
<?php
$content = ob_get_clean();

require __DIR__ . '/../includes/layout.php';
