<?php
require_once 'config/database.php';
require_once 'config/auth.php';
require_once 'includes/functions.php';

if (isLoggedIn()) {
    header('Location: ' . getDashboardUrl());
    exit;
}

$token = $_GET['token'] ?? '';
$error = '';
$success = '';

if (empty($token)) {
    $error = 'Invalid reset token.';
} elseif ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $password = $_POST['password'] ?? '';
    $confirmPassword = $_POST['confirm_password'] ?? '';

    if (empty($password)) {
        $error = 'Password is required';
    } elseif (strlen($password) < 8) {
        $error = 'Password must be at least 8 characters long';
    } elseif ($password !== $confirmPassword) {
        $error = 'Passwords do not match';
    } else {
        if (resetPassword($token, $password)) {
            $success = 'Password reset successful! You can now <a href="login.php?reset=1">login</a> with your new password.';
        } else {
            $error = 'Invalid or expired reset token.';
        }
    }
}

$page_title = 'Reset Password - Mutalex Academy';
include 'includes/header.php';
?>

<section class="login-section">
    <div class="container">
        <div class="login-card">
            <div class="login-header">
                <h1>Reset Your Password</h1>
                <p>Enter your new password below</p>
            </div>

            <?php if ($error): ?>
                <div class="alert alert-error">
                    <?php echo htmlspecialchars($error); ?>
                </div>
            <?php endif; ?>

            <?php if ($success): ?>
                <div class="alert alert-success">
                    <?php echo $success; ?>
                </div>
            <?php endif; ?>

            <?php if (empty($success) && !empty($token)): ?>
            <form method="POST" class="login-form">
                <div class="form-group">
                    <label for="password">New Password</label>
                    <input type="password" id="password" name="password" required minlength="8">
                </div>

                <div class="form-group">
                    <label for="confirm_password">Confirm New Password</label>
                    <input type="password" id="confirm_password" name="confirm_password" required minlength="8">
                </div>

                <button type="submit" class="btn btn-primary btn-full">Reset Password</button>
            </form>
            <?php endif; ?>

            <div class="login-help">
                <p>Remember your password? <a href="login.php">Login here</a></p>
            </div>
        </div>
    </div>
</section>

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