<?php
// Allow any origin (for development only)
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

// Handle preflight requests (OPTIONS)
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}
header("Content-Type: application/json");
include '../../dbcon.php';

$data = json_decode(file_get_contents("php://input"), true);
$email = mysqli_real_escape_string($conn, $data['email'] ?? '');

if (!$email) {
    echo json_encode(["status" => "error", "message" => "Email is required"]);
    exit;
}

// Check user
$userCheck = mysqli_query($conn, "SELECT id FROM users WHERE email='$email'");
if (mysqli_num_rows($userCheck) === 0) {
    echo json_encode(["status" => "error", "message" => "Email not found"]);
    exit;
}

// Generate OTP and expiry
$otp = rand(10000, 99999);
$expires = date("Y-m-d H:i:s", strtotime("+5 minutes"));

mysqli_query($conn, "UPDATE users SET otp='$otp', otp_expires_at='$expires' WHERE email='$email'");

// Return OTP to frontend (send via EmailJS)
echo json_encode([
    "status" => "success",
    "message" => "OTP generated, & Sent",
    "email" => $email,
    "otp" => $otp
]);
?>