
­­­­­­­­­­­­­­­­­­
<!DOCTYPE html>
<html>
<?php
date_default_timezone_set('Asia/Riyadh');
ini_set('display_errors', 1);
error_reporting(E_ALL);

$servername = "localhost";
$username   = "balubaid_autozoneoffers";
$password   = "Vision@2050";
$database   = "balubaid_autozoneoffers";

$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$conn->query("SET time_zone = '+03:00'");

/**
 * Convert Arabic / Persian numbers to English
 */
function convert_persian_numbers($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);
    $string = str_replace($persian, $newNumbers, $string);

    return $string;
}

/**
 * Normalize Saudi mobile
 * 0501234567 => 966501234567
 */
function normalizeSaudiMobile($mobile) {
/*
    $mobile = trim(convert_persian_numbers($mobile));
    $mobile = preg_replace('/\D+/', '', $mobile);

    if (preg_match('/^05\d{8}$/', $mobile)) {
        return '966' . substr($mobile, 1);
    }

    if (preg_match('/^5\d{8}$/', $mobile)) {
        return '966' . $mobile;
    }

    if (preg_match('/^9665\d{8}$/', $mobile)) {
        return $mobile;
    } */

    return $mobile;
}

/**
 * Peugeot branch code map
 */
function getPeugeotBranchCode($branch) {
    $map = [
        'المجدوعي للسيارات جدة' => '0000065018',
        'المجدوعي للسيارات الرياض مخرج 13' => '0000071076',
        'المجدوعي للسيارات الرياض حي الربيع طريق الثمامة' => '0000130171',
        'المجدوعي للسيارات الخبر' => '0000062194',
    ];

    return $map[$branch] ?? null;
}

/**
 * Build and send lead to Mopar
 */
function sendLeadToMopar($lead) {
    $branchCode = getPeugeotBranchCode($lead['branch']);

    if (empty($branchCode)) {
        return [
            'ok' => false,
            'message' => 'Branch mapping not found',
            'success' => '1',
            'reference_id' => 'BRANCH_LOOKUP_FAILED',
            'http_code' => 0,
            'raw_response' => null
        ];
    }

    $sourcee  = $lead['sourcee'] ?? '';
    $campaign = $lead['campaign'] ?? '';

    $surl = "https://peugeotwebstore.me/ar/?utm_source=" . urlencode($sourcee) .
            "&utm_medium=SOC-RPR&utm_campaign=" . urlencode($campaign);

    $url = "https://www.mideast.mopar.com/bridge/psa/";

    $data = [
        "Enquiry_Type" => "Book_a_Test_Drive",
        "FirstName" => $lead['fullName'] ?? '',
        "LastName" => $lead['lastname'] ?? '',
        "Mobile" => normalizeSaudiMobile($lead['mobile'] ?? ''),
        "Email" => $lead['email'] ?? '',
        "DealerCode" => "007524A",
        "Shrm_SvCtr" => $branchCode,
        "Make" => "PEUGEOT",
        "Line" => $lead['model'] ?? '',
        "User_Comments" => $lead['salary'] ?? '',
        "Channel" => "",
        "Entry_Form" => "AR",
        "Source_Site" => "WebsiteOEM",
        "MasterKey" => ".",
        "FormCode" => ".",
        "Extended_Privacy" => "1",
        "Device_Used" => "Desktop",
        "Request_Origin" => $surl,
        "Model" => "",
        "Purchase_Timeframe" => $lead['purchaseTime'] ?? '',
        "Mileage" => "",
        "RegNo" => "",
        "Current_Make" => "",
        "Current_Line" => "",
        "Current_Model" => "",
        "Pref_Date" => "",
        "Parts_Needed" => "",
        "Include_Installation" => "",
        "TestDriveType" => "In Showroom",
        "Campaign_Source" => $sourcee,
        "Campaign_Name" => $campaign,
        "Campaign_Medium" => "SOC-RPR",
        "Market" => "Saudi",
        "Content" => "",
        "Term" => "",
        "Fund" => "",
        "Marketing_Communication_Consent" => "1"
    ];

    $payload = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

    $headers = [
        "Content-Type: application/json",
        "Accept: application/json"
    ];

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);

    $response = curl_exec($ch);
    $curlErr  = curl_errno($ch);
    $curlMsg  = curl_error($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($curlErr) {
        return [
            'ok' => false,
            'message' => 'cURL Error: ' . $curlMsg,
            'success' => '1',
            'reference_id' => 'CURL_' . $curlErr,
            'http_code' => $httpCode,
            'raw_response' => null
        ];
    }

    $decoded = json_decode($response, true);

    if (!is_array($decoded)) {
        return [
            'ok' => false,
            'message' => 'Invalid JSON response',
            'success' => '1',
            'reference_id' => 'INVALID_JSON',
            'http_code' => $httpCode,
            'raw_response' => $response
        ];
    }

    $message     = $decoded['message'] ?? '';
    $isError     = isset($decoded['isError']) ? (string)$decoded['isError'] : '0';
    $errorCode   = $decoded['errorCode'] ?? '';
    $ok          = ($httpCode >= 200 && $httpCode < 300 && $isError !== '1' && $message !== '');

    return [
        'ok' => $ok,
        'message' => $message,
        'success' => $isError,       // keeping your existing column logic
        'reference_id' => $errorCode,
        'http_code' => $httpCode,
        'raw_response' => $response
    ];
}

/**
 * Update lead after retry
 */
function updateLeadStatus($conn, $id, $apiResult) {
    $stmt = $conn->prepare("
        UPDATE leads3
        SET message = ?, success = ?, reference_id = ?
        WHERE id = ?
    ");

    if (!$stmt) {
        die("Prepare failed: " . $conn->error);
    }

    $stmt->bind_param(
        "sssi",
        $apiResult['message'],
        $apiResult['success'],
        $apiResult['reference_id'],
        $id
    );

    $stmt->execute();
    $stmt->close();
}

/**
 * Fetch only unsent / failed Mopar leads
 */
$sql = "
    SELECT id, utm_source, utm_campaign, formtype, offer_id, fullName, lastname, email, mobile,
           salary, model, nationality, bank, gender, city, branch, obligation, realestateLoan,
           obligationAmount, purchaseTime, terms, created_at, otp, otpVerified, campaign,
           sourcee, message, success, reference_id
    FROM leads3
    WHERE
    (
        message IS NULL
        OR TRIM(message) = ''
        OR success = '1'
    )
    AND
    (
        message IS NULL
        OR TRIM(message) <> 'Successfully Saved'
    )
		and date_format(created_at,'%Y-%m-%d') > '2026-02-28'
		and reference_id <> 'VALIDATION'
    ORDER BY id ASC
    LIMIT 50
";

$result = $conn->query($sql);

if (!$result) {
    die("Query failed: " . $conn->error);
}

echo "<pre>";
echo "Mopar resync started at " . date('Y-m-d H:i:s') . "\n\n";

$totalProcessed = 0;
$totalSuccess   = 0;
$totalFailed    = 0;

while ($lead = $result->fetch_assoc()) {
    $id = (int)$lead['id'];

    echo "Processing ID {$id} | Mobile: {$lead['mobile']} | Branch: {$lead['branch']}\n";

    $apiResult = sendLeadToMopar($lead);

    updateLeadStatus($conn, $id, $apiResult);

    $totalProcessed++;

    if ($apiResult['ok']) {
        $totalSuccess++;
        echo "  SUCCESS | Message: {$apiResult['message']}\n";
    } else {
        $totalFailed++;
        echo "  FAILED  | HTTP: {$apiResult['http_code']} | Ref: {$apiResult['reference_id']} | Message: {$apiResult['message']}\n";
    }

    echo "\n";
}

echo "Done.\n";
echo "Processed: {$totalProcessed}\n";
echo "Success: {$totalSuccess}\n";
echo "Failed: {$totalFailed}\n";
echo "</pre>";

$conn->close();
?>