<?php
ini_set('display_errors', 0);
error_reporting(0);

// Buffer everything — guarantees clean JSON output even if an include spits a warning
ob_start();

require_once __DIR__ . '/includes/functions.php';

$type  = $_POST['form_type'] ?? '';
$leads = getData('leads');
$id    = generateId($leads);
$now   = date('Y-m-d H:i:s');

$response      = ['success' => false, 'message' => 'Invalid form type'];
$sendEmailData = null; // hold email job for after response is sent

if ($type === 'register') {
    $lead = [
        'id'           => $id,
        'form_type'    => 'register',
        'company_name' => trim($_POST['company_name'] ?? ''),
        'first_name'   => trim($_POST['first_name'] ?? ''),
        'last_name'    => trim($_POST['last_name'] ?? ''),
        'email'        => trim($_POST['email'] ?? ''),
        'phone'        => trim($_POST['phone'] ?? ''),
        'country'      => trim($_POST['country'] ?? ''),
        'stand_type'   => trim($_POST['stand_type'] ?? ''),
        'stand_size'   => trim($_POST['stand_size'] ?? ''),
        'sectors'      => trim($_POST['sectors'] ?? ''),
        'website'      => trim($_POST['website'] ?? ''),
        'message'      => trim($_POST['message'] ?? ''),
        'status'       => 'New',
        'notes'        => '',
        'date'         => $now
    ];
    $leads[] = $lead;
    saveData('leads', $leads);
    $response      = ['success' => true, 'message' => 'Enquiry received'];
    $sendEmailData = ['type' => 'register', 'lead' => $lead];

} elseif ($type === 'contact') {
    $lead = [
        'id'        => $id,
        'form_type' => 'contact',
        'name'      => trim($_POST['name'] ?? ''),
        'email'     => trim($_POST['email'] ?? ''),
        'phone'     => trim($_POST['phone'] ?? ''),
        'company'   => trim($_POST['company'] ?? ''),
        'country'   => trim($_POST['country'] ?? ''),
        'message'   => trim($_POST['message'] ?? ''),
        'status'    => 'New',
        'notes'     => '',
        'date'      => $now
    ];
    $leads[] = $lead;
    saveData('leads', $leads);
    $response      = ['success' => true, 'message' => 'Message sent'];
    $sendEmailData = ['type' => 'contact', 'lead' => $lead];
}

// Discard any stray output (PHP warnings, BOM chars, etc.) before sending JSON
ob_end_clean();

header('Content-Type: application/json');
echo json_encode($response);

// Flush response to browser immediately
if (function_exists('fastcgi_finish_request')) {
    fastcgi_finish_request();
} else {
    // Fallback for standard PHP-FPM / mod_php
    if (ob_get_level()) ob_end_flush();
    flush();
}

// Send email AFTER response is delivered — failure here won't affect the user
if ($sendEmailData) {
    // Wrap in try/catch so any email crash is fully silent
    try {
        require_once __DIR__ . '/includes/email-templates.php';
        $settings = getSettings();
        if ($sendEmailData['type'] === 'register') {
            $email = getRegisterNotificationEmail($sendEmailData['lead']);
        } else {
            $email = getContactNotificationEmail($sendEmailData['lead']);
        }
        sendEmail($settings['email'], $email['subject'], $email['body']);
    } catch (Throwable $e) {
        // Silent — lead is already saved, email failure is non-critical
    }
}