<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
header("Content-Type: application/json; charset=UTF-8");

require_once "../../dbcon.php";

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

if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    http_response_code(405);
    echo json_encode(["status" => "error", "message" => "Method not allowed"]);
    exit();
}

function sanitize($data) {
    global $conn;
    return htmlspecialchars(strip_tags(mysqli_real_escape_string($conn, $data)));
}

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

$full_name = sanitize($data['full_name'] ?? '');
$email = sanitize($data['email'] ?? '');
$phone = sanitize($data['phone'] ?? '');
$message = sanitize($data['message'] ?? '');
$source = sanitize($data['source'] ?? 'website');

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

$query = "INSERT INTO leads (full_name, email, phone, message, source, status) 
          VALUES ('$full_name', '$email', '$phone', '$message', '$source', 'new')";

if (mysqli_query($conn, $query)) {
    echo json_encode(["status" => "success", "message" => "Thank you for your interest! We will contact you soon."]);
} else {
    echo json_encode(["status" => "error", "message" => "Submission failed. Please try again later."]);
}

mysqli_close($conn);
?>
