<?php
require_once '../config.php';
require_once __DIR__ . '/../engine/Kernel.php';
Kernel::handle(['auth' => false, 'public' => true]);
require_once __DIR__ . '/../../engine/Logger.php'; // COVERAGE
if ($_SERVER['REQUEST_METHOD'] !== 'POST') Kernel::fail('method_not_allowed', '', 405);
$ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
if (!check_rate_limit('contact_' . md5($ip), 5, 3600)) Kernel::fail('rate_limit', '', 429);
$b = json_decode(file_get_contents('php://input'), true) ?? [];
$name  = mb_substr(trim($b['name']    ?? ''), 0, 100);
$email = trim(strtolower($b['email']  ?? ''));
$msg   = mb_substr(trim($b['message'] ?? ''), 0, 2000);
$type  = in_array($b['type'] ?? '', ['contact','invest','partner']) ? ($b['type'] ?? 'contact') : 'contact';
if (!$name || !$email || !$msg) Kernel::fail('missing_fields', 'أدخل كل البيانات', 400);
db()->prepare('INSERT INTO inquiries (name, email, phone, type, message) VALUES (?, ?, ?, ?, ?)')->execute([$name, $email, $b['phone'] ?? '', $type, $msg]);
json_response(['success' => true, 'message' => 'شكراً! تم استلام رسالتك.']);
