<?php
/**
 * Receives a demo request from request-demo.php, stores it as 'pending',
 * notifies the Oric team, and returns a WhatsApp deep-link for the visitor.
 */
header('Content-Type: application/json');
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

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

$fail = static function (string $msg, int $code = 400): void {
    http_response_code($code);
    echo json_encode(['success' => false, 'message' => $msg]);
    exit;
};

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

// Honeypot — bots fill the hidden "website" field.
if (!empty($_POST['website'])) {
    // Pretend success so the bot moves on; nothing is stored.
    echo json_encode(['success' => true, 'message' => 'Request received.']);
    exit;
}

// Simple per-session rate limit: max 3 submissions / hour.
$now  = time();
$hits = array_filter($_SESSION['demo_req_hits'] ?? [], static fn($t) => $t > $now - 3600);
if (count($hits) >= 3) {
    $fail('You have sent several requests already. Please WhatsApp us instead.', 429);
}

$school_name  = trim((string) ($_POST['school_name']  ?? ''));
$contact_name = trim((string) ($_POST['contact_name'] ?? ''));
$role         = trim((string) ($_POST['role']         ?? ''));
$whatsapp     = trim((string) ($_POST['whatsapp']     ?? ''));
$email        = trim((string) ($_POST['email']        ?? ''));
$region       = trim((string) ($_POST['region']       ?? ''));
$message      = trim((string) ($_POST['message']      ?? ''));

if ($school_name === '' || $contact_name === '' || $whatsapp === '') {
    $fail('Please fill in the school name, your name and WhatsApp number.');
}
if (strlen(preg_replace('/\D/', '', $whatsapp)) < 9) {
    $fail('Please enter a valid WhatsApp number.');
}
if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $fail('Please enter a valid email address (or leave it blank).');
}

$conn = getDBConnection();
if (!$conn) {
    $fail('Service temporarily unavailable. Please try again shortly.', 500);
}
ensureDemoRequestsTable($conn);

$ip = $_SERVER['REMOTE_ADDR'] ?? '';
$stmt = $conn->prepare(
    "INSERT INTO demo_requests
        (school_name, contact_name, role, whatsapp, email, region, message, ip_address)
     VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
);
if (!$stmt) {
    error_log('demo_requests insert prepare failed: ' . $conn->error);
    $fail('Could not save your request. Please WhatsApp us instead.', 500);
}
$stmt->bind_param('ssssssss', $school_name, $contact_name, $role, $whatsapp, $email, $region, $message, $ip);
if (!$stmt->execute()) {
    error_log('demo_requests insert failed: ' . $stmt->error);
    $fail('Could not save your request. Please WhatsApp us instead.', 500);
}
$request_id = $stmt->insert_id;
$stmt->close();

// Record the rate-limit hit.
$hits[] = $now;
$_SESSION['demo_req_hits'] = array_values($hits);

// ── Notify the Oric team (best-effort; never blocks the response) ───────────
global $config;
$team_emails = array_values(array_filter([
    $config['email']['tech_email']    ?? '',
    $config['email']['manager_email'] ?? '',
]));
$safe = static fn($v) => htmlspecialchars((string) $v, ENT_QUOTES, 'UTF-8');
$body = '<h2>New EduTrack demo request</h2>'
      . '<table cellpadding="6" style="border-collapse:collapse;font-family:Arial">'
      . '<tr><td><b>School</b></td><td>' . $safe($school_name) . '</td></tr>'
      . '<tr><td><b>Contact</b></td><td>' . $safe($contact_name) . ' (' . $safe($role ?: 'n/a') . ')</td></tr>'
      . '<tr><td><b>WhatsApp</b></td><td>' . $safe($whatsapp) . '</td></tr>'
      . '<tr><td><b>Email</b></td><td>' . $safe($email ?: 'n/a') . '</td></tr>'
      . '<tr><td><b>Region</b></td><td>' . $safe($region ?: 'n/a') . '</td></tr>'
      . '<tr><td><b>Notes</b></td><td>' . nl2br($safe($message ?: '—')) . '</td></tr>'
      . '</table>'
      . '<p>Review &amp; approve: ' . rtrim(BASE_URL, '/') . '/admin/demo_requests.php</p>';

try {
    if (!empty($team_emails) && function_exists('sendEmail')) {
        sendEmail($team_emails[0], 'New demo request: ' . $school_name, $body, array_slice($team_emails, 1));
    }
} catch (Throwable $e) {
    error_log('Demo request team email failed: ' . $e->getMessage());
}

try {
    if (function_exists('sendSMS')) {
        $teamSms = getSettingValue('demo_team_sms') ?: getDemoWhatsApp();
        sendSMS($teamSms, "EduTrack: new demo request from {$school_name} ({$contact_name}, {$whatsapp}).");
    }
} catch (Throwable $e) {
    error_log('Demo request team SMS failed: ' . $e->getMessage());
}

$wa = getDemoWhatsApp();
$wa_text = rawurlencode("Hello Oric team, I just requested a demo for {$school_name}. My name is {$contact_name}.");

echo json_encode([
    'success'      => true,
    'message'      => 'Thanks! Our team will contact you on WhatsApp to schedule your guided demo.',
    'whatsapp_url' => "https://wa.me/{$wa}?text={$wa_text}",
]);
