
­­­­­­­­­­­­­­­­­­
<!DOCTYPE html>
<html>
<?php
declare(strict_types=1);

/**
 * Facebook Lead Webhook Handler (Peugeot)
 * 1) Receives Facebook 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');
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-2026&sourcee=Facebook&utm_source=Facebook&utm_campaign=DD-C3-EOYO-2026";

// Optional: local log file (same folder)
$logFile = __DIR__ . "/facebook_leads.log";

// -----------------------------
// 1) HELPERS
// -----------------------------
function logLine(string $file, string $msg): void
{
    $line = "[" . date('Y-m-d H:i:s') . " Asia/Riyadh] " . $msg . PHP_EOL;
    @file_put_contents($file, $line, FILE_APPEND);
}

/**
 * Some connectors send "{Label:Value}" or "Label:Value"
 * This extracts the label part before ":" and removes braces.
 * If there is no ":", it returns the cleaned full string.
 */
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] ?? '');
}

/**
 * Arabic/Persian digits -> English digits
 */
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 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']   ?? 'Facebook',
        'utm_campaign' => $lead['utm_campaign'] ?? ($lead['campaign'] ?? 'DD-C3-EOYO-2026'),
        'campaign'     => $lead['campaign']     ?? 'DD-C3-EOYO-2026',
        'sourcee'      => $lead['sourcee']      ?? 'Facebook',
        '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
        'terms'         => (string)($lead['terms'] ?? '1'),
        'privacypolicy' => (string)($lead['privacypolicy'] ?? 'on'),
    ];

    // Align if formtype cash (same logic you had)
    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, // 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 : [];
    }

    return is_array($_POST) ? $_POST : [];
}

// -----------------------------
// 2) MAIN
// -----------------------------
header("Content-Type: text/plain; charset=utf-8");

$lead = readIncomingPayload();

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");
}

// Parse CreatedTime (Facebook example: 2026-01-02T12:52:03+0000)
$createdTimeUtc = null;
if (!empty($lead["CreatedTime"])) {
    try {
        $dt = new DateTime((string)$lead["CreatedTime"]);
        $dt->setTimezone(new DateTimeZone("UTC"));
        $createdTimeUtc = $dt->format("Y-m-d H:i:s");
    } catch (Exception $e) {
        $createdTimeUtc = null;
    }
}

// Map payload to DB columns (Facebook keys)
$data = [
    "ad_id"           => $lead["AdID"] ?? null,
    "ad_name"         => $lead["AdName"] ?? null,
    "adset_name"      => $lead["AdsetName"] ?? null,
    "branch"          => extractLabel($lead["Branch"] ?? null),
    "campaign_id"     => $lead["CampaignID"] ?? null,
    "campaign_name"   => $lead["CampaignName"] ?? null,
    "created_time_utc"=> $createdTimeUtc,
    "email"           => $lead["Email"] ?? null,
    "form_id"         => $lead["FormID"] ?? null,
    "form_name"       => $lead["FormName"] ?? null,
    "lead_id"         => $lead["LeadId"] ?? null,
    "page_id"         => $lead["PageID"] ?? null,
    "page_name"       => $lead["PageName"] ?? null,
    "full_name"       => $lead["FullName"] ?? null,
    "phone"           => $lead["Phone"] ?? null,
    "purchase_time"   => extractLabel($lead["PurTime"] ?? null),
    "salary"          => extractLabel($lead["Salary"] ?? null),
    "vehicle"         => extractLabel($lead["Vehicle"] ?? null),
    "platform"        => $lead["Plaform"] ?? ($lead["Platform"] ?? 'fb'),
    "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");
}

// -----------------------------
// 2.1) UPSERT into DB table
// -----------------------------
// TABLE NAME YOU SHOULD HAVE (create it if needed):
// peugeot_facebook_leads
$sql = "
INSERT INTO peugeot_facebook_leads (
  ad_id, ad_name, adset_name, branch,
  campaign_id, campaign_name, created_time_utc,
  email, form_id, form_name, lead_id,
  page_id, page_name, full_name, phone,
  purchase_time, salary, vehicle, platform, raw_payload
) VALUES (
  :ad_id, :ad_name, :adset_name, :branch,
  :campaign_id, :campaign_name, :created_time_utc,
  :email, :form_id, :form_name, :lead_id,
  :page_id, :page_name, :full_name, :phone,
  :purchase_time, :salary, :vehicle, :platform, :raw_payload
)
ON DUPLICATE KEY UPDATE
  ad_id            = VALUES(ad_id),
  ad_name          = VALUES(ad_name),
  adset_name       = VALUES(adset_name),
  branch           = VALUES(branch),
  campaign_id      = VALUES(campaign_id),
  campaign_name    = VALUES(campaign_name),
  created_time_utc = VALUES(created_time_utc),
  email            = VALUES(email),
  form_id          = VALUES(form_id),
  form_name        = VALUES(form_name),
  page_id          = VALUES(page_id),
  page_name        = VALUES(page_name),
  full_name        = VALUES(full_name),
  phone            = VALUES(phone),
  purchase_time    = VALUES(purchase_time),
  salary           = VALUES(salary),
  vehicle          = VALUES(vehicle),
  platform         = VALUES(platform),
  raw_payload      = VALUES(raw_payload)
";

try {
    $stmt = $pdo->prepare($sql);
    $stmt->execute($data);
    echo "OK: Lead stored. LeadId = " . $data["lead_id"] . PHP_EOL;

    logLine($GLOBALS['logFile'], "Stored lead_id={$data['lead_id']} platform={$data['platform']}");
} catch (PDOException $e) {
    http_response_code(500);
    logLine($GLOBALS['logFile'], "DB Error lead_id={$data['lead_id']} msg=" . $e->getMessage());
    exit("DB Error (insert/upsert): " . $e->getMessage() . PHP_EOL);
}

// -----------------------------
// 3) BUILD & SUBMIT TO PEUGEOT FORM
// -----------------------------
$rawName = (string)($lead['FullName'] ?? $lead['RFullName'] ?? '');
[$firstName, $lastName] = splitFullName($rawName);

// Phone: Arabic digits -> English -> normalize -> "05xxxxxxxx"
$mobile9  = normalizeSaudiMobile(convert2english((string)($lead['Phone'] ?? $lead['RPhone'] ?? '')));
$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['PurTime'] ?? ''));

// Lookups (types must match your table)
$salaryVal  = getLookupValue($pdo, $salaryLabel,  'salary');
$vehicleVal = getLookupValue($pdo, $vehicleLabel, 'vehicle');
$branchVal  = getLookupValue($pdo, $branchLabel,  'branch');
$cityVal    = getLookupValue($pdo, $branchLabel,  'city');     // if supported
$purtimeVal = getLookupValue($pdo, $purtimeLabel, 'purtime');  // or 'purchase_time' if that is your type

// 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 = (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'   => 'Facebook',
    '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'      => 'Facebook',
    'formtype'     => 'installment',

    // optional/checkboxes
    'terms'         => '1',
    'privacypolicy' => 'on',
];

// Skip if email/mobile invalid (same behavior you had)
if ($submitPayload['email'] === '' || $submitPayload['mobile'] === '') {
    $msg = "Peugeot submit skipped: missing email or invalid mobile. lead_id={$data['lead_id']} email={$submitPayload['email']} mobile={$submitPayload['mobile']}";
    error_log($msg);
    logLine($logFile, $msg);
    echo "Peugeot submit skipped (missing email or invalid mobile)\n";
    exit;
}

$submitResult = submitPeugeotLeadAr($submitPayload, [
    'post_url' => $peugeotSubmitUrl,
    'referer'  => $peugeotReferer,
    'timeout'  => 30,
]);

// Log result
error_log("Facebook 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));

logLine($logFile, "Submit lead_id={$data['lead_id']} ok=" . ($submitResult['ok'] ? '1' : '0') . " http=" . $submitResult['http_code']);

// 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;
}

// For testing only (comment out in production):
// echo "Response:\n" . $submitResult['response'] . "\n";

?>
