<?php
require_once(__DIR__ . '/../common.php');
require_once(__DIR__ . '/../config.php');

// Function to sanitize input
function sanitize_input($input) {
    return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
}

// Function to enforce password strength
function is_strong_password($password) {
    $uppercase = preg_match('@[A-Z]@', $password);
    $lowercase = preg_match('@[a-z]@', $password);
    $number    = preg_match('@[0-9]@', $password);
    $specialChars = preg_match('@[^\w]@', $password);
    return $uppercase && $lowercase && $number && $specialChars && strlen($password) >= 8;
}

if (session_status() === PHP_SESSION_NONE) {
    session_start(); // Start session
}

$msg = '';
$error = '';
$errors = array();
$success = false; // Track whether the reset is successful

// Check if a token exists in the URL
if (isset($_GET['token'])) {
    $token = sanitize_input($_GET['token']);

    // Check if token is valid and not expired
    $query = "SELECT user_id, expiry FROM password_resets WHERE token = :token";
    $stmt = $pdo->prepare($query);
    $stmt->bindParam(':token', $token, PDO::PARAM_STR);
    $stmt->execute();
    $result = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($result) {
        $user_id = $result['user_id'];
        $expiry = $result['expiry'];

        // Check if the token has expired
        if (strtotime($expiry) > time()) {
            // Token is valid, handle the password reset form submission
            if (isset($_POST['reset_password'])) {
                // Validate new passwords
                $new_password = sanitize_input($_POST['new_password']);
                $confirm_password = sanitize_input($_POST['confirm_password']);

                // Check if password is strong
                if (!is_strong_password($new_password)) {
                    $error = 'Password must meet the requirements below.';
                } elseif ($new_password !== $confirm_password) {
                    $error = 'Passwords do not match.';
                } else {
                    // Hash the new password
                    $hashed_password = password_hash($new_password, PASSWORD_BCRYPT);

                    // Update the password in the users table
                    $update_query = "UPDATE sm_editors SET password = :password WHERE id = :user_id";
                    $update_stmt = $pdo->prepare($update_query);
                    $update_stmt->bindParam(':password', $hashed_password, PDO::PARAM_STR);
                    $update_stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
                    $update_stmt->execute();

                    // Delete the token after password is reset
                    $delete_query = "DELETE FROM password_resets WHERE token = :token";
                    $delete_stmt = $pdo->prepare($delete_query);
                    $delete_stmt->bindParam(':token', $token, PDO::PARAM_STR);
                    $delete_stmt->execute();

                    // Success message with login link
                    $msg = 'Your password has been successfully reset!';
                    $success = true; // Mark as successful
                }
            }
        } else {
            $error = 'The token has expired. Please request a new password reset.';
        }
    } else {
        $error = 'Invalid token. Please request a new password reset.';
    }
} else {
    $error = 'No token provided.';
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reset Password</title>
    <link rel="stylesheet" href="./../css/style.css"> <!-- Link to your CSS file for styling -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css"> <!-- Font Awesome for Icons -->
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f0f0f0;
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100vh;
            margin: 0;
        }
        .container {
            background: #ffffff;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0px 0px 15px rgba(0, 0, 0, 0.2);
            width: 100%;
            max-width: 500px;
        }
        h1 {
            text-align: center;
            color: #333;
        }
        .message {
            margin-bottom: 20px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input[type="password"] {
            width: calc(100% - 20px);
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
            font-size: 16px;
        }
        .button-primary {
            background-color: #007BFF;
            color: #fff;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            width: 100%;
            transition: background-color 0.3s;
            text-align: center;
            text-decoration: none;
            display: inline-block;
        }
        .button-primary:hover {
            background-color: #0056b3;
        }
        .error {
            color: red;
            font-size: 14px;
        }
        .msg {
            color: green;
            font-size: 14px;
        }
        .hint {
            font-size: 12px;
            color: #666;
            margin-top: 5px;
        }
    </style>
    <script>
        // Client-side password strength validation
        function validatePassword() {
            var password = document.getElementById("new_password").value;
            var errorDiv = document.getElementById("password-error");
            var strongPasswordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[^\w\d\s:])([A-Za-z\d@$!%*?&]|[^ ]){8,}$/;

            if (!strongPasswordRegex.test(password)) {
                errorDiv.innerHTML = "Password must be at least 8 characters long, contain at least one uppercase letter, one lowercase letter, one number, and one special character.";
                return false;
            } else {
                errorDiv.innerHTML = "";
                return true;
            }
        }
    </script>
</head>
<body>
<div class="container">
    <h1><i class="fas fa-unlock-alt"></i> Reset Password</h1>
    <div class="message">
        <span class="error"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></span>
        <span class="msg"><?= htmlspecialchars($msg, ENT_QUOTES, 'UTF-8') ?></span>
    </div>

    <!-- Show password reset form if not successful, otherwise show the confirmation message with login button -->
    <?php if ($success): ?>
        <!-- Success message and login button -->
        <a href="login.php" class="button-primary">Click here to login</a>
    <?php elseif (isset($_GET['token']) && $result): ?>
        <!-- Form for resetting the password if token is valid and form hasn't been submitted -->
        <form method="post" action="" onsubmit="return validatePassword();">
            <div class="form-group">
                <label for="new_password">New Password:</label>
                <input type="password" id="new_password" name="new_password" required>
                <div id="password-error" class="error"></div>
                <!-- Password strength hint -->
                <div class="hint">
                    Your password must meet the following requirements:
                    <ul>
                        <li>At least 8 characters long</li>
                        <li>Contains at least one uppercase letter</li>
                        <li>Contains at least one lowercase letter</li>
                        <li>Contains at least one number</li>
                        <li>Contains at least one special character (e.g., @, #, $)</li>
                    </ul>
                </div>
            </div>
            <div class="form-group">
                <label for="confirm_password">Confirm New Password:</label>
                <input type="password" id="confirm_password" name="confirm_password" required>
            </div>
            <input name="reset_password" value="Reset Password" type="submit" class="button-primary" />
        </form>
    <?php endif; ?>
</div>
</body>
</html>
