<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Allow only POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => 'error', 'message' => 'This endpoint accepts POST requests only.']);
    exit();
}

// DB Connection
$conn = new mysqli("localhost", "gobolcha_gobolchain", "@Jibala1997", "gobolcha_gobolchain");
if ($conn->connect_error) {
    echo json_encode(['status' => 'error', 'message' => 'Database connection failed.']);
    exit();
}

// Get POST data
$token = isset($_POST['token']) ? trim($_POST['token']) : '';
$newPassword = isset($_POST['password']) ? trim($_POST['password']) : '';

if (empty($token) || empty($newPassword)) {
    echo json_encode(['status' => 'error', 'message' => 'All fields are required.']);
    exit();
}

// Find token in DB - use bind_result instead of get_result
$stmt = $conn->prepare("SELECT email, expires_at FROM password_resets WHERE token = ?");
$stmt->bind_param("s", $token);
$stmt->execute();
$stmt->bind_result($email, $expiresAt);

if (!$stmt->fetch()) {
    // Token not found
    echo json_encode(['status' => 'error', 'message' => 'Invalid or expired token.']);
    exit();
}

$stmt->close();

// Check if token expired
if (strtotime($expiresAt) < time()) {
    // Token expired, delete it
    $delete = $conn->prepare("DELETE FROM password_resets WHERE token = ?");
    $delete->bind_param("s", $token);
    $delete->execute();
    $delete->close();

    echo json_encode(['status' => 'error', 'message' => 'Token has expired. Please request a new reset link.']);
    exit();
}

// Hash and update password
$hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
$update = $conn->prepare("UPDATE users SET password = ? WHERE email = ?");
$update->bind_param("ss", $hashedPassword, $email);
$update->execute();
$update->close();

// Delete the reset token
$delete = $conn->prepare("DELETE FROM password_resets WHERE token = ?");
$delete->bind_param("s", $token);
$delete->execute();
$delete->close();

// Send JSON response
echo json_encode([
    "status" => "success",
    "message" => "Password successfully reset. Redirecting..."
]);
exit();
?>