
­­­­­­­­­­­­­­­­­­
<!DOCTYPE html>
<html>
<?php
declare(strict_types=1);

/**
 * Snapchat Lead Webhook Handler (Peugeot)
 * 1) Receives Snapchat lead payload via POST (x-www-form-urlencoded or JSON)
 * 2) Stores lead into MySQL (PDO) with upsert by lead_id
 * 3) Submits mapped lead to https://ms.peugeotksaoffers.com/submit-lead-ar/ via cURL
 *
 * IMPORTANT SECURITY NOTE:
 * - Do NOT keep real DB credentials in code on production.
 * - Move secrets to env vars / config file outside web root.
 */

error_reporting(E_ALL);
ini_set('display_errors', '0'); // safer for production; use logs instead

date_default_timezone_set('Asia/Riyadh');

// -----------------------------
// 0) CONFIG
// -----------------------------
$dbHost = "localhost";
$dbName = "balubaid_autozoneoffers";
$dbUser = "balubaid_autozoneoffers";
$dbPass = "Vision@2050"; // move to env var in production
$dsn    = "mysql:host={$dbHost};dbname={$dbName};charset=utf8mb4";

// Where to POST after saving lead
$peugeotSubmitUrl = "https://ms.peugeotksaoffers.com/submit-lead-ar/";
$peugeotReferer   = "https://ms.peugeotksaoffers.com/lead-form-ar/1/?campaign=DD-C3-EOYO-2025&sourcee=Google&utm_source=Google&utm_campaign=DD-C3-EOYO-2025";

// -----------------------------
// 1) HELPERS
// -----------------------------

/**
 * Some Snapchat fields come like "{Label:Value}" or "Label:Value" depending on connector.
 * This extracts the label part before ":" and removes braces.
 */
function extractLabel(?string $input): string
{
    $input = (string)$input;
    $input = trim($input);
    if ($input === '') return '';

    // Remove surrounding braces { }
    $clean = trim($input, "{} \t\n\r\0\x0B");

    // Split on colon
    $parts = explode(":", $clean, 2);

    return trim($parts[0] ?? '');
}

function convert2english(string $string): string
{
    $newNumbers     = range(0, 9);
    $persianDecimal = ['&#1776;','&#1777;','&#1778;','&#1779;','&#1780;','&#1781;','&#1782;','&#1783;','&#1784;','&#1785;'];
    $arabicDecimal  = ['&#1632;','&#1633;','&#1634;','&#1635;','&#1636;','&#1637;','&#1638;','&#1639;','&#1640;','&#1641;'];
    $arabic         = ['٠','١','٢','٣','٤','٥','٦','٧','٨','٩'];
    $persian        = ['۰','۱','۲','۳','۴','۵','۶','۷','۸','۹'];

    $string = str_replace($persianDecimal, $newNumbers, $string);
    $string = str_replace($arabicDecimal,  $newNumbers, $string);
    $string = str_replace($arabic,         $newNumbers, $string);
    return str_replace($persian,           $newNumbers, $string);
}

/**
 * Normalizes Saudi mobile to 9-digit "5XXXXXXXX"
 */
function normalizeSaudiMobile(string $input): ?string
{
    $number = preg_replace('/\D+/', '', $input);

    if (strpos($number, '966') === 0) {
        $number = substr($number, 3);
    }
    if (strpos($number, '0') === 0) {
        $number = substr($number, 1);
    }

    if (preg_match('/^5\d{8}$/', $number)) {
        return $number;
    }
    return null;
}

/**
 * Splits a full name into [first, last]
 */
function splitFullName(string $name): array
{
    $name = trim(preg_replace('/\s+/', ' ', $name));
    if ($name === '') return ['', ''];
    $parts = explode(' ', $name);
    $first = array_shift($parts);
    $last  = trim(implode(' ', $parts));
    return [$first, $last];
}

/**
 * Lookup mapping value from DB table:
 * peugeot_lead_lookup_values(lookup_value, type, result_value)
 */
function getLookupValue(PDO $pdo, string $lookupValue, string $type): ?string
{
    if ($lookupValue === '' || $type === '') return null;

    $sql = "SELECT result_value
            FROM peugeot_lead_lookup_values
            WHERE lookup_value = :lookup_value AND type = :type
            LIMIT 1";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        ':lookup_value' => $lookupValue,
        ':type'         => $type,
    ]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    return $row['result_value'] ?? null;
}

/**
 * Submit lead to Peugeot submit-lead-ar endpoint (form-urlencoded)
 */
function submitPeugeotLeadAr(array $lead, array $opts = []): array
{
    $postUrl = $opts['post_url'] ?? "https://ms.peugeotksaoffers.com/submit-lead-ar/";
    $referer = $opts['referer'] ?? "https://ms.peugeotksaoffers.com/lead-form-ar/1/";
    $timeout = (int)($opts['timeout'] ?? 30);

    // lightweight required fields check
    $required = ['offer_id','fullName','lastname','email','mobile','model','city','branch'];
    foreach ($required as $k) {
        if (!isset($lead[$k]) || trim((string)$lead[$k]) === '') {
            return [
                'ok'        => false,
                'http_code' => 0,
                'response'  => '',
                'error'     => "Missing required field: {$k}",
            ];
        }
    }

    $data = [
        // tracking
        'utm_source'   => $lead['utm_source']   ?? 'Snapchat',
        'utm_campaign' => $lead['utm_campaign'] ?? ($lead['campaign'] ?? 'DD-C3-EOYO-2026'),
        'campaign'     => $lead['campaign']     ?? 'DD-C3-EOYO-2026',
        'sourcee'      => $lead['sourcee']      ?? 'Snapchat',
        'formtype'     => $lead['formtype']     ?? 'installment',
        'offer_id'     => (string)$lead['offer_id'],

        // user fields
        'fullName'     => (string)$lead['fullName'],
        'lastname'     => (string)$lead['lastname'],
        'email'        => (string)$lead['email'],
        'mobile'       => (string)$lead['mobile'],

        // car & purchase
        'model'        => (string)$lead['model'],
        'purchaseTime' => (string)($lead['purchaseTime'] ?? '1-3-months'),

        // optionals
        'nationality'     => (string)($lead['nationality'] ?? 'Non-Saudi'),
        'bank'            => (string)($lead['bank'] ?? 'Others'),
        'gender'          => (string)($lead['gender'] ?? 'Male'),
        'salary'          => (string)($lead['salary'] ?? '5000-7500'),

        // location
        'city'            => (string)$lead['city'],
        'branch'          => (string)$lead['branch'],

        // obligations
        'obligation'       => (string)($lead['obligation'] ?? 'no'),
        'realestateLoan'   => (string)($lead['realestateLoan'] ?? 'no'),
        'obligationAmount' => (string)($lead['obligationAmount'] ?? ''),

        // checkboxes in your form (some forms use terms/privacypolicy)
        'terms'         => (string)($lead['terms'] ?? '1'),
        'privacypolicy' => (string)($lead['privacypolicy'] ?? 'on'),
    ];

    // If formtype cash => align with your submit script logic
    if ($data['formtype'] === 'cash') {
        $data['salary']     = '4502';
        $data['bank']       = 'OTHERS';
        $data['obligation'] = 'no';
    }

    $ch = curl_init($postUrl);

    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => http_build_query($data),
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_TIMEOUT        => $timeout,
        CURLOPT_HTTPHEADER     => [
            "Content-Type: application/x-www-form-urlencoded; charset=UTF-8",
            "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
            "Origin: https://ms.peugeotksaoffers.com",
            "Referer: {$referer}",
        ],
    ]);

    $response = (string)curl_exec($ch);
    $httpCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $err      = curl_errno($ch) ? curl_error($ch) : null;
    curl_close($ch);

    return [
        'ok'        => ($err === null && $httpCode >= 200 && $httpCode < 400),
        'http_code' => $httpCode,
        'response'  => $response,
        'error'     => $err,
        'posted'    => $data, // helpful for debugging; remove in production if needed
    ];
}

/**
 * Read incoming payload:
 * - If JSON: read php://input
 * - Else: use $_POST
 */
function readIncomingPayload(): array
{
    $contentType = $_SERVER['CONTENT_TYPE'] ?? $_SERVER['HTTP_CONTENT_TYPE'] ?? '';
    $contentType = strtolower($contentType);

    if (strpos($contentType, 'application/json') !== false) {
        $raw = file_get_contents('php://input') ?: '';
        $decoded = json_decode($raw, true);
        return is_array($decoded) ? $decoded : [];
    }

    // Fallback: normal form POST
    return is_array($_POST) ? $_POST : [];
}

// -----------------------------
// 2) MAIN
// -----------------------------
header("Content-Type: text/plain; charset=utf-8");

$lead = readIncomingPayload();

// Quick sanity
if (!is_array($lead) || empty($lead)) {
    http_response_code(400);
    exit("Bad Request: empty payload\n");
}

// Connect DB
try {
    $pdo = new PDO($dsn, $dbUser, $dbPass, [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES   => false,
    ]);
} catch (PDOException $e) {
    http_response_code(500);
    exit("DB Connection Error: " . $e->getMessage() . "\n");
}

// Convert CreateTime (ISO 8601 with Z) into MySQL DATETIME (UTC)
$createTimeUtc = null;
if (!empty($lead["CreateTime"])) {
    try {
        $dt = new DateTime((string)$lead["CreateTime"]); // understands Z
        $dt->setTimezone(new DateTimeZone("UTC"));
        $createTimeUtc = $dt->format("Y-m-d H:i:s");
    } catch (Exception $e) {
        $createTimeUtc = null;
    }
}

// Map payload to DB columns
$data = [
    "ad_account_id"         => $lead["AdAccountID"] ?? null,
    "ad_id"                 => $lead["AdId"] ?? null,
    "ad_name"               => $lead["AdName"] ?? null,
    "ad_squad_id"           => $lead["AdSquadID"] ?? null,
    "ad_squad_name"         => $lead["AdSquadName"] ?? null,
    "branch"                => extractLabel($lead["Branch"]) ?? null,
    "campaign_id"           => $lead["CampaignId"] ?? null,
    "campaign_name"         => $lead["CampaignName"] ?? null,
    "create_time_utc"       => $createTimeUtc,
    "email"                 => $lead["Email"] ?? null,
    "form_id"               => $lead["FormID"] ?? null,
    "form_name"             => $lead["FormName"] ?? null,
    "lead_id"               => $lead["LeadId"] ?? null,
    "lead_preferred_status" => $lead["LeadPreferredStatus"] ?? null,
    "full_name"             => $lead["Name"] ?? null,
    "phone"                 => $lead["Phone"] ?? null,
    "purchase_time"         => extractLabel($lead["PurchaseTime"]) ?? null,
    "salary"                => extractLabel($lead["Salary"]) ?? null,
    "strategy_type"         => $lead["StrategyType"] ?? null,
    "vehicle"               => extractLabel($lead["Vehicle"]) ?? null,
    "raw_payload"           => json_encode($lead, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
];

if (empty($data["lead_id"])) {
    http_response_code(400);
    exit("LeadId is required.\n");
}

// Upsert into peugeot_snapchat_leads
$sql = "
INSERT INTO peugeot_snapchat_leads (
  ad_account_id, ad_id, ad_name, ad_squad_id, ad_squad_name, branch,
  campaign_id, campaign_name, create_time_utc, email,
  form_id, form_name, lead_id, lead_preferred_status, full_name, phone,
  purchase_time, salary, strategy_type, vehicle, raw_payload
) VALUES (
  :ad_account_id, :ad_id, :ad_name, :ad_squad_id, :ad_squad_name, :branch,
  :campaign_id, :campaign_name, :create_time_utc, :email,
  :form_id, :form_name, :lead_id, :lead_preferred_status, :full_name, :phone,
  :purchase_time, :salary, :strategy_type, :vehicle, :raw_payload
)
ON DUPLICATE KEY UPDATE
  ad_account_id         = VALUES(ad_account_id),
  ad_id                 = VALUES(ad_id),
  ad_name               = VALUES(ad_name),
  ad_squad_id           = VALUES(ad_squad_id),
  ad_squad_name         = VALUES(ad_squad_name),
  branch                = VALUES(branch),
  campaign_id           = VALUES(campaign_id),
  campaign_name         = VALUES(campaign_name),
  create_time_utc       = VALUES(create_time_utc),
  email                 = VALUES(email),
  form_id               = VALUES(form_id),
  form_name             = VALUES(form_name),
  lead_preferred_status = VALUES(lead_preferred_status),
  full_name             = VALUES(full_name),
  phone                 = VALUES(phone),
  purchase_time         = VALUES(purchase_time),
  salary                = VALUES(salary),
  strategy_type         = VALUES(strategy_type),
  vehicle               = VALUES(vehicle),
  raw_payload           = VALUES(raw_payload)
";

try {
    $stmt = $pdo->prepare($sql);
    $stmt->execute($data);
    echo "OK: Lead stored. LeadId = " . $data["lead_id"] . PHP_EOL;
} catch (PDOException $e) {
    http_response_code(500);
    exit("DB Error (insert/upsert): " . $e->getMessage() . PHP_EOL);
}

// -----------------------------
// 3) BUILD & SUBMIT TO PEUGEOT FORM
// -----------------------------
$rawName = (string)($lead['Name'] ?? '');
[$firstName, $lastName] = splitFullName($rawName);

// Mobile normalize => submit script expects "05xxxxxxxx"
$mobile9 = normalizeSaudiMobile(convert2english((string)($lead['Phone'] ?? '')));
$mobile05 = $mobile9 ? ('0' . $mobile9) : '';

// Extract labels then lookup
$salaryLabel   = extractLabel((string)($lead['Salary'] ?? ''));
$vehicleLabel  = extractLabel((string)($lead['Vehicle'] ?? ''));
$branchLabel   = extractLabel((string)($lead['Branch'] ?? ''));
$purtimeLabel  = extractLabel((string)($lead['PurchaseTime'] ?? ''));

$salaryVal   = getLookupValue($pdo, $salaryLabel,  'salary');
$vehicleVal  = getLookupValue($pdo, $vehicleLabel, 'vehicle');
$branchVal   = getLookupValue($pdo, $branchLabel,  'branch');
$cityVal     = getLookupValue($pdo, $branchLabel,  'city');     // if your table supports it
$purtimeVal  = getLookupValue($pdo, $purtimeLabel, 'purtime');

// Defensive defaults if lookup returns null



$salaryVal  = $salaryVal  ?? '5000-7500';
$vehicleVal = $vehicleVal ?? '3008';
$cityVal    = $cityVal    ?? 'Riyadh';
$branchVal  = $branchVal  ?? 'Riyadh';
$purtimeVal = $purtimeVal ?? '1-3-months';



// Email may be missing in some snap leads -> stop submission if missing (because submitPeugeotLeadAr requires it)
$email = (string)($lead['Email'] ?? '');

// Build payload for Peugeot submit
$submitPayload = [
    'offer_id'     => 1,
    'fullName'     => $firstName ?: 'Unknown',
    'lastname'     => $lastName  ?: 'Lead',
    'email'        => $email,
    'mobile'       => $mobile05,
    'salary'       => $salaryVal,
    'model'        => $vehicleVal,
    'city'         => $cityVal,
    'branch'       => $branchVal,
    'purchaseTime' => $purtimeVal,

    // tracking
    'utm_source'   => 'Snapchat',
    'utm_campaign' => 'DD-C3-RAMADAN-2026_SA_AP_VN_OnGoing_SOC-RPR_A_LDS_LEAD_NA_NA',
    'campaign'     => 'DD-C3-RAMADAN-2026_SA_AP_VN_OnGoing_SOC-RPR_A_LDS_LEAD_NA_NA',
    'sourcee'      => 'Snapchat',
    'formtype'     => 'installment',

    // optional/checkboxes
    'terms'        => '1',
    'privacypolicy'=> 'on',
];

// If you want to allow missing email, change submitPeugeotLeadAr required list above.
// For now, if email/mobile invalid => log and exit gracefully.
if ($submitPayload['email'] === '' || $submitPayload['mobile'] === '') {
    error_log("Peugeot submit skipped: missing email or invalid mobile. lead_id={$data['lead_id']} email={$submitPayload['email']} mobile={$submitPayload['mobile']}".extractLabel($lead['Branch']));
    echo "Peugeot submit skipped (missing email or invalid mobile)\n";
    exit;
}

$submitResult = submitPeugeotLeadAr($submitPayload, [
    'post_url' => $peugeotSubmitUrl,
    'referer'  => $peugeotReferer,
    'timeout'  => 30,
]);


// Log (recommended)
error_log("Snapchat Peugeot submit result lead_id={$data['lead_id']}: ". extractLabel($lead['Branch']) . json_encode([
    'ok' => $submitResult['ok'],
    'http_code' => $submitResult['http_code'],
    'error' => $submitResult['error'],
], JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));

// Output summary
echo "Peugeot submit: " . ($submitResult['ok'] ? "OK" : "FAILED") . PHP_EOL;
echo "HTTP Code: " . $submitResult['http_code'] . PHP_EOL;
if (!empty($submitResult['error'])) {
    echo "cURL Error: " . $submitResult['error'] . PHP_EOL;
}

// If you want to see HTML response while testing (comment out in production):
// echo "Response:\n" . $submitResult['response'] . "\n";

?>