<?php
// === Allow CORS ===
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

header("Content-Type: application/json");
include '../../dbcon.php';

// Make sure timezone is correct
date_default_timezone_set("Asia/Karachi");

$data = json_decode(file_get_contents("php://input"), true);

$email = mysqli_real_escape_string($conn, $data['email'] ?? '');
$otp = mysqli_real_escape_string($conn, $data['otp'] ?? '');
$new_password = mysqli_real_escape_string($conn, $data['new_password'] ?? '');

if (!$email || !$otp || !$new_password) {
    echo json_encode(["status" => "error", "message" => "All fields required"]);
    exit;
}

$query = "SELECT otp, otp_expires_at FROM users WHERE email='$email' LIMIT 1";
$result = mysqli_query($conn, $query);

if (mysqli_num_rows($result) === 1) {
    $row = mysqli_fetch_assoc($result);
    $now = date("Y-m-d H:i:s");

    // ✅ Compare safely (trim + string compare)
    if (trim($row['otp']) == trim((string) $otp)) {
        if ($row['otp_expires_at'] > $now) {
            $hashed = password_hash($new_password, PASSWORD_BCRYPT);
            mysqli_query($conn, "UPDATE users SET password='$hashed', otp=NULL, otp_expires_at=NULL WHERE email='$email'");
            echo json_encode(["status" => "success", "message" => "Password reset successful"]);
        } else {
            echo json_encode(["status" => "error", "message" => "OTP has expired"]);
        }
    } else {
        echo json_encode(["status" => "error", "message" => "Invalid OTP"]);
    }
} else {
    echo json_encode(["status" => "error", "message" => "User not found"]);
}
?>