<?php

// ---------------------------
// 1) VERIFY WEBHOOK
// ---------------------------
if (isset($_GET['hub_mode']) && $_GET['hub_mode'] === 'subscribe') {

    $verify_token = "123456";

    if ($_GET['hub_verify_token'] === $verify_token) {
        echo $_GET['hub_challenge'];
        exit;
    } else {
        echo "Invalid verify token";
        exit;
    }
}


// ---------------------------
// 2) ENCRYPT FUNCTION
// ---------------------------
function encryptString($string, $secret = "MySecretKey123") {
    return base64_encode(openssl_encrypt($string, "AES-128-ECB", $secret));
}


// ---------------------------
// 3) RECEIVE RAW WEBHOOK
// ---------------------------
$input = file_get_contents("php://input");

$encrypted_raw = encryptString($input);

file_put_contents(
    "lead_log.txt",
    date('Y-m-d H:i:s') . " --- RAW_ENCRYPTED: " . $encrypted_raw . PHP_EOL,
    FILE_APPEND
);

$data = json_decode($input, true);

// ---------------------------
// 4) CHECK LEAD ID + AD IDS
// ---------------------------
if (!isset($data["entry"][0]["changes"][0]["value"]["leadgen_id"])) {
    echo "NO LEAD FOUND";
    exit;
}

$value = $data["entry"][0]["changes"][0]["value"];

$lead_id     = $value["leadgen_id"] ?? '';
$form_id     = $value["form_id"] ?? '';
$page_id     = $data["entry"][0]["id"] ?? '';

$ad_id       = $value["ad_id"] ?? '';
$adset_id    = $value["adset_id"] ?? '';
$campaign_id = $value["campaign_id"] ?? '';

file_put_contents(
    "fb_ids_log.txt",
    date('Y-m-d H:i:s') .
    " PAGE_ID: $page_id | AD_ID: $ad_id | ADSET_ID: $adset_id | CAMPAIGN_ID: $campaign_id" . PHP_EOL,
    FILE_APPEND
);


// ---------------------------
// MULTIPLE PAGE TOKEN SYSTEM
// ---------------------------

$page_tokens = [

    // PAGE_ID => ACCESS_TOKEN

    "1015271311660553" => "EAAX1yOqyzxoBRjWZCk9Nb6bblO7K4j8UMDvQoyY6kWlOzxNIRdpZAjZAcwGgxDBaz67H29pyYmO5mVodfYwED8D89SHQBXgsVaJ19qvWI0f886StzINrEVFeIZC8ZCiYji6TA2qd38o9IQ8H298rrVc9YCKFgxbLVK2MpnXPNnU4xPYyJevDswrKoSoiZB91KxDcpNjp8W",
    "114394455048565" => "EAAX1yOqyzxoBRuTI2Bo49Pr4llXrJLqwEzjvA0AsdzZCj9BNzyhxZBrfmwEGUbhXfAkNqK1kF4XXJUSZBdLmJtAm4mRLtDGKGfKAXkwN8raT1FBRzziAhpggne0iqmvfFFnm7MmNyPyqmKJ6L2GLedUScAvjBqYA27AK3NuvUdDJLQvucTxkiZAeykW4cUPVcD4ZD",
    "1116790168394635" => "EAAX1yOqyzxoBRraId1pNlfDo7LMIB5zXY4AZBZADX2HIdt90sBJkYEGm280mGqO0YsB5zT9e8w4Aj7ZBDB2ZBleImtqQkhZBo9k5YesBMl4tDGfoblqKyZARdDVSnZCKi2LZAWpvPxOpeM7Iz4OmgdrZAttexbiHwX6ZCu5TpSJLOGZCiLaC35sXp2FZAo32MMSFzxhIUfnymtjF",
    "1087579004434407" => "EAAX1yOqyzxoBRuJacBApNpYs5n7lhkxvL8nnvUAu5ScZBAQwrkZBT3el7flIanlrvLJGYkwGARmJlxkGJxuMgP45VeZCzEoYwo0TjGh82rDngNNDY4FFs01BIa0mnHz49e9ZAFAZAChNrc5VfXK2D1lIJljCDOHcOXNxws2yX7ZAeIkgHYROyix7hTykATVduOuOLX",
    "135356093002933" => "EAAX1yOqyzxoBR5MPlWJiA5BIKTbeNgJ87N6HUjmZBo7n5G5jjJQHdJe86MpcIMH301xUZAhngaCyOgusU0KyFQyhpgtbsbaXXHCeEyvY0ZAyPUr8ZAiXmomwpZBBVJlp0PdghmaGstDcVIjWvOhmuEwT9vAa5ifKepoqBHSsxZASgr9NFNySyU7Gg2xuTTisI5G5ZAswmkZD",
    "1206258565898117" => "EAAX1yOqyzxoBRyO6Cj4P5dmtfsuUmtt5zQbd0ZBEH1oXqvuZA39PPhs07oqs7vX7QdLFnNQGJZBjCASHU6i5WjDYHr5WYpZCID3tpvsj7RF4ZBuFlFyWTPG5vZBguaSAvIzSfOTMHlPUqbf7WHBySZAS0kA7cGlOIfAsOjR5gftjrP5j5D5nvGUNaJZA5pTVBzKHPZCTOX2uZC",
    "457452687451115" => "EAAX1yOqyzxoBR3sQ99WTWVGwZAfOr8ntV4XSB9HXUm6stVoHFpH3rgpmblyUxOlp7nLlpsZCZCVPMs6DNoFAIKP7jLRgP6xQKP2gaCakkkzrVOLpo8fh5NTN6lZB6ID1CAmsZCZAYorbYraGCl2oLcysDrkWqZBNPcqi3LBWTmW0Pk8B8ZBIBtG2LxxhbZCxuHICZBFNzl9Gfj",
    "1053118067319654" => "EAAX1yOqyzxoBR8vjHNIY9S34Wu6NcFKATdUvLHp4U3FZCTQzqUhZCVFzwzKi3JkxEM2AibA2aAaQCMWs2vSMGoFoWiEZANrm0mbSKxsM16spcVXPJVBH9MjWGYSWg2xZCCd1ZAVZBAUBNoI94ZCwCQ2WZBRKd7X3DkBm3MtBBN3d9MoUMe0jUm0LUjyRn9OJrUO8boHCo1iW",
    "1677660806827257" => "EAAX1yOqyzxoBR466C0LkEixZAS9fmRSHXztXnqeuHAP4wrU90KP3faiKUgWWIYw1kPk8ZC8efF2kKho2JJF5Fwvjk1OtJAkYgg2fl1ORwp46tHs8uytrde9fXajl98LgJNFZB3wqwoACdwbupLXZAuldo5p0jJvavaM3Bwl1d45w6tz6wu27Sa2rZBqj7yLliqUrD",
    "1221515234375241" => "EAAX1yOqyzxoBRyNVURkC3avvVg7OFgFqCAUisGsZAN1ZAAaRqlgtxYw3yrZC10dRBwUrOy7Jrf3joo2bHrdMsqO2JKaQTsFZAtEWmagZArzhkI8qqjkhxE3ZC0XcNgpEDhjpZA5lEnOvCKlAb6LUweRjgCv0jDycj91bGY5jztZCB6q2HxZBZBwz9vbwgFpDtEr3g6ZC7jNB1WP",
    "1264387056748764" => "EAAX1yOqyzxoBR234LC3eFMiu4yof4xrnXTb5VFNPBrTOy7tZAvjjCTbvT0CKEzAHinBeX4kZAgF4F4mdRt0isKDJUZB5FZCoSNH3WsNJ7z1NBscM0BJ7u9I2oxGrsAn4yklQQKqyUQP6bVrcIUKBVJTJczl0TAygjO5ebG03v9AZB4XFCcXKhcpC9pDfdPGXZAuohvFIWv"

      

];

// Check if token exists for this page
if (!isset($page_tokens[$page_id])) {

    file_put_contents(
        "token_error.txt",
        date('Y-m-d H:i:s') . " --- TOKEN NOT FOUND FOR PAGE: $page_id" . PHP_EOL,
        FILE_APPEND
    );

    exit;
}

// Assign correct token dynamically
$access_token = $page_tokens[$page_id];



// ---------------------------
// 5) FETCH FORM NAME
// ---------------------------


// ---------------------------
// 5) FETCH FORM NAME (DYNAMIC MAPPING + FALLBACK)
// ---------------------------
$project_name = "Facebook Lead"; // Default Name

// Database details (Strings ko quotes mein dalna zaruri hai)
$db_host = "localhost";
$db_user = "theniralatrio_root";
$db_pass = 'Kamal@321'; // Single quotes use karein agar password mein @ ho
$db_name = "theniralatrio_lead";

// Database Connection (Safe Mode)
$conn_map = @new mysqli($db_host, $db_user, $db_pass, $db_name);

if ($conn_map && !$conn_map->connect_error) {
    // SQL query to find mapping
    $sql_map = "SELECT project_name FROM fb_form_mapping WHERE form_id = '$form_id' LIMIT 1";
    $map_res = @$conn_map->query($sql_map);

    if ($map_res && $map_res->num_rows > 0) {
        $row_map = $map_res->fetch_assoc();
        $project_name = $row_map['project_name'];
        $mapping_success = true; // Flag: Mapping mil gayi
    }
    $conn_map->close(); // Connection close karna achhi practice hai
}

// Fallback: Agar upar mapping nahi mili, toh FB API se naam fetch karo
if (!isset($mapping_success)) {
    $form_api_url = "https://graph.facebook.com/v19.0/$form_id?fields=name,id&access_token=$access_token";
    $form_response = @file_get_contents($form_api_url);

    if ($form_response !== false) {
        $form_data = json_decode($form_response, true);
        $project_name = $form_data['name'] ?? $project_name;
    }
}


// ---------------------------
// 6) FETCH FULL LEAD DETAILS
// ---------------------------
$lead_api_url = "https://graph.facebook.com/v19.0/$lead_id?fields=created_time,field_data&access_token=$access_token";
$lead_response = file_get_contents($lead_api_url);

$lead_details = json_decode($lead_response, true);


// ---------------------------
// 7) PARSE LEAD FIELDS
// ---------------------------
$name = "";
$email = "";
$phone = "";
$city = "";
$message = "";

$utm_source = "";
$utm_medium = "";
$utm_campaign = "";
$utm_term = "";

$form_fields = [];

if (!empty($lead_details['field_data'])) {

    foreach ($lead_details['field_data'] as $field) {

        $field_name = strtolower(trim($field['name']));
        $normalized = str_replace([' ','_','-'], '', $field_name);

        $value = $field['values'][0] ?? '';

        $form_fields[$field_name] = $value;

        if (in_array($normalized, ['fullname','name'])) $name = $value;
        if ($normalized == 'email') $email = $value;
        if (in_array($normalized, ['phonenumber','phone','mobile'])) $phone = $value;
        if ($normalized == 'city') $city = $value;

        if ($normalized == 'utmsource') $utm_source = $value;
        if ($normalized == 'utmmedium') $utm_medium = $value;
        if ($normalized == 'utmcampaign') $utm_campaign = $value;
        if ($normalized == 'utmterm') $utm_term = $value;
    }
}

/* ===== EXTRA FORM FIELDS MESSAGE BLOCK ADD HERE ===== */

$extra_fields_text = "";

$skip_fields = [
    'full name',
    'full_name',
    'name',
    'phone_number',
    'phone',
    'mobile',
    'email'
];

foreach ($form_fields as $key => $val) {

    $normalized = strtolower(trim($key));

    if (in_array($normalized, $skip_fields)) {
        continue;
    }

    $extra_fields_text .= "$key : $val | ";
}




// ---------------------------
// 8) DEFAULT SOURCE (Page-Specific)
// ---------------------------

$page_specific_source = [
    "1015271311660553" => "BTS DMXD",  // Specific page
    // baki pages default me Digital Marketing XD
];

if (!isset($utm_source) || empty($utm_source)) {
    if (isset($page_specific_source[$page_id])) {
        $utm_source = $page_specific_source[$page_id];
    } else {
        $utm_source = "Digital Marketing XD";
    }
}


// ================================
// 9) MARKETING API TRACKING
// ================================

$campaign_name = "";
$adset_name = "";
$ad_name = "";
$spend = "";

if (!empty($ad_id)) {

    $ad_api = "https://graph.facebook.com/v19.0/$ad_id?fields=name,adset_id,campaign_id&access_token=$access_token";
    $ad_response = @file_get_contents($ad_api);
    $ad_data = json_decode($ad_response, true);

    $ad_name = $ad_data['name'] ?? '';
    $adset_id = $ad_data['adset_id'] ?? $adset_id;
    $campaign_id = $ad_data['campaign_id'] ?? $campaign_id;

    if (!empty($adset_id)) {
        $adset_api = "https://graph.facebook.com/v19.0/$adset_id?fields=name&access_token=$access_token";
        $adset_data = json_decode(@file_get_contents($adset_api), true);
        $adset_name = $adset_data['name'] ?? '';
    }

    if (!empty($campaign_id)) {
        $campaign_api = "https://graph.facebook.com/v19.0/$campaign_id?fields=name&access_token=$access_token";
        $campaign_data = json_decode(@file_get_contents($campaign_api), true);
        $campaign_name = $campaign_data['name'] ?? '';
    }

   $lead_date = date('Y-m-d', strtotime($lead_details['created_time']));

$insight_api = "https://graph.facebook.com/v19.0/$ad_id/insights?fields=spend&time_range={'since':'$lead_date','until':'$lead_date'}&access_token=$access_token";

$insight_data = json_decode(@file_get_contents($insight_api), true);

if (!empty($insight_data['data'][0]['spend'])) {
    $spend = $insight_data['data'][0]['spend'];
}

}


// Fallback Tracking
if (empty($utm_medium)) $utm_medium = $adset_id;
if (empty($utm_campaign)) $utm_campaign = $campaign_id;
if (empty($utm_term)) $utm_term = $ad_id;

/* ===== FINAL CRM VALIDATION ===== */


/* ===== CRM FINAL SANITIZE ===== */

$name_original = $name;

$name = preg_replace('/[^A-Za-z0-9 ]/', '', $name);
$city = $city ?: "NA";

$phone = preg_replace('/[^0-9]/', '', $phone);

if(strlen($phone) > 10){
    $phone = substr($phone, -10);
}

if(empty($email)){
    $email = $phone . "@fblead.com";
}



// ---------------------------
// FIX PROJECT NAME BY FORM ID
// ---------------------------

if ($form_id == "1579337340289737") {

    $project_name = "Mahindra Rainforest Mumbai";

} 



// ---------------------------
// 13) X-DIMENSION CRM
// ONLY SELECTED FORM IDS
// ---------------------------

if (
    trim($form_id) === "1995428617735454" ||
    trim($form_id) === "3408647729308603" ||
    trim($form_id) === "1026333589785499" ||
    trim($form_id) === "1360010719377383" ||
    trim($form_id) === "1505051358095157" ||
    trim($form_id) === "1052502117208204" ||
    trim($form_id) === "1751421219213610" ||
    trim($form_id) === "1795227728111722" ||
    trim($form_id) === "1896024677683843" ||
    trim($form_id) === "4337289223083686" ||
    trim($form_id) === "1625405848558477" ||
    trim($form_id) === "1036305875534449" ||
    trim($form_id) === "27433396582983852" ||
    trim($form_id) === "993153417039854" ||
    trim($form_id) === "1634884707597505" ||
    trim($form_id) === "2892050847815674" ||
    trim($form_id) === "1308067258158012" ||
    trim($form_id) === "2111600566191795" ||
    trim($form_id) === "1703826184072736" ||
    trim($form_id) === "1009460181823375" ||
    trim($form_id) === "1689045608850732" ||
    trim($form_id) === "1639362007124512" ||
    trim($form_id) === "4326860537616927" ||
    trim($form_id) === "1955725328468978" ||
    trim($form_id) === "1057386530306604" ||
    trim($form_id) === "1259009092851912" ||
    trim($form_id) === "1369205331739893" ||
    trim($form_id) === "1898064070863664" ||
    trim($form_id) === "1607476874716171" ||
    trim($form_id) === "1416562013631285" ||
    trim($form_id) === "1496999208780885" ||
    trim($form_id) === "1545727027346228" ||
    trim($form_id) === "1625116192947712" ||
    trim($form_id) === "1266919175369396" ||
    trim($form_id) === "1654248152349205" 
    
    
) {

    $form_project_map = [

        "1995428617735454" => "SmartWorld Elie Saab Noida, Studio Apt",
        "3408647729308603" => "SmartWorld Elie Saab Noida, Studio Apt",
        "1026333589785499" => "SmartWorld Elie Saab Noida, Studio Apt",
        "1360010719377383" => "Gaur Bento Noida",
        "1505051358095157" => "Gaur Chrysalis Noida",
        "1052502117208204" => "GGL Crown Noida",
        "1751421219213610" => "Ace Parkway 2.0, Noida Sec 150",
        "1795227728111722" => "Gaur Bento Noida",
        "1896024677683843" => "Gaur Chrysalis Noida",
        "4337289223083686" => "Sawasdee Galaxy Vasundhara Ghaziabad",
        "1625405848558477" => "Dasnac Yuva Noida",
        "1036305875534449" => "Ekana Sportz City Lucknow",
        "27433396582983852" => "Misgun Lucknow",
        "993153417039854" => "M3m the line Noida",
        "1634884707597505" => "Gaur Studio Noida",
        "2892050847815674" => "Nirala Gateway Gr Noida West",
        "1308067258158012" => "Godrej Aden Greator Noida",
        "2111600566191795" => "Trump Tower Noida",
        "1703826184072736" => "Experion Elements Noida",
        "1009460181823375" => "Trump Tower Noida New",
        "1689045608850732" => "L&T Green Reserve Noida",
        "1639362007124512" => "Experion Satori Noida",
        "4326860537616927" => "M3M The Cullinan Noida",
        "1955725328468978" => "M3M Smart Elie Saab Noida Residence",
        "1057386530306604" => "M3M Jacob & Co. Residences Noida",
        "1259009092851912" => "Gaurs – Jaypee Greens Greater Noida",
        "1369205331739893" => "Clove Country Noida",
        "1898064070863664" => "Ekana Sports City Lucknow",
        "1607476874716171" => "Smart World Studio Noida",
        "1416562013631285" => "GGL Crown Noida",
        "1496999208780885" => "Misgun Shaheed Path Lucknow",
        "1545727027346228" => "L&T Green Reserve Noida",
        "1625116192947712" => "SmartWorld Elie Saab Noida, Studio Apt",
        "1266919175369396" => "SmartWorld Elie Saab Noida, Studio Apt",
        "1654248152349205" => "Kb Mart Gr noida west"
        

    ];

    $service_needed = $form_project_map[trim($form_id)] ?? "Default Project";
    
    file_put_contents(
    "project_debug.txt",
    date('Y-m-d H:i:s') .
    " | FORM_ID=" . $form_id .
    " | PROJECT=" . $service_needed . PHP_EOL,
    FILE_APPEND
);

    $xd_url    = "https://new-keys.xdimension.in/webhook/lead";
    $xd_secret = "xd_super_secret_key_2025";

    // =========================
    // PHONE FIX
    // =========================

    $phoneValue = !empty($phone_raw) ? $phone_raw : $phone;

    $xd_phone_raw = preg_replace('/[^0-9+]/', '', trim($phoneValue));

    if (!empty($xd_phone_raw) && strpos($xd_phone_raw, '+') !== 0) {
        $xd_phone_raw = '+91' . $xd_phone_raw;
    }

    // =========================
    // INDUSTRY / REMARKS DATA
    // =========================

    $xd_industry = trim($extra_fields_text ?: '');

    if (!empty($xd_phone_raw)) {
        $xd_industry .= ' | phone: ' . $xd_phone_raw;
    }

    $xd_industry = substr($xd_industry, 0, 255);

    // =========================
    // PAYLOAD
    // =========================

  $xd_payload = json_encode([
    "full_name"       => $name_original,
    "name"            => $name_original,
    "email"           => $email,
    "phone"           => $xd_phone_raw,
    "mobile"          => $xd_phone_raw,
    "phone_number"    => $xd_phone_raw,
    "city"            => !empty($city) ? $city : "NA",
    "source_platform" => "Meta",
    "service_needed"  => $service_needed,
    "industry"        => $xd_industry,
    "adSpend"         => $spend ?: "",

    "company_website" => "Campaign Name: " . ($campaign_name ?: "NA") .
                         " | Ad Name: " . ($ad_name ?: "NA") .
                         " | Ad Set Name: " . ($adset_name ?: "NA")
]);

    // =========================
    // DEBUG LOG
    // =========================

    file_put_contents(
        "phone_debug.txt",
        date('Y-m-d H:i:s') .
        " | phone_raw=[" . ($phone_raw ?? '') . "]" .
        " | phone=[" . ($phone ?? '') . "]" .
        " | final_phone=[" . $xd_phone_raw . "]" . PHP_EOL,
        FILE_APPEND
    );

    // =========================
    // API CALL
    // =========================

    $ch_xd = curl_init($xd_url);

    curl_setopt_array($ch_xd, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => $xd_payload,
        CURLOPT_HTTPHEADER     => [
            "Content-Type: application/json",
            "X-Webhook-Secret: " . $xd_secret,
            "Accept: application/json"
        ],
        CURLOPT_TIMEOUT        => 15,
        CURLOPT_SSL_VERIFYPEER => true
    ]);

    $xd_response  = curl_exec($ch_xd);
    $xd_httpCode  = curl_getinfo($ch_xd, CURLINFO_HTTP_CODE);
    $xd_curlError = curl_error($ch_xd);

    curl_close($ch_xd);

    // =========================
    // MAIN LOG
    // =========================

    file_put_contents(
        "xd_crm_log.txt",
        date('Y-m-d H:i:s') .
        " --- FORM ID: " . $form_id .
        " --- HTTP: " . $xd_httpCode .
        " --- DATA: " . $xd_payload .
        " --- RESP: " . $xd_response .
        " --- CURL_ERR: " . $xd_curlError . PHP_EOL,
        FILE_APPEND
    );

    // =========================
    // STOP OTHER INTEGRATIONS
    // =========================

    if ($xd_httpCode == 200 || $xd_httpCode == 201) {
        exit; // Lead sirf CRM me jayegi
    }
}

// ---------------------------
// 10) SEND TO CRM
// ---------------------------
$crm1_url = "https://lms.theniralatrio.com/request.php";

$post_data1 = [
    "name" => $name,
    "Email" => $email,
    "Mob" => $phone,
    "city" => $city,
    "Project" => $project_name,
    "ip"            => $_SERVER['REMOTE_ADDR'],
    "message" => $extra_fields_text,
    "gclid"         => $spend,
    "utm_source" => $utm_source,
    "utm_medium" => $campaign_name,
    "utm_campaignID" => $adset_name,
    "utm_term" => $ad_name

];

$ch = curl_init($crm1_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$resp = curl_exec($ch);

if($resp === false){
    file_put_contents("crm_error.txt", curl_error($ch));
}

curl_close($ch);


file_put_contents(
    "crm1_log.txt",
    date('Y-m-d H:i:s') .
    " --- SENT TO CRM1: " . json_encode($post_data1) .
    " | RESP: " . $resp . PHP_EOL,
    FILE_APPEND
);



// ---------------------------
// 11) SECOND CRM (investoxpert.remserp.com)
// ---------------------------

$crm2_url = "https://investoxpert.remserp.com/WebCreate.aspx";

$query = http_build_query([
    "UID"        => "fourqt",
    "PWD"        => "wn9mxO76f34=",
    "name"       => $name,
    "Email"      => $email,
    "Mob"        => $phone,
    "Channel"    => "FB",
    "Src"        => $utm_source,
    "City"       => $city,
    "Location"   => "",
    "Project"    => $project_name,
    "Remark"     => $extra_fields_text,
    "url"        => "",
    "fld1"       => $utm_source,  
    "fld2"       => $campaign_name ?: "NA",
    "fld3"       => $spend ?: "NA",
    "fld4"       => $ad_name ?: "NA",
    "Adset_Name" => $adset_name ?: "NA"
]);

$final_url = $crm2_url . "?" . $query;

$resp2 = @file_get_contents($final_url);

file_put_contents(
    "crm2_log.txt",
    date('Y-m-d H:i:s') . " --- SENT TO CRM2 URL: $final_url | RESP: " . $resp2 . PHP_EOL,
    FILE_APPEND
);

// ---------------------------
// SEND TO MAVIS / LEWIS API
// ---------------------------

// ---------------------------
// 12) THIRD CRM - LEADSQUARED API
// ---------------------------
// ---------------------------
// 12) THIRD CRM - LEADSQUARED API
// ONLY FOR SPECIFIC FORM IDs
// ---------------------------


// ---------------------------
// DEBUG FORM ID
// ---------------------------

file_put_contents(
    "form_debug.txt",
    date('Y-m-d H:i:s') .
    " --- RECEIVED FORM ID: " . $form_id . PHP_EOL,
    FILE_APPEND
);


// ---------------------------
// 12) THIRD CRM - LEADSQUARED API
// ONLY FOR SPECIFIC FORM IDs
// ---------------------------

$allowed_form_ids = [
    "1579337340289737"
];

if (in_array(trim($form_id), $allowed_form_ids)) {

    file_put_contents(
        "lsq_trigger.txt",
        date('Y-m-d H:i:s') .
        " --- API TRIGGERED FOR FORM ID: " . $form_id . PHP_EOL,
        FILE_APPEND
    );

    $lsq_accessKey = "u\$rd5bf7098855691c44d158b298329acb4";
    $lsq_secretKey = "8b3f5817a33c70006d55d6c430a65815429df6ec";

    $lsq_url = "https://api-in21.leadsquared.com/v2/LeadManagement.svc/Lead.Capture?accessKey={$lsq_accessKey}&secretKey={$lsq_secretKey}";

    $lsq_data = [

        [
            "Attribute" => "SearchBy",
            "Value"     => "Phone"
        ],
        [
            "Attribute" => "EmailAddress",
            "Value"     => $email
        ],
        [
            "Attribute" => "FirstName",
            "Value"     => $name
        ],
        [
            "Attribute" => "Phone",
            "Value"     => "+91-" . $phone
        ],
        [
            "Attribute" => "Source",
            "Value"     => "Meta"
        ],
        [
            "Attribute" => "mx_SubSource",
            "Value"     => "Digital Marketing XD"
        ],
        [
    "Attribute" => "mx_Region",
    "Value"     => ""
],
        [
            "Attribute" => "mx_Project_name",
            "Value"     => $project_name
        ]
    ];

    $ch4 = curl_init($lsq_url);

    curl_setopt($ch4, CURLOPT_HTTPHEADER, [
        "Content-Type: application/json"
    ]);

    curl_setopt($ch4, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch4, CURLOPT_POST, true);
    curl_setopt($ch4, CURLOPT_POSTFIELDS, json_encode($lsq_data));

    $lsq_response = curl_exec($ch4);

    $curl_error = curl_error($ch4);

    curl_close($ch4);

    file_put_contents(
        "lsq_log.txt",
        date('Y-m-d H:i:s') .
        " --- FORM ID: " . $form_id .
        " --- DATA: " . json_encode($lsq_data) .
        " --- RESPONSE: " . $lsq_response .
        " --- CURL ERROR: " . $curl_error . PHP_EOL,
        FILE_APPEND
    );

} else {

    file_put_contents(
        "lsq_skip.txt",
        date('Y-m-d H:i:s') .
        " --- FORM ID NOT MATCHED: " . $form_id . PHP_EOL,
        FILE_APPEND
    );
}



echo "OK";

?>
