
­­­­­­­­­­­­­­­­­­
<!DOCTYPE html>
<html>
<?php
declare(strict_types=1);

function analyzeStringAmount(?string $input): array
{
    // Handle NULL or empty input safely
    if ($input === null || trim($input) === '') {
        return [
            'has_amount' => 'No',
            'amount'     => 0
        ];
    }

    // Normalize input
    $input = trim($input);

    // Convert Arabic digits to English
    $arabic  = ['٠','١','٢','٣','٤','٥','٦','٧','٨','٩'];
    $english = ['0','1','2','3','4','5','6','7','8','9'];
    $normalized = str_replace($arabic, $english, $input);

    // Extract numbers (integers & decimals)
    preg_match_all('/\d+(?:\.\d+)?/', $normalized, $matches);

    $amount = 0;

    if (!empty($matches[0])) {
        foreach ($matches[0] as $num) {
            $num = (float) $num;
            if ($num > $amount) {
                $amount = $num;
            }
        }
    }

    return [
        'has_amount' => $amount > 0 ? 'Yes' : 'No',
        'amount'     => $amount > 0 ? $amount : 0
    ];
}

function submitHondaServiceLead(array $data, array $options = []): array
{
    $endpoint = $options['endpoint']
        ?? 'https://services.core3consultancy.com/icaur/social_lead_webhook.php?token=MY_SECRET_TOKEN_123';

    $timeout  = $options['timeout'] ?? 30;

    // -----------------------------
    // Required fields mapping
    // -----------------------------
    $postData = [
        'location'   => $data['location']   ?? '',
        'phone' => $data['phone'] ?? '',
        'email'    => $data['email']    ?? '',
        'first_name'  => $data['first_name']  ?? '',
        'source'      => $data['source']      ?? '',
        'gender'      => $data['gender']      ?? '',
        'formid'      => $data['formid']      ?? '',
        'payment_option'  => $data['payment_option']  ?? '',
        'car_color'      => $data['car_color']      ?? '',
        'campaign'    => $data['campaign']    ?? '',
        'trim'     => $data['trim']     ?? '',
        'request_id'     => $data['request_id']     ?? '',
    ];

    $ch = curl_init($endpoint);

    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => json_encode($postData, JSON_UNESCAPED_UNICODE),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => $timeout,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_HTTPHEADER     => [
            'Content-Type: application/x-www-form-urlencoded',
        ],
    ]);

    $response   = curl_exec($ch);
    $httpCode   = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError  = curl_error($ch);

    curl_close($ch);

    return [
        'success'   => ($curlError === '' && $httpCode === 200),
        'http_code' => $httpCode,
        'response'  => $response,
        'error'     => $curlError ?: null,
        'payload'   => $postData,
    ];
}


function extractLabel($input) {
    // Remove curly braces
    $clean = trim($input, "{}");

    // Split on colon
    $parts = explode(":", $clean);

    // Return the label part
    return $parts[0] ?? '';
}

function convert2english($string) {
    $newNumbers = range(0, 9);
    // 1. Persian HTML decimal
    $persianDecimal = array('&#1776;', '&#1777;', '&#1778;', '&#1779;', '&#1780;', '&#1781;', '&#1782;', '&#1783;', '&#1784;', '&#1785;');
    // 2. Arabic HTML decimal
    $arabicDecimal = array('&#1632;', '&#1633;', '&#1634;', '&#1635;', '&#1636;', '&#1637;', '&#1638;', '&#1639;', '&#1640;', '&#1641;');
    // 3. Arabic Numeric
    $arabic = array('٠', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩');
    // 4. Persian Numeric
    $persian = array('۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹');

    $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 getLookupValue($lookup_value,$type) {
    // Database connection parameters
    $servername = "localhost";
    $username = "balubaid_honda_native_forms";
    $password = "Vision@2050";
    $dbname = "balubaid_honda_native_forms_leads";
    

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);

    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    // Prepare SQL query to prevent SQL injection
    $stmt = $conn->prepare("SELECT result_value FROM core3_lookup_values   WHERE lookup_value = ? and type = ?");
    $stmt->bind_param("ss", $lookup_value,$type);  // "s" means string type

    // Execute the query
    $stmt->execute();
    $stmt->bind_result($result_value);

    // Fetch the result
    if ($stmt->fetch()) {
        $stmt->close();
        $conn->close();
        return $result_value;
    } else {
        $stmt->close();
        $conn->close();
        return null; // Return null if no match is found
    }
}


function getLookupValue2($lookup_value, $type) {
    // Database connection parameters
    $servername = "localhost";
    $username = "balubaid_honda_native_forms";
    $password = "Vision@2050";
    $dbname = "balubaid_honda_native_forms_leads";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);

    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    // Prepare SQL query to prevent SQL injection
    $stmt = $conn->prepare("SELECT result_value FROM core3_lookup_values WHERE lookup_value = ? AND type = ?");
    $stmt->bind_param("ss", $lookup_value, $type);

    // Execute the query
    $stmt->execute();
    $stmt->bind_result($result_value);

    // Fetch the result
    if ($stmt->fetch()) {
        $stmt->close();
        $conn->close();
        return $result_value;
    } else {
        $stmt->close();
        $conn->close();
        return $lookup_value; // ✅ Return original passed value instead of null
    }
}

function normalizeSaudiMobile($input)
{
    // Remove all non-numeric characters
    $number = preg_replace('/\D+/', '', $input);

    // If starts with country code 966
    if (strpos($number, '966') === 0) {
        $number = substr($number, 3);
    }

    // If starts with leading zero (05xxxxxxxx)
    if (strpos($number, '0') === 0) {
        $number = substr($number, 1);
    }

    // Final validation: must be 9 digits and start with 5
    if (preg_match('/^5\d{8}$/', $number)) {
        return $number;
    }

    return null; // Invalid number
}



error_reporting(E_ALL);
ini_set('display_errors', '0');
date_default_timezone_set('Asia/Riyadh');

/* ------------------ DB CONFIG ------------------ */
$dbHost = "localhost";
$dbName = "balubaid_honda_native_forms_leads";
$dbUser = "balubaid_honda_native_forms";
$dbPass = "Vision@2050";

$dsn = "mysql:host=$dbHost;dbname=$dbName;charset=utf8mb4";
$pdo = new PDO($dsn, $dbUser, $dbPass, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);

/* ------------------ INPUT DATA ------------------ */
/* Replace with $_POST or JSON payload parsing */
$data = [
    'adid'          => '120239468389660023',
    'adname'        => 'ZRV',
    'adsquadename'  => 'ZRV',
    'branch'        => 'جدة - فرع طريق المدينة',
    'channel'       => 'Facebook',
    'city'          => 'الرياض',
    'cmpname'       => 'Honda Saudi Jan 2026 FB',
    'createdat'     => '2026-01-06T08:28:46+0000',
    'email'         => 'Meng.tarekabozaid@gamil.com',
    'fname'         => 'Tarek Abozaid',
    'formname'      => 'Honda Saudi - Dynamic - C3 V2',
    'leadid'        => '1215791713842053',
    'leadpreferred' => 'Pref',
    'mobile'        => '+966546008718',
    'paymethod'     => 'قسط',
    'purchasetime'  => 'فورًا',
    'salary'        => 'أكثر من 10 آلف',
    'strategy'      => 'Leads'
];



$_POST['mobile'] = "0".normalizeSaudiMobile(convert2english($_POST['mobile']));
$_POST['paymethod'] = getLookupValue(extractLabel($_POST['paymethod']),'paymethod');
$_POST['purchasetime'] = getLookupValue(extractLabel($_POST['purchasetime']),'purtime');
$_POST['gender'] = getLookupValue(extractLabel($_POST['gender']),'gender');
$_POST['color'] = getLookupValue(extractLabel($_POST['color']),'color');
$_POST['trim'] = getLookupValue(extractLabel($_POST['trim']),'trim');
$_POST['salary'] = getLookupValue(extractLabel($_POST['salary']),'salary');
$_POST['obligation'] = getLookupValue2(extractLabel($_POST['obligation']),'obligation');
$_POST['isobligation'] = analyzeStringAmount($_POST['obligation'])['has_amount'];
$_POST['obligation_amount'] = analyzeStringAmount($_POST['obligation'])['amount'];
$_POST['city'] = getLookupValue(extractLabel($_POST['city']),'city');
$_POST['model'] = getLookupValue(extractLabel($_POST['adname']),'model');
$_POST['preftime'] = getLookupValue(extractLabel($_POST['preftime']),'preftime');
$_POST['fullname'] = $_POST['fname']." ".$_POST['lname'];

$data = $_POST;

/* ------------------ Helpers ------------------ */
function normalizeMobile(?string $mobile): string {
    $m = trim((string)$mobile);
    // Keep + and digits only
    $m = preg_replace('/[^\d+]/', '', $m) ?? '';
    return $m;
}

function metaTimeToRiyadh(?string $value): ?string {
    if (!$value) return null;
    $v = trim($value);
    if ($v === '' || stripos($v, 'NaN') !== false) return null;
    $dt = new DateTime($v); // handles 2026-01-06T08:28:46+0000
    $dt->setTimezone(new DateTimeZone('Asia/Riyadh'));
    return $dt->format('Y-m-d H:i:s');
}

$mobile    = normalizeMobile($data['mobile'] ?? '');
$leadId    = (string)($data['leadid'] ?? '');
$createdAt = metaTimeToRiyadh($data['createdat'] ?? null);

if ($mobile === '' || $leadId === '') {
    http_response_code(400);
    echo "Missing required fields: mobile or leadid";
    exit;
}

try {
    $pdo->beginTransaction();

    /* ----------------------------------------------
       1) Check if mobile exists in last 15 days
       - We compare against honda_leads.createdat if available,
         otherwise fallback to created_at timestamp.
    ---------------------------------------------- */
    $dupCheckSql = "
        SELECT leadid, createdat
        FROM core3_leads
        WHERE mobile = :mobile
          AND (
                (createdat IS NOT NULL AND createdat >= (NOW() - INTERVAL 15 DAY))
             OR (createdat IS NULL AND created_at >= (NOW() - INTERVAL 15 DAY))
          )
        ORDER BY COALESCE(createdat, created_at) DESC
        LIMIT 1
    ";
    $dupStmt = $pdo->prepare($dupCheckSql);
    $dupStmt->execute([':mobile' => $mobile]);
    $existing = $dupStmt->fetch();

    if ($existing) {
        /* ----------------------------------------------
           2) Dump into duplicate table and stop
        ---------------------------------------------- */
        $insDupSql = "
            INSERT INTO core3_duplicate_leads (
                leadid, mobile, original_lead_id, original_createdat, reason,
                adid, adname, adsquadename, cmpname, strategy, channel, formname,
                fname, email, branch, city, paymethod, purchasetime, preftime, model, gender, obligations, isobligations, obligationsamount, salary, leadpreferred,color,trim,
                createdat
            ) VALUES (
                :leadid, :mobile, :original_lead_id, :original_createdat, :reason,
                :adid, :adname, :adsquadename, :cmpname, :strategy, :channel, :formname,
                :fname, :email, :branch, :city, :paymethod, :purchasetime, :preftime, :model, :gender, :obligations, :isobligations, :obligationsamount, :salary, :leadpreferred, :color, :trim,
                :createdat
            )
            ON DUPLICATE KEY UPDATE
                dumped_at = CURRENT_TIMESTAMP,
                reason = VALUES(reason)
        ";
        $insDup = $pdo->prepare($insDupSql);
        $insDup->execute([
            ':leadid'             => $leadId,
            ':mobile'             => $mobile,
            ':original_lead_id'    => $existing['leadid'] ?? null,
            ':original_createdat'  => $existing['createdat'] ?? null,
            ':reason'             => 'Mobile duplicate within 15 days',

            ':adid'               => $data['adid'] ?? null,
            ':adname'             => $data['adname'] ?? null,
            ':adsquadename'       => $data['adsquadename'] ?? null,
            ':cmpname'            => $data['cmpname'] ?? null,
            ':strategy'           => $data['strategy'] ?? null,
            ':channel'            => $data['channel'] ?? null,
            ':formname'           => $data['formname'] ?? null,

            ':fname'              => $data['fullname'] ?? null,
            ':email'              => $data['email'] ?? null,
            ':branch'             => $data['branch'] ?? null,
            ':city'               => $data['city'] ?? null,

            ':paymethod'          => $data['paymethod'] ?? null,
            ':color'          => $data['color'] ?? null,
            ':trim'          => $data['trim'] ?? null,
            ':color'          => $data['color'] ?? null,
            ':trim'          => $data['trim'] ?? null,
            ':preftime'       => $data['preftime'] ?? null,
            ':model'       => $data['model'] ?? null,
            ':purchasetime'       => $data['purchasetime'] ?? null,
            ':gender'             => $data['gender'] ?? null,
            ':obligations'             => $data['obligation'] ?? null,
            ':isobligations'             => $data['isobligation'] ?? null,
            ':obligationsamount'             => $data['obligation_amount'] ?? null,
            ':salary'             => $data['salary'] ?? null,
            ':leadpreferred'      => $data['leadpreferred'] ?? null,

            ':createdat'          => $createdAt
        ]);

        $pdo->commit();
        echo "Duplicate lead (mobile exists within 15 days). Dumped to duplicate table.";
        exit;
    }

    /* ----------------------------------------------
       3) Not duplicate: insert/upsert into main table
    ---------------------------------------------- */
    $insMainSql = "
        INSERT INTO core3_leads (
            leadid, adid, adname, adsquadename, cmpname, strategy, channel,
            formname, fname, email, mobile, branch, city,
            paymethod, purchasetime, preftime, model, gender, obligations, isobligations, obligationsamount, salary, leadpreferred, color, trim, createdat
        ) VALUES (
            :leadid, :adid, :adname, :adsquadename, :cmpname, :strategy, :channel,
            :formname, :fname, :email, :mobile, :branch, :city,
            :paymethod, :purchasetime, :preftime, :model, :gender, :obligations, :isobligations, :obligationsamount, :salary, :leadpreferred, :color, :trim, :createdat
        )
        ON DUPLICATE KEY UPDATE
            adname = VALUES(adname),
            cmpname = VALUES(cmpname),
            mobile = VALUES(mobile),
            branch = VALUES(branch),
            city = VALUES(city),
            paymethod = VALUES(paymethod),
            purchasetime = VALUES(purchasetime),
            salary = VALUES(salary),
            leadpreferred = VALUES(leadpreferred),
            createdat = VALUES(createdat),
            updated_at = CURRENT_TIMESTAMP
    ";
    $insMain = $pdo->prepare($insMainSql);
    $insMain->execute([
        ':leadid'        => $leadId,
        ':adid'          => $data['adid'] ?? null,
        ':adname'        => $data['adname'] ?? null,
        ':adsquadename'  => $data['adsquadename'] ?? null,
        ':cmpname'       => $data['cmpname'] ?? null,
        ':strategy'      => $data['strategy'] ?? null,
        ':channel'       => $data['channel'] ?? null,
        ':formname'      => $data['formname'] ?? null,
        ':fname'         => $data['fullname'] ?? null,
        ':email'         => $data['email'] ?? null,
        ':mobile'        => $mobile,
        ':branch'        => $data['branch'] ?? null,
        ':city'          => $data['city'] ?? null,
        ':paymethod'     => $data['paymethod'] ?? null,
        ':preftime'  => $data['preftime'] ?? null,
        ':model'  => $data['model'] ?? null,
        ':purchasetime'  => $data['purchasetime'] ?? null,
        ':color'  => $data['color'] ?? null,
        ':trim'  => $data['trim'] ?? null,
        ':salary'        => $data['salary'] ?? null,
        ':gender'        => $data['gender'] ?? null,
        ':obligations'   => $data['obligation'] ?? null,
        ':isobligations' => $data['isobligation'] ?? null,
        ':obligationsamount' => $data['obligation_amount'] ?? null,
        ':leadpreferred' => $data['leadpreferred'] ?? null,
        ':createdat'     => $createdAt
    ]);

    $pdo->commit();
    echo "Lead stored successfully in main table.";
    
    $xxhlead = [
    'location'   => $data['city'],
    'phone' => $data['mobile'],
    'your-car'    => $data['model'],
    'email'  => $data['email'],
    'first_name'   => $data['fullname'],
    'source'      => $data['channel'],
    'gender'      => $data['gender'],
    'formid'      => '565845759',
    'payment_option'  => $data['paymethod'],
    'salary'      => $data['salary'],
    'campaign'    => $data['cmpname'],
    'PurTime'     => $data['purchasetime'],
    'car_color'     => $data['color'],
    'trim'     => $data['trim'],
    'request_id' => $data['leadid'],
    'PrefTime'    => $data['preftime'],
    'isobligations'    => $data['isobligation'],
    'obligation_amount'    => $data['obligation_amount']
];

$result = submitHondaServiceLead($xxhlead);

if ($result['success']) {
    echo "Lead submitted successfully\n";
} else {
    echo "Failed to submit lead\n";
    print_r($result);
}
    
} catch (Throwable $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    http_response_code(500);
    echo "Server error while saving lead.";
}