<?php
session_start();
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/config.php';

header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(false, 'Invalid request method.', [], 405);
}

$name = isset($_POST['name']) ? trim($_POST['name']) : '';
$restaurantName = isset($_POST['restaurant_name']) ? trim($_POST['restaurant_name']) : '';
$phone = isset($_POST['phone']) ? trim($_POST['phone']) : '';
$email = isset($_POST['email']) ? trim($_POST['email']) : '';
$city = isset($_POST['city']) ? trim($_POST['city']) : '';
$message = isset($_POST['message']) ? trim($_POST['message']) : '';
$preferredPlan = isset($_POST['preferred_plan']) ? trim($_POST['preferred_plan']) : '';

if (empty($name)) {
    jsonResponse(false, 'Please enter your name.');
}

if (empty($email)) {
    jsonResponse(false, 'Please enter your email address.');
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    jsonResponse(false, 'Please enter a valid email address.');
}

if (empty($phone)) {
    jsonResponse(false, 'Please enter your phone number.');
}

$csrfToken = isset($_POST['csrf_token']) ? trim($_POST['csrf_token']) : '';
$csrf = new CSRF();
if (!$csrf->verify($csrfToken)) {
    jsonResponse(false, 'Invalid security token. Please refresh the page and try again.', [
        'csrf_token' => $csrf->getToken(),
    ]);
}

try {
    $db = Database::getInstance();

    $db->insert('enquiries', [
        'name'           => $name,
        'restaurant_name' => $restaurantName,
        'phone'          => $phone,
        'email'          => $email,
        'city'           => $city,
        'message'        => $message,
        'preferred_plan' => $preferredPlan,
        'status'         => 'new',
        'created_at'     => date('Y-m-d H:i:s'),
    ]);

    jsonResponse(true, 'Thank you! We will be in touch soon.', [
        'csrf_token' => $csrf->getToken(),
    ]);

} catch (Exception $e) {
    error_log('Enquiry save error: ' . $e->getMessage());
    jsonResponse(false, 'An error occurred while saving your enquiry. Please try again.', [
        'csrf_token' => $csrf->getToken(),
    ]);
}
