
­­­­­­­­­­­­­­­­­­
<!DOCTYPE html>
<html>
<?php
declare(strict_types=1);


function sendLeadAndLogToMySQL(array $payload, array $opts): array
{
    // -----------------------------
    // 1) Required options
    // -----------------------------
    $endpoint = $opts['endpoint'] ?? '';
    if ($endpoint === '') {
        throw new InvalidArgumentException("Missing opts['endpoint'].");
    }

    /** @var PDO $pdo */
    $pdo = $opts['pdo'] ?? null;
    if (!$pdo instanceof PDO) {
        throw new InvalidArgumentException("Missing opts['pdo'] (PDO instance).");
    }

    // Basic Auth (as per your Postman request)
    $basicUser = $opts['basic_user'] ?? '';
    $basicPass = $opts['basic_pass'] ?? '';
    if ($basicUser === '' || $basicPass === '') {
        throw new InvalidArgumentException("Missing Basic Auth creds opts['basic_user'] and opts['basic_pass'].");
    }

    // Optional headers
    // If you also need an extra Authorization header (Bearer/Token), pass it in opts['auth_header'].
    // It will be sent, but redacted in DB logs.
    $authHeader = $opts['auth_header'] ?? null; // e.g. "Bearer xxxxx" or "Basic xxxxx"
    $timeout    = (int)($opts['timeout'] ?? 30);
    $provider   = $opts['provider'] ?? 'almajdouie-soa';
    $method     = 'POST';

    // -----------------------------
    // 2) Prepare request
    // -----------------------------
    $jsonBody = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    if ($jsonBody === false) {
        throw new RuntimeException("JSON encode failed: " . json_last_error_msg());
    }

    $requestHeaders = [
        'Content-Type: application/json',
        'Accept: application/json',
    ];

    if (is_string($authHeader) && trim($authHeader) !== '') {
        $requestHeaders[] = 'Authorization: ' . trim($authHeader);
    }

    // For DB log: redact sensitive headers
    $headersForLog = [];
    foreach ($requestHeaders as $h) {
        if (stripos($h, 'Authorization:') === 0) {
            $headersForLog[] = 'Authorization: [REDACTED]';
        } else {
            $headersForLog[] = $h;
        }
    }

    $requestHeadersJson = json_encode($headersForLog, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

    // -----------------------------
    // 3) cURL call
    // -----------------------------
    $ch = curl_init($endpoint);

    // Capture response headers too
    $responseHeadersRaw = '';
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => $jsonBody,
        CURLOPT_HTTPHEADER     => $requestHeaders,

        // Basic auth
        CURLOPT_HTTPAUTH       => CURLAUTH_BASIC,
        CURLOPT_USERPWD        => $basicUser . ':' . $basicPass,

        // timeouts
        CURLOPT_CONNECTTIMEOUT => $timeout,
        CURLOPT_TIMEOUT        => $timeout,

        // SSL (keep verify true in production)
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_SSL_VERIFYHOST => 2,

        // response headers capture
        CURLOPT_HEADERFUNCTION => function($curl, $headerLine) use (&$responseHeadersRaw) {
            $responseHeadersRaw .= $headerLine;
            return strlen($headerLine);
        },
    ]);

    $start = microtime(true);
    $responseBody = curl_exec($ch);
    $end   = microtime(true);

    $durationMs = (int)round(($end - $start) * 1000);

    $curlErrNo  = curl_errno($ch);
    $curlErrMsg = curl_error($ch);
    $httpCode   = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);

    curl_close($ch);

    // If curl_exec fails, $responseBody can be false
    if ($responseBody === false) {
        $responseBody = '';
    }

    // -----------------------------
    // 4) Insert log into MySQL
    // -----------------------------
    $sql = "
        INSERT INTO deepal_api_request_logs
        (provider, endpoint, method,
         request_headers_json, request_body_json,
         auth_type, auth_username,
         response_http_code, response_headers_raw, response_body,
         curl_errno, curl_error, duration_ms, created_at)
        VALUES
        (:provider, :endpoint, :method,
         :req_headers, :req_body,
         :auth_type, :auth_username,
         :http_code, :resp_headers, :resp_body,
         :curl_errno, :curl_error, :duration_ms, NOW())
    ";

    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        ':provider'      => $provider,
        ':endpoint'      => $endpoint,
        ':method'        => $method,

        ':req_headers'   => $requestHeadersJson,
        ':req_body'      => $jsonBody,

        ':auth_type'     => 'basic',
        ':auth_username' => $basicUser,

        ':http_code'     => $httpCode,
        ':resp_headers'  => $responseHeadersRaw,
        ':resp_body'     => (string)$responseBody,

        ':curl_errno'    => $curlErrNo ?: null,
        ':curl_error'    => ($curlErrNo ? $curlErrMsg : null),
        ':duration_ms'   => $durationMs,
    ]);

    $logId = (int)$pdo->lastInsertId();

    // -----------------------------
    // 5) Return a clean result
    // -----------------------------
    return [
        'ok'          => ($curlErrNo === 0 && $httpCode >= 200 && $httpCode < 300),
        'log_id'      => $logId,
        'http_code'   => $httpCode,
        'duration_ms' => $durationMs,
        'curl_errno'  => $curlErrNo,
        'curl_error'  => $curlErrNo ? $curlErrMsg : null,
        'response'    => $responseBody, // raw response
    ];
}

function submitHondaServiceLead(array $data, array $options = []): array
{
    $endpoint = $options['endpoint']
        ?? 'https://honda.core3.agency/service_request/get_service.php?confirm=@CRM1';

    $timeout  = $options['timeout'] ?? 30;

    // -----------------------------
    // Required fields mapping
    // -----------------------------
    $postData = [
        'your-city'   => $data['your-city']   ?? '',
        'phonenumber' => $data['phonenumber'] ?? '',
        'your-car'    => $data['your-car']    ?? '',
        'your-email'  => $data['your-email']  ?? '',
        'your-name'   => $data['your-name']   ?? '',
        'source'      => $data['source']      ?? '',
        'gender'      => $data['gender']      ?? '',
        'formid'      => $data['formid']      ?? '',
        'pay-method'  => $data['pay-method']  ?? '',
        'salary'      => $data['salary']      ?? '',
        'campaign'    => $data['campaign']    ?? '',
        'PurTime'     => $data['PurTime']     ?? '',
        'PrefTime'    => $data['PrefTime']    ?? '',
    ];

    $ch = curl_init($endpoint);

    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => http_build_query($postData),
        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_changan_forms_leads";
    $password = "Vision@2050";
    $dbname = "balubaid_changan_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 deepal_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 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_changan_forms_leads";
$dbUser = "balubaid_changan_forms_leads";
$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['mobile2'] = 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['salary'] = getLookupValue(extractLabel($_POST['salary']),'salary');
$_POST['city'] = getLookupValue(extractLabel($_POST['branch']),'city');
$_POST['model'] = getLookupValue(extractLabel($_POST['adname']),'model');
$_POST['preftime'] = getLookupValue(extractLabel($_POST['preftime']),'preftime');
$_POST['fullname'] = $_POST['fname']." ".$_POST['lname'];
$_POST['branch'] = getLookupValue(extractLabel($_POST['branch']),'branch');

$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 deepal_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 deepal_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, salary, leadpreferred,
                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, :salary, :leadpreferred,
                :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,
            ':preftime'       => $data['preftime'] ?? null,
            ':model'       => $data['model'] ?? null,
            ':purchasetime'       => $data['purchasetime'] ?? null,
            ':gender'             => $data['gender'] ?? 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 deepal_leads (
            leadid, adid, adname, adsquadename, cmpname, strategy, channel,
            formname, fname, email, mobile, branch, city,
            paymethod, purchasetime, preftime, model, gender, salary, leadpreferred, createdat
        ) VALUES (
            :leadid, :adid, :adname, :adsquadename, :cmpname, :strategy, :channel,
            :formname, :fname, :email, :mobile, :branch, :city,
            :paymethod, :purchasetime, :preftime, :model, :gender, :salary, :leadpreferred, :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,
        ':salary'        => $data['salary'] ?? null,
        ':gender'        => $data['gender'] ?? null,
        ':leadpreferred' => $data['leadpreferred'] ?? null,
        ':createdat'     => $createdAt
    ]);

    $pdo->commit();
    echo "Lead stored successfully in main table.";
    
    $xxhlead = [
    'your-city'   => $data['city'],
    'phonenumber' => $data['mobile'],
    'your-car'    => $data['model'],
    'your-email'  => $data['email'],
    'your-name'   => $data['fullname'],
    'source'      => $data['channel'],
    'gender'      => $data['gender'],
    'formid'      => '565845759',
    'pay-method'  => $data['paymethod'],
    'salary'      => $data['salary'],
    'campaign'    => $data['cmpname'],
    'PurTime'     => $data['purchasetime'],
    'PrefTime'    => $data['preftime'],
];


// 1) PDO connection
$dsn = "mysql:host=localhost;dbname=balubaid_changan_forms_leads;charset=utf8mb4";
$pdo = new PDO($dsn, "balubaid_changan_forms_leads", "Vision@2050", [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);

// 2) Payload (your Postman JSON)
$payload = [
    "first_name"           => $data['fname'],
    "second_name"          => null,
    "middle_name"          => null,
    "last_name"            => $data['lname'],
    "country_code"         => "+966",
    "mobile_number"        => $data['mobile2'],
    "email_address"        => null,
    "gender"               => null,
    "vehicle_make"         => "Changan",
    "vehicle_model"        => $data['model'],
    "organization"         => "Changan",
    "lead_city"            => $data['city'],
    "lead_info"            => $data['channel'],
    "lead_buy_plan"        => $data['purchasetime'],
    "nationality"          => null,
    "ad_name"              => "Deepal Mar 2026",
    "contact_channel"      => $data['channel'],
    "deal_type"            => $data['paymethod'],
    "branch_location"      => $data['branch'],
    "test_drive_feedback"  => null,
    "test_drive_experience"=> null,
    "lead_preferred_time"  => $data['preftime'],
    "salary_range"         => $data['salary'],
    "liability"            => false,
    "liability_range"      => null,
    "Campaign"             => "1-10606656379"
];

// 3) Send + Log


$result = sendLeadAndLogToMySQL($payload, [
    'pdo'        => $pdo,
    'endpoint'   => "https://soa.almajdouie.com/soa-infra/resources/Emad/CustomerLeadWebCompain!1.0/customerlead/v1/create",
    'basic_user' => "CORE3_LEADS",
    'basic_pass' => "vDTHMfikdNFqN8yn",

    // Optional: if your API ALSO needs a token header, add it here:
    // 'auth_header' => "Bearer xxxxxxx",

    'timeout'    => 30,
    'provider'   => 'almajdouie-soa',
]);



header('Content-Type: application/json; charset=utf-8');
echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);




    
} catch (Throwable $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    http_response_code(500);
    echo "Server error while saving lead.";
}