
­­­­­­­­­­­­­­­­­­
<!DOCTYPE html>
<html>
<?php
declare(strict_types=1);

/**
 * TikTok / Unified lead saver + Submit to Peugeot form endpoint
 * - Stores lead into MySQL (upsert)
 * - Submits mapped lead to: https://ms.peugeotksaoffers.com/submit-lead-ar/
 *
 * Notes:
 * - This script reads payload from $_POST by default.
 * - It supports both Snapchat-like and Meta-like keys (as your unified handler already does).
 * - It uses the same lookup table: peugeot_lead_lookup_values (lookup_value, type, result_value)
 */

error_reporting(E_ALL);
ini_set('display_errors', '0');
date_default_timezone_set('Asia/Riyadh');

header("Content-Type: text/plain; charset=utf-8");

// -------------------- Helpers --------------------
function parseCreateTimeToUtc(?string $value): ?string {
    if (!$value) return null;
    $v = trim($value);
    if ($v === '' || stripos($v, 'NaN') !== false) return null;

    try {
        $dt = new DateTime($v);
        $dt->setTimezone(new DateTimeZone('UTC'));
        return $dt->format('Y-m-d H:i:s');
    } catch (Exception $e) {
        return null;
    }
}

function detectPlatform(array $payload): string {
    // Snapchat payload often has AdAccountID, FormID, AdSquadID, StrategyType
    if (isset($payload['AdAccountID']) || isset($payload['FormID']) || isset($payload['AdSquadID'])) {
        return 'snapchat';
    }
    // Meta instant form sample has PageId + LeadSource + AdGroupId
    if (isset($payload['PageId']) || isset($payload['LeadSource']) || isset($payload['AdGroupId'])) {
        return 'meta';
    }
    // TikTok / other: keep as tiktok if you want a fixed value
    return 'tiktok';
}

function extractLabel(?string $input): string {
    $input = (string)$input;
    $input = trim($input);
    if ($input === '') return '';
    $clean = trim($input, "{} \t\n\r\0\x0B");
    $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);
}

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);

    return preg_match('/^5\d{8}$/', $number) ? $number : null;
}

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];
}

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;
}

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);

    // required fields for the PHP submit script you shared
    $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 = [
        'utm_source'   => $lead['utm_source']   ?? 'TikTok',
        'utm_campaign' => $lead['utm_campaign'] ?? ($lead['campaign'] ?? 'DD-C3-EOYO-2026'),
        'campaign'     => $lead['campaign']     ?? 'DD-C3-EOYO-2026',
        'sourcee'      => $lead['sourcee']      ?? 'TikTok',
        'formtype'     => $lead['formtype']     ?? 'installment',
        'offer_id'     => (string)$lead['offer_id'],

        'fullName'     => (string)$lead['fullName'],
        'lastname'     => (string)$lead['lastname'],
        'email'        => (string)$lead['email'],
        'mobile'       => (string)$lead['mobile'],

        'model'        => (string)$lead['model'],
        'purchaseTime' => (string)($lead['purchaseTime'] ?? '1-3-months'),

        'nationality'     => (string)($lead['nationality'] ?? 'Non-Saudi'),
        'bank'            => (string)($lead['bank'] ?? 'Others'),
        'gender'          => (string)($lead['gender'] ?? 'Male'),
        'salary'          => (string)($lead['salary'] ?? '5000-7500'),

        'city'            => (string)$lead['city'],
        'branch'          => (string)$lead['branch'],

        'obligation'       => (string)($lead['obligation'] ?? 'no'),
        'realestateLoan'   => (string)($lead['realestateLoan'] ?? 'no'),
        'obligationAmount' => (string)($lead['obligationAmount'] ?? ''),

        // some forms expect these
        'terms'         => (string)($lead['terms'] ?? '1'),
        'privacypolicy' => (string)($lead['privacypolicy'] ?? 'on'),
    ];

    $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, // enable for debugging if needed
    ];
}

// -------------------- INPUT --------------------
// In production this will be your webhook
$lead = is_array($_POST) ? $_POST : [];
if (empty($lead)) {
    http_response_code(400);
    exit("Bad Request: empty payload\n");
}

// -------------------- DB config --------------------
$dbHost = "localhost";
$dbName = "balubaid_autozoneoffers";
$dbUser = "balubaid_autozoneoffers";
$dbPass = "Vision@2050";
$dsn = "mysql:host={$dbHost};dbname={$dbName};charset=utf8mb4";

$platform = detectPlatform($lead);
$createTimeUtc = parseCreateTimeToUtc($lead['CreateTime'] ?? null);

// Normalize “ad name” key differences: AdName vs Adname
$adName = $lead['AdName'] ?? ($lead['Adname'] ?? null);

// Normalize “ad group” key differences: AdSquad vs AdGroup
$adGroupId   = $lead['AdGroupId']   ?? ($lead['AdSquadID'] ?? null);
$adGroupName = $lead['AdGroupName'] ?? ($lead['AdSquadName'] ?? null);

$leadIdRaw = (string)($lead['LeadId'] ?? '');
if ($leadIdRaw === '') {
    http_response_code(400);
    exit("LeadId is required.\n");
}

// Make globally-unique lead id
$leadIdUnique = $platform . ':' . $leadIdRaw;

// Build unified row
$data = [
    "platform"        => $platform,
    "lead_source"     => $lead["LeadSource"] ?? null,

    "lead_id"         => $leadIdUnique,
    "email"           => $lead["Email"] ?? null,
    "full_name"       => $lead["Name"] ?? null,
    "phone"           => $lead["Phone"] ?? null,

    "campaign_id"     => $lead["CampaignId"] ?? null,
    "campaign_name"   => $lead["CampaignName"] ?? null,

    "ad_group_id"     => $adGroupId,
    "ad_group_name"   => $adGroupName,

    "ad_id"           => $lead["AdId"] ?? null,
    "ad_name"         => $adName,

    "page_id"         => $lead["PageId"] ?? null,

    "branch"          => $lead["Branch"] ?? null,
    "purchase_time"   => $lead["PurchaseTime"] ?? null,
    "salary"          => $lead["Salary"] ?? null,
    "vehicle"         => $lead["Vehicle"] ?? null,

    "create_time_utc" => $createTimeUtc,

    "raw_payload"     => json_encode($lead, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
];

// -------------------- UPSERT SQL --------------------
$sql = "
INSERT INTO peugeot_tiktok_leads (
  platform, lead_source, lead_id, email, full_name, phone,
  campaign_id, campaign_name,
  ad_group_id, ad_group_name,
  ad_id, ad_name,
  page_id,
  branch, purchase_time, salary, vehicle,
  create_time_utc,
  raw_payload
) VALUES (
  :platform, :lead_source, :lead_id, :email, :full_name, :phone,
  :campaign_id, :campaign_name,
  :ad_group_id, :ad_group_name,
  :ad_id, :ad_name,
  :page_id,
  :branch, :purchase_time, :salary, :vehicle,
  :create_time_utc,
  :raw_payload
)
ON DUPLICATE KEY UPDATE
  platform        = VALUES(platform),
  lead_source     = VALUES(lead_source),
  email           = VALUES(email),
  full_name       = VALUES(full_name),
  phone           = VALUES(phone),
  campaign_id     = VALUES(campaign_id),
  campaign_name   = VALUES(campaign_name),
  ad_group_id     = VALUES(ad_group_id),
  ad_group_name   = VALUES(ad_group_name),
  ad_id           = VALUES(ad_id),
  ad_name         = VALUES(ad_name),
  page_id         = VALUES(page_id),
  branch          = VALUES(branch),
  purchase_time   = VALUES(purchase_time),
  salary          = VALUES(salary),
  vehicle         = VALUES(vehicle),
  create_time_utc = VALUES(create_time_utc),
  raw_payload     = VALUES(raw_payload)
";

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,
    ]);

    $stmt = $pdo->prepare($sql);
    $stmt->execute($data);

    echo "OK: Lead stored. lead_id = {$data['lead_id']}\n";

    // -------------------- SUBMIT TO PEUGEOT FORM --------------------
    $rawName = (string)($lead['Name'] ?? '');
    [$firstName, $lastName] = splitFullName($rawName);

    $mobile9  = normalizeSaudiMobile(convert2english((string)($lead['Phone'] ?? '')));
    $mobile05 = $mobile9 ? ('0' . $mobile9) : '';

    // Labels -> mapped values
    $salaryLabel  = extractLabel((string)($lead['Salary'] ?? ''));
    $vehicleLabel = extractLabel((string)($lead['Vehicle'] ?? ''));
    $branchLabel  = extractLabel((string)($lead['Branch'] ?? ''));
    $purLabel     = extractLabel((string)($lead['PurchaseTime'] ?? ''));

    $salaryVal  = getLookupValue($pdo, $salaryLabel,  'salary')  ?? '5000-7500';
    $vehicleVal = getLookupValue($pdo, $vehicleLabel, 'vehicle') ?? '3008';
    $branchVal  = getLookupValue($pdo, $branchLabel,  'branch')  ?? 'Riyadh';
    $cityVal    = getLookupValue($pdo, $branchLabel,  'city')    ?? 'Riyadh';
    $purVal     = getLookupValue($pdo, $purLabel,     'purtime') ?? '1-3-months';

    $email = (string)($lead['Email'] ?? '');

    // Build submit payload
    $submitPayload = [
        'offer_id'     => 1,
        'fullName'     => $firstName ?: 'Unknown',
        'lastname'     => $lastName  ?: 'Lead',
        'email'        => $email,
        'mobile'       => $mobile05,
        'salary'       => $salaryVal,
        'model'        => $vehicleVal,
        'city'         => $cityVal,
        'branch'       => $branchVal,
        'purchaseTime' => $purVal,

        'utm_source'   => 'TikTok',
        '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'      => 'TikTok',
        'formtype'     => 'installment',

        'terms'        => '1',
        'privacypolicy'=> 'on',
    ];

    // Prevent calling submit if required values missing
    if ($submitPayload['email'] === '' || $submitPayload['mobile'] === '') {
        echo "Peugeot submit skipped (missing email or invalid mobile)\n";
        exit;
    }

    $submitResult = submitPeugeotLeadAr($submitPayload, [
        'post_url' => 'https://ms.peugeotksaoffers.com/submit-lead-ar/',
        'referer'  => 'https://ms.peugeotksaoffers.com/lead-form-ar/1/?campaign=DD-C3-EOYO-2025&sourcee=Google&utm_source=Google&utm_campaign=DD-C3-EOYO-2025',
        'timeout'  => 30,
    ]);
    



// Log (recommended)
error_log("TikTok Peugeot submit result lead_id={$data['lead_id']}: " . json_encode([
    'ok' => $submitResult['ok'],
    'http_code' => $submitResult['http_code'],
    'error' => $submitResult['error'],
], JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));

    echo "Peugeot submit: " . ($submitResult['ok'] ? "OK" : "FAILED") . "\n";
    echo "HTTP Code: {$submitResult['http_code']}\n";
    if (!empty($submitResult['error'])) {
        echo "cURL Error: {$submitResult['error']}\n";
    }

} catch (PDOException $e) {
    http_response_code(500);
    echo "DB Error: " . $e->getMessage() . "\n";
}