<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../lib/auth.php';
require_once __DIR__ . '/../lib/csrf.php';

if (isLoggedIn()) {
    header('Location: /dashboard/dashboard.php');
    exit;
}

$token = trim($_GET['token'] ?? '');
$error = '';
$done  = false;

// Validate token on page load
if ($token === '') {
    header('Location: /login/forgot-password.php');
    exit;
}

$tokenEmail = validatePasswordResetToken($token);
if ($tokenEmail === null) {
    $error = 'This reset link is invalid or has expired. Please request a new one.';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $tokenEmail !== null) {
    if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
        $error = 'Invalid request. Please try again.';
    } else {
        $password  = $_POST['password']         ?? '';
        $password2 = $_POST['password_confirm'] ?? '';

        if (strlen($password) < 8) {
            $error = 'Password must be at least 8 characters.';
        } elseif ($password !== $password2) {
            $error = 'Passwords do not match.';
        } else {
            if (resetPassword($token, $password)) {
                $done = true;
            } else {
                $error = 'This reset link is invalid or has expired. Please request a new one.';
            }
        }
    }
}

$pageTitle = 'Reset Password';
include __DIR__ . '/_head.php';
?>

<div class="container">
    <div class="row justify-content-center">
        <div class="col-xl-10 col-lg-12 col-md-9">
            <div class="card o-hidden border-0 shadow-lg my-5">
                <div class="card-body p-0">
                    <div class="row">
                        <div class="col-lg-6 d-none d-lg-block bg-login-image"></div>
                        <div class="col-lg-6">
                            <div class="p-5">
                                <div class="text-center mb-4">
                                    <h1 class="h4 text-gray-900">Reset Your Password</h1>
                                </div>

                                <?php if ($done): ?>
                                    <div class="alert alert-success" role="alert">
                                        Your password has been reset.
                                        <a href="/login/login.php?reset=1">Click here to log in.</a>
                                    </div>

                                <?php elseif ($error !== '' && $tokenEmail === null): ?>
                                    <div class="alert alert-danger"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></div>
                                    <div class="text-center">
                                        <a href="/login/forgot-password.php">Request a new reset link</a>
                                    </div>

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

                                    <form method="POST" action="/login/reset-password.php?token=<?= urlencode($token) ?>" novalidate>
                                        <input type="hidden" name="csrf_token" value="<?= generateCsrfToken() ?>">

                                        <div class="mb-3">
                                            <input type="password" name="password" class="form-control form-control-user"
                                                   placeholder="New Password (min 8 chars)" required autofocus>
                                        </div>
                                        <div class="mb-3">
                                            <input type="password" name="password_confirm" class="form-control form-control-user"
                                                   placeholder="Confirm New Password" required>
                                        </div>
                                        <button type="submit" class="btn btn-success btn-user w-100 mb-3">
                                            Set New Password
                                        </button>
                                    </form>
                                <?php endif; ?>

                                <hr>
                                <div class="text-center">
                                    <a class="small" href="/login/login.php">Back to Login</a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include __DIR__ . '/_foot.php'; ?>
