<?php
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
$_kctx = Kernel::handle(['auth' => true, 'rate' => 'api']);
$_user = $_kctx['user']; $_userId = (int)$_user['id'];
header('Content-Type: application/json; charset=utf-8');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') Kernel::fail('method_not_allowed', '', 405);
$ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
if (!check_rate_limit('invest_' . md5($ip), 3, 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']  ?? ''));
$phone = mb_substr(trim($b['phone']   ?? ''), 0, 30);
$country = mb_substr(trim($b['country'] ?? ''), 0, 100);
$tier  = mb_substr(trim($b['tier']    ?? ''), 0, 50);
if (!$name || !$email) Kernel::fail('missing_fields', '', 400);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) Kernel::fail('invalid_email', '', 400);
db()->prepare('INSERT INTO investment_applications (name, email, phone, country, tier, q1, q2, q3, q4, q5, q6) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)')->execute([$name, $email, $phone, $country, $tier, $b['q1'] ?? '', $b['q2'] ?? '', $b['q3'] ?? '', $b['q4'] ?? '', $b['q5'] ?? '', $b['q6'] ?? '']);
json_response(['success' => true, 'message' => 'شكراً! سنتواصل معك خلال 48 ساعة.']);
