
­­­­­­­­­­­­­­­­­­
<!DOCTYPE html>
<html>
<?php
declare(strict_types=1);

/**
 * push_honda_by_mobile.php
 *
 * Usage:
 *   GET  /push_honda_by_mobile.php?mobile=05xxxxxxxx
 *   POST /push_honda_by_mobile.php  (mobile=05xxxxxxxx)
 */

header('Content-Type: application/json; charset=utf-8');

// ----------------------
// CONFIG
// ----------------------
$db = [
  'host' => 'localhost',
  'name' => 'balubaid_core3_leads',
  'user' => 'balubaid_core3_leads',
  'pass' => 'Vision@2050',
  'charset' => 'utf8mb4',
];

$cfg = [
  'endpoint_url' => 'https://hondasaudi.com/service_request/ai_integration/',
  'timeout_sec'  => 30,
  'lang_default' => 'Arabic',
];

// ----------------------
// HELPERS
// ----------------------
function normalizeSaudiMobile(?string $mobile): string {
    $m = trim((string)$mobile);

    // Keep digits only
    $m = preg_replace('/\D+/', '', $m);

    if (!$m) {
        return '';
    }

    // Replace str_starts_with() for PHP 7
    if (substr($m, 0, 5) === '00966') {
        $m = '0' . substr($m, 5);
    } 
    elseif (substr($m, 0, 3) === '966') {
        $m = '0' . substr($m, 3);
    } 
    elseif (substr($m, 0, 1) === '5' && strlen($m) === 9) {
        $m = '0' . $m;
    }

    return $m;
}


function jsonOut(array $data, int $code = 200): void {
  http_response_code($code);
  echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
  exit;
}

// ----------------------
// INPUT (GET or POST)
// ----------------------
$inputMobile = $_GET['mobile'] ?? ($_POST['mobile'] ?? '');
$inputMobile = normalizeSaudiMobile($inputMobile);

if ($inputMobile === '' || strlen($inputMobile) < 10) {
  jsonOut([
    'ok' => false,
    'error' => 'Please pass a valid mobile. Example: ?mobile=055xxxxxxx'
  ], 400);
}

// Build mobile variants to match different stored formats
$variants = array_values(array_unique([
  $inputMobile,                    // 05xxxxxxxx
  ltrim($inputMobile, '0'),        // 5xxxxxxxx
  '966' . ltrim($inputMobile, '0') // 9665xxxxxxxx
]));

// ----------------------
// DB CONNECT
// ----------------------
$dsn = "mysql:host={$db['host']};dbname={$db['name']};charset={$db['charset']}";
try {
  $pdo = new PDO($dsn, $db['user'], $db['pass'], [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
  ]);
} catch (Throwable $e) {
  jsonOut(['ok' => false, 'error' => 'DB connection failed', 'details' => $e->getMessage()], 500);
}

// ----------------------
// FETCH latest lead by mobile (ONLY ONE)
// ----------------------
$placeholders = implode(',', array_fill(0, count($variants), '?'));

$sql = "
  SELECT
    name,
    mobile,
    car,
    city,
    request_date,
    email_address,
    source,
    gender,
    formid,
    salary,
    paymethod,
    campaign,
    preftime,
    purtime,
    isobligations,
    obligation_amount
  FROM xx_honda_leads
  WHERE mobile IN ($placeholders)
  ORDER BY request_date DESC
  LIMIT 1
";

$stmt = $pdo->prepare($sql);
$stmt->execute($variants);
$row = $stmt->fetch();

if (!$row) {
  jsonOut([
    'ok' => false,
    'error' => 'No lead found for this mobile',
    'mobile_normalized' => $inputMobile,
    'searched_variants' => $variants
  ], 404);
}

// ----------------------
// MAP DB -> API payload
// ----------------------
$payload = [
  'mobile'       => $inputMobile,
  'name'         => (string)($row['name'] ?? ''),
  'email'        => (string)($row['email_address'] ?? ''),
  'gender'       => (string)($row['gender'] ?? ''),
  'city'         => (string)($row['city'] ?? ''),
  'model'        => (string)($row['car'] ?? ''),
  'paymethod'    => (string)($row['paymethod'] ?? ''),
  'purtime'      => (string)($row['purtime'] ?? ''),
  'preftime'     => (string)($row['preftime'] ?? ''),
  'source'       => (string)($row['source'] ?? ''),
  'campaign'     => (string)($row['campaign'] ?? ''),
  'ref_id'       => (string)($row['formid'] ?? ''),
  'salary'       => (string)($row['salary'] ?? ''),
  'deduction'    => (string)($row['obligation_amount'] ?? ''),
  'lang'         => $cfg['lang_default'],
  'request_date' => !empty($row['request_date']) ? (string)$row['request_date'] : date('Y-m-d H:i:s'),
];

// ----------------------
// CALL HONDA ENDPOINT
// ----------------------
$ch = curl_init($cfg['endpoint_url']);
curl_setopt_array($ch, [
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_POST           => true,
  CURLOPT_POSTFIELDS     => http_build_query($payload),
  CURLOPT_HTTPHEADER     => ['Content-Type: application/x-www-form-urlencoded'],
  CURLOPT_TIMEOUT        => (int)$cfg['timeout_sec'],
]);

$response = curl_exec($ch);
$error    = curl_error($ch);
$httpCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

jsonOut([
  'ok' => ($error === '' && $httpCode >= 200 && $httpCode < 300),
  'mobile' => $inputMobile,
  'db_row' => $row,
  'sent_payload' => $payload,
  'http_code' => $httpCode,
  'curl_error' => $error ?: null,
  'endpoint_response' => $response,
], 200);
