<?php
session_start();
require_once('common.php'); // Ensure this includes your PDO connection setup
require_once('functions.php');

// Initialize variables
$error = '';
$msg = '';
$token = $_GET['token'] ?? null;

// If there's no token in the URL, display an error
if (!$token) {
    die('Invalid password reset token.');
}

// Handle form submission to reset the password
if (isset($_POST['submit'])) {
    // Validate the new password inputs
    $new_password = trim($_POST['password']);
    $confirm_password = trim($_POST['confirm_password']);

    if (empty($new_password) || empty($confirm_password)) {
        $error = 'Both password fields are required.';
    } elseif ($new_password !== $confirm_password) {
        $error = 'Passwords do not match.';
    } elseif (strlen($new_password) < 8 || !preg_match('/[A-Z]/', $new_password) || !preg_match('/[a-z]/', $new_password) || !preg_match('/[0-9]/', $new_password) || !preg_match('/[^\w]/', $new_password)) {
        $error = 'Password must be at least 8 characters long and contain uppercase, lowercase letters, a number, and a special character.';
    }

    // Proceed if there are no errors
    if (empty($error)) {
        try {
            // Fetch the user based on the reset token and make sure the token is still valid
            $query = "SELECT * FROM sm_poets WHERE reset_token = :token AND token_expiry > NOW()";
            $stmt = $pdo->prepare($query);
            $stmt->bindParam(':token', $token, PDO::PARAM_STR);
            $stmt->execute();
            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($user) {
                // Hash the new password
                $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);

                // Update the user's password, confirm the email, and clear the reset token and expiry
                $update_query = "UPDATE sm_poets 
                                 SET password = :password, reset_token = NULL, token_expiry = NULL, email_confirmed = 1 
                                 WHERE id = :id";
                $update_stmt = $pdo->prepare($update_query);
                $update_stmt->bindParam(':password', $hashed_password, PDO::PARAM_STR);
                $update_stmt->bindParam(':id', $user['id'], PDO::PARAM_INT);
                $update_stmt->execute();

                // Success message
                $msg = 'Your password has been successfully reset and your email has been confirmed. You can now log in.';
            } else {
                // Invalid or expired token
                $error = 'The password reset token is invalid or has expired.';
            }
        } catch (PDOException $e) {
            $error = 'Database error: ' . htmlspecialchars($e->getMessage());
        }
    }
}

// Include header and menu
include_once('header.php');
include_once('menu.php');
?>

<div class="container">
    <div class="form-wrapper">
        <h2>Reset Your Password</h2>
        <span class="error"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></span>
        <span class="msg"><?= htmlspecialchars($msg, ENT_QUOTES, 'UTF-8') ?></span>

        <!-- Display the form if there is no success message -->
        <?php if (empty($msg)) { ?>
        <form method="post" action="reset-password.php?token=<?= htmlspecialchars($token, ENT_QUOTES, 'UTF-8') ?>">
            <!-- New password input -->
            <div class="form-group">
                <label for="password">New Password:</label>
                <input id="password" name="password" type="password" class="form-control" required />
            </div>

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

            <!-- Submit Button -->
            <div class="form-group">
                <input name="submit" value="Reset Password" type="submit" class="btn btn-primary" />
            </div>
        </form>
        <?php } ?>
    </div>
</div>

<?php
// Include footer
include_once('footer.php');
?>

<style>
/* Align the form at the top with some spacing */
.container {
    display: flex;
    justify-content: center;
    padding-top: 50px; /* Adjust this for spacing from the top */
}

.form-wrapper {
    background-color: #ffffff;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0px 0px 15px rgba(0, 0, 0, 0.1);
    width: 400px;
    text-align: center;
}

h2 {
    margin-bottom: 20px;
    color: #333;
}

.form-group {
    margin-bottom: 15px;
    text-align: left;
}

label {
    display: block;
    margin-bottom: 5px;
    font-weight: bold;
    color: #555;
}

input[type="password"] {
    width: 100%;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
    box-sizing: border-box;
}

input[type="submit"] {
    width: 100%;
    padding: 10px;
    background-color: #007bff;
    border: none;
    color: white;
    border-radius: 5px;
    cursor: pointer;
    font-size: 16px;
}

input[type="submit"]:hover {
    background-color: #0056b3;
}

.error {
    color: red;
    font-size: 14px;
    margin-bottom: 10px;
}

.msg {
    color: green;
    font-size: 14px;
    margin-bottom: 10px;
}
</style>
