<?php
define('SECURE_ACCESS', true);
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

redirectIfLoggedIn();

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

if (empty($token)) {
    $_SESSION['flash_error'] = "Invalid or missing password reset token.";
    header("Location: login");
    exit();
}

try {
    // Look up the token in the database
    $stmt = $pdo->prepare("SELECT id, username, reset_token_expires FROM users WHERE reset_token = ?");
    $stmt->execute([$token]);
    $user = $stmt->fetch();
    
    if (!$user || strtotime($user['reset_token_expires']) < time()) {
        $_SESSION['flash_error'] = "The password reset token is invalid or has expired.";
        header("Location: login");
        exit();
    }
} catch (PDOException $e) {
    $_SESSION['flash_error'] = "An error occurred: " . $e->getMessage();
    header("Location: login");
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $error = "Security check failed (CSRF). Please try again.";
    } else {
        $new_password = $_POST['new_password'] ?? '';
        $confirm_password = $_POST['confirm_password'] ?? '';
        
        if (empty($new_password) || empty($confirm_password)) {
            $error = "All fields are required.";
        } elseif ($new_password !== $confirm_password) {
            $error = "New password and confirmation password do not match.";
        } elseif (strlen($new_password) < 6) {
            $error = "Password must be at least 6 characters long.";
        } else {
            try {
                // Update password and clear reset token
                $new_hash = password_hash($new_password, PASSWORD_DEFAULT);
                $stmt_update = $pdo->prepare("
                    UPDATE users 
                    SET password = ?, reset_token = NULL, reset_token_expires = NULL 
                    WHERE id = ?
                ");
                $stmt_update->execute([$new_hash, $user['id']]);
                
                $_SESSION['flash_success'] = "Password has been reset successfully. You can now log in.";
                header("Location: login");
                exit();
            } catch (PDOException $e) {
                $error = "Failed to update password: " . $e->getMessage();
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>RENENET EDUCARE</title>
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        html { font-size: 16px; }
        @media (max-width: 576px) { html { font-size: 14px; } }
        body { font-size: calc(14px + 0.2vw); background-color: #f8f9fa; }
        .reset-card { border: none; border-radius: 12px; }
    </style>
</head>
<body class="d-flex align-items-center min-vh-100 py-4">
    <div class="container-fluid px-md-5">
        <div class="row justify-content-center">
            <div class="col-12 col-sm-10 col-md-8 col-lg-6 col-xl-5">
                <div class="card shadow-lg reset-card p-4">
                    <div class="card-body">
                        <div class="text-center mb-4">
                            <i class="bi bi-key-fill text-success mb-2" style="font-size: 3.5rem;"></i>
                            <h2 class="fw-bold mt-2">Reset Password</h2>
                            <p class="text-muted">Enter a new secure password for your account, <strong><?php echo htmlspecialchars($user['username']); ?></strong>.</p>
                        </div>

                        <?php if (!empty($error)): ?>
                            <div class="alert alert-danger shadow-sm border-0 mb-3" role="alert">
                                <i class="bi bi-x-circle-fill me-2"></i>
                                <?php echo htmlspecialchars($error); ?>
                            </div>
                        <?php endif; ?>

                        <form method="POST" action="reset_password" class="needs-validation" novalidate>
                            <input type="hidden" name="csrf_token" value="<?php echo getCSRFToken(); ?>">
                            <input type="hidden" name="token" value="<?php echo htmlspecialchars($token); ?>">
                            
                            <div class="mb-3">
                                <label for="new_password" class="form-label">New Password</label>
                                <div class="input-group">
                                    <span class="input-group-text bg-white text-muted border-end-0"><i class="bi bi-lock-fill"></i></span>
                                    <input type="password" class="form-control border-start-0 ps-0" id="new_password" name="new_password" required minlength="6" placeholder="••••••••">
                                </div>
                            </div>

                            <div class="mb-4">
                                <label for="confirm_password" class="form-label">Confirm Password</label>
                                <div class="input-group">
                                    <span class="input-group-text bg-white text-muted border-end-0"><i class="bi bi-lock-fill"></i></span>
                                    <input type="password" class="form-control border-start-0 ps-0" id="confirm_password" name="confirm_password" required minlength="6" placeholder="••••••••">
                                </div>
                            </div>

                            <div class="d-grid gap-2 mb-3">
                                <button type="submit" class="btn btn-success btn-lg py-2 text-white fw-bold">
                                    <i class="bi bi-check-circle me-2"></i>Update Password
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- Bootstrap JS Bundle -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
