
­­­­­­­­­­­­­­­­­­
<!DOCTYPE html>
<html>
<?php 

//print_r($_POST);

?>

<?php
date_default_timezone_set('Asia/Riyadh'); // Set PHP timezone to Riyadh

// Database connection
$servername = "localhost";  // Change this if necessary
$username = "balubaid_autozoneoffers";         // Your database username
$password = "Vision@2050";             // Your database password
$database = "balubaid_autozoneoffers";  // Your database name


function convert_persian_numbers ($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);
}


$conn = new mysqli($servername, $username, $password, $database);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Sanitize and retrieve form data
$mobile = isset($_POST['mobile']) ? $conn->real_escape_string(convert_persian_numbers($_POST['mobile'])) : '';

if (empty($mobile)) {
    die("Mobile number is required.");
}

// Check if the mobile number has submitted a lead in the last 15 days
$checkQuery = "SELECT id FROM leads3 WHERE mobile = '$mobile' AND created_at >= DATE_SUB(NOW(), INTERVAL 15 DAY)";
$result = $conn->query($checkQuery);

if ($result->num_rows > 0) {
    //$is_duplicate = '1';
   // echo "Duplicate Lead";
    

// If no recent lead exists, insert the new lead
$utm_source = isset($_POST['utm_source']) ? $conn->real_escape_string($_POST['utm_source']) : '';
$utm_campaign = isset($_POST['utm_campaign']) ? $conn->real_escape_string($_POST['utm_campaign']) : '';
$formtype = isset($_POST['formtype']) ? $conn->real_escape_string($_POST['formtype']) : '';
$offer_id = isset($_POST['offer_id']) ? (int)$_POST['offer_id'] : 0;
$fullName = isset($_POST['fullName']) ? $conn->real_escape_string($_POST['fullName']) : '';
$lastname = isset($_POST['lastname']) ? $conn->real_escape_string($_POST['lastname']) : '';
$email = isset($_POST['email']) ? $conn->real_escape_string($_POST['email']) : '';
$salary = isset($_POST['salary']) ? $conn->real_escape_string($_POST['salary']) : '';
$model = isset($_POST['model']) ? $conn->real_escape_string($_POST['model']) : '';
$nationality = isset($_POST['nationality']) ? $conn->real_escape_string($_POST['nationality']) : '';
$bank = isset($_POST['bank']) ? $conn->real_escape_string($_POST['bank']) : '';
$gender = isset($_POST['gender']) ? $conn->real_escape_string($_POST['gender']) : '';
$city = isset($_POST['city']) ? $conn->real_escape_string($_POST['city']) : '';
$branch = isset($_POST['branch']) ? $conn->real_escape_string($_POST['branch']) : '';
$obligation = isset($_POST['obligation']) ? $conn->real_escape_string($_POST['obligation']) : '';
$realestateLoan = isset($_POST['realestateLoan']) ? $conn->real_escape_string($_POST['realestateLoan']) : '';
$obligationAmount = isset($_POST['obligationAmount']) ? (int)convert_persian_numbers($_POST['obligationAmount']) : 0;
$purchaseTime = isset($_POST['purchaseTime']) ? $conn->real_escape_string($_POST['purchaseTime']) : '';
$terms = isset($_POST['terms']) ? $conn->real_escape_string($_POST['terms']) : '';
$otp = isset($_POST['otp']) ? $conn->real_escape_string($_POST['otp']) : '';
$otpVerified = isset($_POST['otpVerified']) ? $conn->real_escape_string($_POST['otpVerified']) : '';
$campaign = isset($_POST['campaign']) ? $conn->real_escape_string($_POST['campaign']) : '';
$sourcee = isset($_POST['sourcee']) ? $conn->real_escape_string($_POST['sourcee']) : '';



function getbranchValue2($lookup_value) {
    // Database connection parameters
    $servername = "localhost";
    $username = "balubaid_autozoneoffers";
    $password = "Vision@2050";
    $dbname = "balubaid_autozoneoffers";
    

    // 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 branch_lookup_peugeot WHERE lookup_value = ?");
    $stmt->bind_param("s", $lookup_value);  // "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
    }
}

// My Naghi New API


$url = "https://new.mynm-livedashboard.com/saveformjson";

$data = [
    "firstName" => $fullName,
    "lastName" => $lastname,
    "email" => $email,
    "mobile" => $mobile,
    "dealerCity" => $city,
    "branch" => getbranchValue2($branch),
    "vehicle" => $model,
    "purchasePlan" => $purchaseTime,
    "monthlySalary" => $salary,
    "customersBank" => $bank,
    "preferredTime" => "",
    "sourcee" => $sourcee,
    "pagesub" => $campaign,
    "page" => "leads",
    "read_accept" => true,
    "letter_accept" => true
];

$headers = [
    "Content-Type: application/json"
];

//print_r($data);

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

//$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

curl_close($ch);

//echo "Response Code: " . $http_code . "\n";
//echo "Response: " . $response . "\n";

//{"success":true,"message":"Added Successfully","data":{"reference_id":853039}}

//print_r(json_decode($response,true));

$result = json_decode($response,true);

$message = $result['message'];
$success = $reullt['success'];
$reference_id = $result['data']['reference_id'];

//echo $message;
//echo $success;
//echo $reference_id;


if($message == 'Already Added Successfully'){

$is_duplicate = '1';    
    
}

else{

$is_duplicate = '1';    
    
}


$surl = "https://peugeotwebstore.me/ar/?utm_source=".$sourcee."&utm_medium=SOC-RPR&utm_campaign=".$campaign;

$url = "https://www.mideast.mopar.com/bridge/psa/";

$data = [
    "Enquiry_Type" => "Book_a_Test_Drive",
    "FirstName" => $fullName,
    "LastName" => $lastname,
    "Mobile" => $mobile,
    "Email" => $email,
    "DealerCode" => "007524A",
    "Shrm_SvCtr" => getbranchValue2($branch),
    "Make" => "PEUGEOT",
    "Line" => $model,
    "User_Comments" => $salary,
    "Channel" => "",
    "Entry_Form" => "AR",
    "Source_Site" => "WebsiteOEM",
    "MasterKey" => ".",
    "FormCode" => ".",
    "Extended_Privacy" => "1",
    "Device_Used" => "Desktop",
    "Request_Origin" => $surl,
    "Model" => "",
    "Purchase_Timeframe" => $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"
];

// Encode data as JSON
$payload = json_encode($data,JSON_UNESCAPED_SLASHES);

//echo $payload;

$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);

//$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
} else {
    // Decode JSON response
    $responseData = json_decode($response, true);

    // Store into variables
    $message = $responseData['message'] ?? '';
    $isError = $responseData['isError'] ?? '';
    $errorCode = $responseData['errorCode'] ?? '';

    // Example output
   // echo "Message: " . $message . "<br>";
//    echo "Is Error: " . ($isError ? 'true' : 'false') . "<br>";
//    echo "Error Code: " . ($errorCode ?? 'None') . "<br>";


}

if($isError == '1'){

$is_duplicate = '1';    
    
}

else{

$is_duplicate = '1';    
    
}

curl_close($ch);





$created_at = date('Y-m-d H:i:s'); // Current timestamp in Riyadh timezone

$sql = "INSERT INTO duplicate_leads3 (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)
VALUES ('$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','$isError','$errorCode')";

if ($conn->query($sql) === TRUE) {
    //echo "Data successfully inserted!";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}    
    
    
    
}else{

// If no recent lead exists, insert the new lead
$utm_source = isset($_POST['utm_source']) ? $conn->real_escape_string($_POST['utm_source']) : '';
$utm_campaign = isset($_POST['utm_campaign']) ? $conn->real_escape_string($_POST['utm_campaign']) : '';
$formtype = isset($_POST['formtype']) ? $conn->real_escape_string($_POST['formtype']) : '';
$offer_id = isset($_POST['offer_id']) ? (int)$_POST['offer_id'] : 0;
$fullName = isset($_POST['fullName']) ? $conn->real_escape_string($_POST['fullName']) : '';
$lastname = isset($_POST['lastname']) ? $conn->real_escape_string($_POST['lastname']) : '';
$email = isset($_POST['email']) ? $conn->real_escape_string($_POST['email']) : '';
$salary = isset($_POST['salary']) ? $conn->real_escape_string($_POST['salary']) : '';
$model = isset($_POST['model']) ? $conn->real_escape_string($_POST['model']) : '';
$nationality = isset($_POST['nationality']) ? $conn->real_escape_string($_POST['nationality']) : '';
$bank = isset($_POST['bank']) ? $conn->real_escape_string($_POST['bank']) : '';
$gender = isset($_POST['gender']) ? $conn->real_escape_string($_POST['gender']) : '';
$city = isset($_POST['city']) ? $conn->real_escape_string($_POST['city']) : '';
$branch = isset($_POST['branch']) ? $conn->real_escape_string($_POST['branch']) : '';
$obligation = isset($_POST['obligation']) ? $conn->real_escape_string($_POST['obligation']) : '';
$realestateLoan = isset($_POST['realestateLoan']) ? $conn->real_escape_string($_POST['realestateLoan']) : '';
$obligationAmount = isset($_POST['obligationAmount']) ? (int)convert_persian_numbers($_POST['obligationAmount']) : 0;
$purchaseTime = isset($_POST['purchaseTime']) ? $conn->real_escape_string($_POST['purchaseTime']) : '';
$terms = isset($_POST['terms']) ? $conn->real_escape_string($_POST['terms']) : '';
$otp = isset($_POST['otp']) ? $conn->real_escape_string($_POST['otp']) : '';
$otpVerified = isset($_POST['otpVerified']) ? $conn->real_escape_string($_POST['otpVerified']) : '';
$campaign = isset($_POST['campaign']) ? $conn->real_escape_string($_POST['campaign']) : '';
$sourcee = isset($_POST['sourcee']) ? $conn->real_escape_string($_POST['sourcee']) : '';


function getbranchValue2($lookup_value) {
    // Database connection parameters
    $servername = "localhost";
    $username = "balubaid_autozoneoffers";
    $password = "Vision@2050";
    $dbname = "balubaid_autozoneoffers";
    

    // 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 branch_lookup_peugeot WHERE lookup_value = ?");
    $stmt->bind_param("s", $lookup_value);  // "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
    }
}

// My Naghi New API


$url = "https://new.mynm-livedashboard.com/saveformjson";

$data = [
    "firstName" => $fullName,
    "lastName" => $lastname,
    "email" => $email,
    "mobile" => $mobile,
    "dealerCity" => $city,
    "branch" => getbranchValue2($branch),
    "vehicle" => $model,
    "purchasePlan" => $purchaseTime,
    "monthlySalary" => $salary,
    "customersBank" => $bank,
    "preferredTime" => "",
    "sourcee" => $sourcee,
    "pagesub" => $campaign,
    "page" => "leads",
    "read_accept" => true,
    "letter_accept" => true
];

$headers = [
    "Content-Type: application/json"
];

//print_r($data);

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

//$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

curl_close($ch);

//echo "Response Code: " . $http_code . "\n";
//echo "Response: " . $response . "\n";

//{"success":true,"message":"Added Successfully","data":{"reference_id":853039}}

//print_r(json_decode($response,true));

$result = json_decode($response,true);

$message = $result['message'];
$success = $reullt['success'];
$reference_id = $result['data']['reference_id'];

//echo $message;
//echo $success;
//echo $reference_id;



if($message == 'Already Added Successfully'){

$is_duplicate = '1';    
    
}

$surl = "https://peugeotwebstore.me/ar/?utm_source=".$sourcee."&utm_medium=SOC-RPR&utm_campaign=".$campaign;

$url = "https://www.mideast.mopar.com/bridge/psa/";

$data = [
    "Enquiry_Type" => "Book_a_Test_Drive",
    "FirstName" => $fullName,
    "LastName" => $lastname,
    "Mobile" => $mobile,
    "Email" => $email,
    "DealerCode" => "007524A",
    "Shrm_SvCtr" => getbranchValue2($branch),
    "Make" => "PEUGEOT",
    "Line" => $model,
    "User_Comments" => $salary,
    "Channel" => "",
    "Entry_Form" => "AR",
    "Source_Site" => "WebsiteOEM",
    "MasterKey" => ".",
    "FormCode" => ".",
    "Extended_Privacy" => "1",
    "Device_Used" => "Desktop",
    "Request_Origin" => $surl,
    "Model" => "",
    "Purchase_Timeframe" => $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"
];

// Encode data as JSON
$payload = json_encode($data,JSON_UNESCAPED_SLASHES);

//echo $payload;

$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);

$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
} else {
    // Decode JSON response
    $responseData = json_decode($response, true);

    // Store into variables
    $message = $responseData['message'] ?? '';
    $isError = $responseData['isError'] ?? '';
    $errorCode = $responseData['errorCode'] ?? '';

    // Example output
   // echo "Message: " . $message . "<br>";
//    echo "Is Error: " . ($isError ? 'true' : 'false') . "<br>";
//    echo "Error Code: " . ($errorCode ?? 'None') . "<br>";
}

if($isError == '1'){

$is_duplicate = '1';    
    
}

curl_close($ch);



$created_at = date('Y-m-d H:i:s'); // Current timestamp in Riyadh timezone

$sql = "INSERT INTO leads3 (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)
VALUES ('$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','$isError','$errorCode')";

if ($conn->query($sql) === TRUE) {
    //echo "Data successfully inserted!";
} else {
   // echo "Error: " . $sql . "<br>" . $conn->error;
}





function getbranchValue($lookup_value) {
    // Database connection parameters
    $servername = "localhost";
    $username = "balubaid_autozoneoffers";
    $password = "Vision@2050";
    $dbname = "balubaid_autozoneoffers";
    

    // 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 branch_lookup_peugeot WHERE lookup_value = ?");
    $stmt->bind_param("s", $lookup_value);  // "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 getcityValue($lookup_value) {
    // Database connection parameters
    $servername = "localhost";
    $username = "balubaid_autozoneoffers";
    $password = "Vision@2050";
    $dbname = "balubaid_autozoneoffers";
    

    // 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 city_lookup_hyundai WHERE lookup_value = ?");
    $stmt->bind_param("s", $lookup_value);  // "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 getcarValue($lookup_value) {
    // Database connection parameters
    $servername = "localhost";
    $username = "balubaid_autozoneoffers";
    $password = "Vision@2050";
    $dbname = "balubaid_autozoneoffers";
    

    // 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 car_lookup_hyundai WHERE lookup_value = ?");
    $stmt->bind_param("s", $lookup_value);  // "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 getbankValue($lookup_value) {
    // Database connection parameters
    $servername = "localhost";
    $username = "balubaid_autozoneoffers";
    $password = "Vision@2050";
    $dbname = "balubaid_autozoneoffers";
    

    // 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 bank_lookup_hyundai WHERE lookup_value = ?");
    $stmt->bind_param("s", $lookup_value);  // "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 getsalaryValue($lookup_value) {
    // Database connection parameters
    $servername = "localhost";
    $username = "balubaid_autozoneoffers";
    $password = "Vision@2050";
    $dbname = "balubaid_autozoneoffers";
    

    // 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 salary_lookup_hyundai WHERE lookup_value = ?");
    $stmt->bind_param("s", $lookup_value);  // "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 getpurchaseValue($lookup_value) {
    // Database connection parameters
    $servername = "localhost";
    $username = "balubaid_autozoneoffers";
    $password = "Vision@2050";
    $dbname = "balubaid_autozoneoffers";
    

    // 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 purchase_lookup_hyundai WHERE lookup_value = ?");
    $stmt->bind_param("s", $lookup_value);  // "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
    }
}


if($salary > 10000){
    
$vsalary = 'أكثر من ١٠٠٠٠ - Above 10000';    
    
}elseif($salary > 5000){

$vsalary = 'من ٥٠٠٠ إلى ١٠٠٠٠ - From 5000 to 10000';    
    
}elseif($salary > 4000){

$vsalary = 'أكثر من ١٠٠٠٠ - Above 10000';
    
}

if($gender == 'Male'){

$vgender = 'Male - ذكر';    
    
}

if($gender == 'Female'){

$vgender = 'Female - أنثى';    
    
}

$vbank = getbankValue($bank);
$vbranch = getbranchValue($branch);
$vcity = getcityValue($city);


$data = array('your-name' => $fullName,'phonenumber' => $mobile,'your-email' => $email,'your-car' => $model,'source' => $utm_source,'campaign' => $utm_campaign, 'your-city' => $vcity,'gender' => $vgender,'salary' => $vsalary,'your-branch' => $vbranch,'your-bank' => $vbank,'formid' => $offer_id,'form-type' => $formtype);	   
      $ch = curl_init();

curl_setopt($ch, CURLOPT_URL,"https://lp.autozone.com.sa/service_request/get_service.php?confirm=@CRM1");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);

// In real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS, 
//          http_build_query(array('postvar1' => 'value1')));

// Receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

//$server_output = curl_exec($ch);

curl_close ($ch);

//print_r($server_output);
//print_r(json_decode(trim($server_output),true));

$oppdetail = json_decode(trim($server_output),true);


//echo $oppdetail['Agent Name'];
//echo "<br>";
//echo $oppdetail['Branch Name'];
//echo "<br>";
//echo $oppdetail['address'];
//echo "<br>";
//echo $oppdetail['agentnumber'];
//echo "<br>";
//echo $oppdetail['branchurl'];



// Target Hyundai API URL
$url = "https://www.hyundai.com/wsvc/template_ar/spa/common/mail/commonSendMail.html";

// Form data extracted from the network request
$data = [
    'loc' => 'MYNAGHI',
    'lang' => 'ar',
    'mail_title' => 'msg_mail_Special_offers_title',
    'image_title' => 'mailing_title_special_offer',
    'first_name' => $fullName,
    'last_name' => $lastname,
    'phone' => $mobile,
    'email' => $email,
    'recv_email' => 'digitalsales@hyundai.mynaghi.com',
    'recv_name' => '',
    'both_send' => '',
    'page_title' => 'Special Offers',
    'dealer_city' => getcityValue($city),
    'customers_bank' => getbankValue($bank),
    'dealer_branch' => $branch,
    'preferred_time_to_call' => '',
    'vehicles' => getcarValue($model),
    'purchase_plan' => getpurchaseValue($purchaseTime),
    'monthly_salary' => getsalaryValue($salary),
    'dealer_city_en' => $city,
    'dealer_branch_en' => getbranchValue($branch),
    'send_vehicle_en' => $model,
    'customers_bank_en' => $bank,
    'purchase_plan_en' => $purchaseTime,
    'monthly_salary_en' => $salary,
    'preferred_time_to_call_en' => '',
    'sourcee' => $sourcee,
    'page_sub' => $campaign,
    'page' => 'leads',
    'i18n_lang' => 'ar_je',
    'lan' => 'ar'
];


//print_r($data);

// Convert array to URL-encoded string
$postFields = http_build_query($data);

// Initialize cURL session
$ch = curl_init();

// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

// Add request headers (matching your browser request)
$headers = [
    "Content-Type: application/x-www-form-urlencoded",
    "Accept: application/json, text/javascript, */*; q=0.01",
    "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
    "Referer: https://www.hyundai.com/mynaghi/ar/build-a-car/special-offers/ramadan25-SCS.html"
];

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

// Execute cURL request
//$response = curl_exec($ch);

// Check for errors
if (curl_errno($ch)) {
//    echo 'cURL Error: ' . curl_error($ch);
} else {
    //echo "Response: " . $response;
}

// Close cURL session
curl_close($ch);

}

$conn->close();







?>

<?php
// Confirmation page for Autozone loan application submission
// Sample data for agent details (to be replaced with dynamic data from database)

if($formtype=='cash' || $formtype=='highscore'){

$autoassigned = 1;    
    
}

$agent_name = $oppdetail['Agent Name'];
$agent_mobile = $oppdetail['agentnumber'];
$agent_mobile2 = "966".substr($oppdetail['agentnumber'],1);

$text = rawurlencode("مرحبًا " . $oppdetail['Agent Name'] . "، أنا " . $fullName . " وأرغب في إتمام شراء " . $model . ". ما الخطوات التالية؟ شكرًا!");

$whatsapp_link = "https://wa.me/".$agent_mobile2."?text=".$text;
$showroom_location = $oppdetail['branchurl'];
?>
<!DOCTYPE html>
<html lang="ar">
<head>

<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'/kD786/?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-TGR7S4JG');</script>
<!-- End Google Tag Manager -->
    
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>سيارتك المثالية بانتظارك! - <?php if($is_duplicate == '1'){echo "Duplicate Submission";}else{echo "Thank-You Submission";} ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            text-align: center;
            margin: 0;
            padding: 0;
            direction: rtl;
        }
        .container {
            background: #fff;
            max-width: 500px;
            margin: 50px auto;
            padding: 30px;
            border-radius: 15px;
            box-shadow: 0px 4px 15px rgba(0, 0, 0, 0.1);
        }
        .logo img {
            max-width: 160px;
            margin-bottom: 20px;
        }
        .checkmark {
            font-size: 70px;
            color: #000000;
        }
        h2 {
            color: #222;
            font-size: 26px;
            margin-bottom: 15px;
        }
        p {
            color: #555;
            font-size: 18px;
            margin-bottom: 15px;
        }
        .contact, .agent-info {
            margin-top: 20px;
            padding: 15px;
            background: #f9f9f9;
            border-radius: 10px;
            box-shadow: 0px 2px 10px rgba(0, 0, 0, 0.05);
        }
        .contact a, .save-contact, .save-vcf {
            color: #002c5f;
            text-decoration: none;
            font-weight: bold;
        }
        .social-icons {
            margin-top: 20px;
        }
        .social-icons a {
            margin: 0 10px;
            font-size: 24px;
            color: #000000;
            text-decoration: none;
        }
        .button {
            display: inline-flex;
            align-items: center;
            padding: 12px 20px;
            background: #FEC327;
            color: #222;
            border-radius: 8px;
            text-decoration: none;
            font-size: 18px;
            font-weight: bold;
            margin-top: 10px;
            transition: background 0.3s ease;
            transform: skew(-6deg, 0deg);
        }
        .button i {
            margin-left: 10px;
        }
        .button:hover {
            background: #E0A800;
        }
    </style>
</head>
<body>

<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-TGR7S4JG"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
    
    <div class="container">
        <div class="logo">
            <img src="/../assets/peugeot-logo.png" alt="Peugeot Logo">
        </div>
        <p>أنت على بعد خطوة واحدة من قيادة سيارتك المثالية!</p>
        <div class="checkmark"><i class="fas fa-check-circle"></i></div>
        <h2>تهانينا!</h2>
        <p>تم إرسال طلبك بنجاح.</p>
<?php if($autoassigned == 1 && $is_duplicate == '' && $agent_name != ''){ ?>        
    <!--    <div class="agent-info">
            <h3>مستشارك المبيعات المخصص لك</h3>
            <p><strong>الاسم:</strong> <?php echo $agent_name; ?></p>
            <p><strong>الجوال:</strong> <?php echo $agent_mobile; ?></p>
            
            <a href="<?php echo $whatsapp_link; ?>" class="button">
                <i class="fab fa-whatsapp"></i> تواصل مع مستشارك
            </a>
            
            <br>
            
            <a href="<?php echo $showroom_location; ?>" class="button">
                <i class="fa-solid fa-store"></i> موقع المعرض
            </a>
            
            <br><br><br>
            <a href="https://specialoffers.autozone.com.sa/generate-vcf/?name=<?php echo urlencode($agent_name); ?>&phone=<?php echo urlencode($agent_mobile); ?>&location=<?php echo urlencode($showroom_location); ?>&text=<?php echo $whatsapp_link; ?>" class="button">
                <i class="fas fa-save"></i> حفظ جهة الاتصال
            </a>
        </div>  -->
<?php  } ?>        
        <p>ابقَ على تواصل معنا!</p>
        <div class="social-icons">
            <a href="https://x.com/peugeotinksa/"><i class="fab fa-twitter"></i></a>
            <a href="https://www.facebook.com/Peugeot.Saudi/"><i class="fab fa-facebook"></i></a>
            <a href="https://www.instagram.com/peugeotksa/"><i class="fab fa-instagram"></i></a>
          <!--  <a href="https://www.youtube.com/user/hyundaisaudi/featured"><i class="fab fa-youtube"></i></a> -->
        </div>
        <div class="contact">
            <p>إذا كان لديك أي استفسارات، لا تتردد في التواصل معنا!</p>
           <!-- <p><a href="mailto:customer.care@hyundai.mynaghi.com">customer.care@hyundai.mynaghi.com</a></p> -->
            <p>اتصل بنا على <strong>920023550</strong></p>
        </div>
    </div>

<script>

var gtm_mobile = "<?php echo $mobile; ?>";

</script>

<script>

var gtm_email = "<?php echo $email; ?>";

</script>

<script>

var gtm_source = "<?php echo $utm_source; ?>";

</script>
    
</body>
</html>