<?php
require_once '../src/Database.php';
$conn = Database::getInstance();
$token = isset($_POST['token']) ? trim($_POST['token']) : '';
$newPassword = isset($_POST['new_password']) ? trim($_POST['new_password']) : '';
$confirmPassword = isset($_POST['confirm_password']) ? trim($_POST['confirm_password']) : '';

// Basic validation
if (empty($token) || empty($newPassword) || strlen($newPassword) < 8 || $newPassword !== $confirmPassword) {
    die("Invalid request. Please check all fields.");
}

// Check if token exists and not expired
$stmt = $conn->prepare("SELECT email FROM users WHERE reset_token = ? AND reset_token IS NOT NULL");
$stmt->bind_param("s", $token);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows === 0) {
    echo '
    <div style="
        max-width: 400px;
        margin: 50px auto;
        padding: 20px;
        border: 2px solid #e74c3c;
        background-color: #fcebea;
        color: #c0392b;
        font-family: Arial, sans-serif;
        border-radius: 8px;
        text-align: center;
        box-shadow: 0 0 10px rgba(199, 0, 0, 0.2);
    ">
        <h2 style="margin-bottom: 15px;">Oops!</h2>
        <p>Your password reset link has expired or is invalid.</p>
        <p>Please <a href="login-reg.php?box=reset" style="color: #2980b9; text-decoration: none; font-weight: bold;">request a new password reset</a> to continue.</p>
    </div>';
    exit;
}



$row = $result->fetch_assoc();
$email = $row['email'];

// Hash the new password
$hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);

// Update password and remove token
$updateStmt = $conn->prepare("UPDATE users SET password = ?, reset_token = NULL WHERE email = ?");
$updateStmt->bind_param("ss", $hashedPassword, $email);

if ($updateStmt->execute()) {
    echo '
<div style="
    max-width: 400px;
    margin: 50px auto;
    padding: 20px;
    background-color: #d4edda;
    border: 2px solid #28a745;
    color: #155724;
    font-family: Arial, sans-serif;
    border-radius: 8px;
    text-align: center;
    box-shadow: 0 0 10px rgba(40, 167, 69, 0.2);
">
    <h2 style="margin-bottom: 15px;">Success!</h2>
    <p>Your password has been reset successfully.</p>
    <p><a href="login-reg.php" style="color: #155724; text-decoration: underline; font-weight: bold;">Click here to Login</a></p>
</div>';

} else {
    echo "Something went wrong. Please try again.";
}

$stmt->close();
$updateStmt->close();
$conn->close();
?>
