<?php
header('Content-Type: application/json; charset=utf-8');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { echo json_encode(['ok'=>false,'error'=>'method']); exit; }

require_once __DIR__ . '/config/db.php';

$name    = trim($_POST['name']    ?? '');
$email   = trim($_POST['email']   ?? '');
$phone   = trim($_POST['phone']   ?? '');
$message = trim($_POST['message'] ?? '');
$lang    = preg_replace('/[^a-z]/', '', strtolower($_POST['lang'] ?? 'ar'));

if (!$name || !$email || !$message || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode(['ok'=>false,'error'=>'validation']); exit;
}

$ip = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'] ?? null;

try {
    $stmt = db()->prepare("INSERT INTO messages (name,email,phone,message,lang,ip) VALUES (?,?,?,?,?,?)");
    $stmt->execute([$name, $email, $phone ?: null, $message, $lang ?: 'ar', $ip]);
    echo json_encode(['ok'=>true]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['ok'=>false,'error'=>'server']);
}
