<?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();
}

// --- Auto-Migration: Ensure site_inquiries table exists ---
$createTable = "CREATE TABLE IF NOT EXISTS site_inquiries (
    id INT AUTO_INCREMENT PRIMARY KEY,
    full_name VARCHAR(150) NOT NULL,
    email VARCHAR(150) NOT NULL,
    phone VARCHAR(50) NOT NULL,
    message TEXT NOT NULL,
    source VARCHAR(100) DEFAULT 'website_inquiry',
    status ENUM('new', 'contacted', 'converted', 'lost') DEFAULT 'new',
    agent_id INT DEFAULT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (agent_id) REFERENCES users(id) ON DELETE SET NULL
)";
mysqli_query($conn, $createTable);

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_inquiry');

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

$query = "INSERT INTO site_inquiries (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! Your inquiry has been submitted successfully."]);
} else {
    echo json_encode(["status" => "error", "message" => "Submission failed: " . mysqli_error($conn)]);
}

mysqli_close($conn);
?>
