<?php
require_once __DIR__ . '/includes/config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: ' . BASE_URL . '/contact.php');
    exit;
}

$name    = trim($_POST['full_name']        ?? '');
$email   = trim($_POST['email']            ?? '');
$subject = trim($_POST['subject']          ?? '');
$phone   = trim($_POST['phone']            ?? '');
$country = trim($_POST['preferred_country']?? '');
$message = trim($_POST['message']          ?? '');

if ($country) $subject = ($subject ?: 'Consultation') . ' [' . $country . ']';
if (!$subject) $subject = 'Free Consultation Request';

$db = site_db();
if ($db) {
    $db->query("CREATE TABLE IF NOT EXISTS contact_messages (
        id INT AUTO_INCREMENT PRIMARY KEY,
        full_name VARCHAR(100),
        email VARCHAR(150),
        phone VARCHAR(30),
        subject VARCHAR(200),
        message TEXT,
        is_read TINYINT(1) DEFAULT 0,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");
    $st = $db->prepare("INSERT INTO contact_messages (full_name,email,phone,subject,message) VALUES (?,?,?,?,?)");
    $st->bind_param('sssss', $name,$email,$phone,$subject,$message);
    $st->execute();
}

// Check if AJAX request
$isAjax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && 
          strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';

if ($isAjax) {
    header('Content-Type: application/json');
    echo json_encode(['success'=>true]);
} else {
    header('Location: ' . BASE_URL . '/contact.php?sent=1');
}
exit;
