<?php
// File: reset-password-handler.php (Final Version)
require_once 'db.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = $_POST['token'];
    $new_password = $_POST['new_password'];
    $confirm_password = $_POST['confirm_password'];

    // 1. Basic Validation: Check if passwords match
    if ($new_password !== $confirm_password) {
        header("Location: reset-password.php?token=$token&error=mismatch");
        exit();
    }

    // 2. Re-validate the token and retrieve the associated email
    $stmt = $conn->prepare("SELECT email FROM password_resets WHERE token = ? AND expires_at > NOW()");
    $stmt->bind_param("s", $token);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $email = $row['email']; // This line is now guaranteed to work

        // 3. Hash the new password securely
        $password_hash = password_hash($new_password, PASSWORD_DEFAULT);

        // 4. Update the user's password in the main `users` table
        $stmt_update = $conn->prepare("UPDATE users SET password_hash = ? WHERE email = ?");
        $stmt_update->bind_param("ss", $password_hash, $email);
        $stmt_update->execute();

        // 5. Delete the used token from the `password_resets` table for security
        $stmt_delete = $conn->prepare("DELETE FROM password_resets WHERE email = ?");
        $stmt_delete->bind_param("s", $email);
        $stmt_delete->execute();

        // 6. Redirect to the login page with a success message
        header("Location: login.php?status=reset_success");
        exit();
    } else {
        // Token is invalid or has expired
        header("Location: reset-password.php?token=$token&error=invalid_token");
        exit();
    }
} else {
    // If not a POST request, redirect to the home page
    header("Location: index.php");
    exit();
}

