<?php
// ====== Form inputs ======
$name    = trim($_POST['name'] ?? '');
$phone   = trim($_POST['phone'] ?? '');
$country = trim($_POST['country'] ?? '');
$offerNo = trim($_POST['offer_no'] ?? '');

// ====== Zoho OAuth (ضعها في ENV الأفضل) ======
$client_id     = getenv('ZOHO_CLIENT_ID') ?: '1000.DP09SN7VWSOVLIV21LY6IRGXR9XDLD';
$client_secret = getenv('ZOHO_CLIENT_SECRET') ?: 'ac369b67b1a39e52fea07901d6caf74bb252a4b651';
$refresh_token = getenv('ZOHO_REFRESH_TOKEN') ?: '1000.630a827ffc148b09262be91823bc4dcb.842ecbec8b0041ae67dd4afca77ba45b';

// 1) Get fresh access token
$token_url = "https://accounts.zoho.com/oauth/v2/token";
$post = http_build_query([
  'refresh_token' => $refresh_token,
  'client_id' => $client_id,
  'client_secret' => $client_secret,
  'grant_type' => 'refresh_token',
]);

$ch = curl_init($token_url);
curl_setopt_array($ch, [
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_POST => true,
  CURLOPT_POSTFIELDS => $post,
]);
$token_response = curl_exec($ch);
curl_close($ch);

$token_data = json_decode($token_response, true);
$access_token = $token_data['access_token'] ?? null;

if (!$access_token) {
  http_response_code(500);
  exit("Zoho token error");
}

// 2) Send lead to Zoho CRM
$payload = [
  "data" => [[
    "Last_Name"   => $name ?: "Unknown",
    "Phone"       => $phone,
    "Country"     => $country,
    "Lead_Source" => "Landing Page",
    "Description" => $offerNo ? "Offer: ".$offerNo : ""
  ]]
];

$ch = curl_init("https://www.zohoapis.com/crm/v2/Leads");
curl_setopt_array($ch, [
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_POST => true,
  CURLOPT_POSTFIELDS => json_encode($payload),
  CURLOPT_HTTPHEADER => [
    "Authorization: Zoho-oauthtoken $access_token",
    "Content-Type: application/json"
  ],
]);

$response = curl_exec($ch);
curl_close($ch);

// Optional: لو حابب تتأكد من الرد أثناء الاختبار
// file_put_contents(__DIR__.'/zoho_log.txt', date('c')." ".$response.PHP_EOL, FILE_APPEND);

header("Location: thank-you.html");
exit();
?>
