<?php
require_once __DIR__ . '/../includes/mj_v304_bootstrap.php';
require_once __DIR__ . '/../includes/mj_v304_leads_helper.php';
try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') { throw new RuntimeException('Invalid request.'); }
    $sellerUserId = (int)($_POST['seller_user_id'] ?? 0);
    if ($sellerUserId <= 0) { throw new RuntimeException('Seller not found.'); }
    $name = trim((string)($_POST['customer_name'] ?? ''));
    $phone = trim((string)($_POST['customer_phone'] ?? ''));
    $msg = trim((string)($_POST['customer_message'] ?? ''));
    if ($name === '' || $phone === '' || $msg === '') { throw new RuntimeException('Please fill name, phone, and message.'); }
    $leadId = mjv304_create_seller_lead([
        'seller_user_id'=>$sellerUserId,
        'source_type'=>$_POST['source_type'] ?? 'listing',
        'source_id'=>(int)($_POST['source_id'] ?? 0),
        'source_title'=>$_POST['source_title'] ?? '',
        'country'=>$_POST['country'] ?? '',
        'customer_name'=>$name,
        'customer_phone'=>$phone,
        'customer_email'=>$_POST['customer_email'] ?? '',
        'customer_message'=>$msg,
    ]);
    $back = $_SERVER['HTTP_REFERER'] ?? '../index.php';
    $sep = strpos($back, '?') === false ? '?' : '&';
    header('Location: '.$back.$sep.'enquiry=sent&lead_id='.$leadId.'#send-enquiry');
    exit;
} catch (Throwable $e) {
    $back = $_SERVER['HTTP_REFERER'] ?? '../index.php';
    $sep = strpos($back, '?') === false ? '?' : '&';
    header('Location: '.$back.$sep.'enquiry_error='.rawurlencode($e->getMessage()).'#send-enquiry');
    exit;
}
