<?php
require_once '../core/bootstrap.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: login.php');
    exit();
}

$token = $_POST['token'] ?? '';
$email = $_POST['email'] ?? '';
$password = $_POST['password'] ?? '';
$confirm_password = $_POST['confirm_password'] ?? '';

if (empty($token) || empty($email) || empty($password)) {
    header("Location: reset_password.php?token=$token&email=$email&error=" . urlencode('All fields are required.'));
    exit();
}

if ($password !== $confirm_password) {
    header("Location: reset_password.php?token=$token&email=$email&error=" . urlencode('Passwords do not match.'));
    exit();
}

// Verify Token
$db = new Database();
$db->query("SELECT * FROM password_resets WHERE email = :email AND token = :token AND created_at >= DATE_SUB(NOW(), INTERVAL 1 HOUR)");
$db->bind(':email', $email);
$db->bind(':token', $token);
$resetRequest = $db->single();

if (!$resetRequest) {
    header("Location: reset_password.php?token=$token&email=$email&error=" . urlencode('Invalid or expired token.'));
    exit();
}

// Update Password
$userModel = new User();
$user = $userModel->findByEmail($email);
if ($user) {
    $new_hash = password_hash($password, PASSWORD_DEFAULT);
    $userModel->updatePassword($user->id, $new_hash);
    
    // Delete Token
    $db->query("DELETE FROM password_resets WHERE email = :email");
    $db->bind(':email', $email);
    $db->execute();

    header('Location: login.php?status=password_reset');
} else {
    header("Location: reset_password.php?token=$token&email=$email&error=" . urlencode('User not found.'));
}
exit();