<?php

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    exit('Invalid request');
}

/* ===============================
   0. HONEYPOT (BOT PROTECTION)
=============================== */
if (!empty($_POST['USER_MESSAGE'] ?? '')) {
    exit; // Bot detected
}

/* ===============================
   1. SAFE INPUT
=============================== */
$name   = trim($_POST['name'] ?? '');
$email  = trim($_POST['email'] ?? '');
$mobile = trim($_POST['phone'] ?? '');

$projectname = trim($_POST['projectname'] ?? 'Unknown Project');
$subsource   = trim($_POST['form_source'] ?? 'google ads');

/* ===============================
   2. VALIDATION
=============================== */
if ($name === '' || $email === '' || $mobile === '') {
    exit('Invalid form submission');
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    exit('Invalid email address');
}

if (!preg_match('/^[0-9]{10}$/', $mobile)) {
    exit('Invalid phone number');
}

/* ===============================
   3. USER IP
=============================== */
function getUserIP() {
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) return $_SERVER['HTTP_CLIENT_IP'];
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) return explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
    return $_SERVER['REMOTE_ADDR'];
}

$ipaddress = getUserIP();

/* ===============================
   4. SEND DATA TO CRM API
=============================== */
$apiUrl = "https://www.searchhomesindia.in/superadmin/myapicontainer/v2/api/googleads_leads";
$apiKey = "21728c9120b8b8a1607ac9af5dcfef4d";

$crmPayload = [
    "name" => $name,
    "email" => $email,
    "number" => $mobile,
    "location" => $ipaddress,
    "subsource_of_lead" => $subsource
];

$ch = curl_init($apiUrl);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode($crmPayload),
    CURLOPT_HTTPHEADER => [
        "Content-Type: application/json",
        "API-Key: $apiKey"
    ],
]);

$crmResponse = curl_exec($ch);

if ($crmResponse === false) {
    error_log("CRM API Error: " . curl_error($ch));
}

curl_close($ch);

/* ===============================
   5. SEND SMS (FAST2SMS)
=============================== */
$smsMessage = "Property - $projectname | Name - $name | Mobile - $mobile | Email - $email | Regards, SearchHomes India Pvt Ltd";

$fields = [
    "sender_id" => "SHHOME",
    "message" => $smsMessage,
    "template_id" => "1207163731895114985",
    "entity_id" => "1201159178483176795",
    "route" => "dlt_manual",
    "numbers" => "8147267372"
];

$curl = curl_init();
curl_setopt_array($curl, [
    CURLOPT_URL => "https://www.fast2sms.com/dev/bulkV2",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode($fields),
    CURLOPT_HTTPHEADER => [
        "authorization: RKnKg7po5EXg8lVwwYLYnZHFcoBBHEqWKfh4juLfSuuuZCCbPj4nFjzsSnGV",
        "content-type: application/json"
    ],
]);

$smsResponse = curl_exec($curl);

if ($smsResponse === false) {
    error_log("Fast2SMS Error: " . curl_error($curl));
}

curl_close($curl);

/* ===============================
   6. REDIRECT
=============================== */
header("Location: thank-you.php");
exit;
?>