<?php
// submit_lead.php

// 1. Timezone India
date_default_timezone_set('Asia/Kolkata');

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
    $name = htmlspecialchars(trim($_POST['name']));
    $phone = htmlspecialchars(trim($_POST['phone']));
    $city = htmlspecialchars(trim($_POST['city']));
    
    // Date aur Time alag-alag
    $currentDate = date("d-M-Y"); 
    $currentTime = date("h:i A"); 

    // --- CSV Save ---
    $filename = "leads.csv";
    $file_exists = file_exists($filename);
    $file = fopen($filename, "a");

    if (!$file_exists) {
        fputcsv($file, ["Date", "Time", "Customer Name", "WhatsApp Number", "Location"]);
    }
    fputcsv($file, [$currentDate, $currentTime, $name, $phone, $city]);
    fclose($file);


    $google_script_url = "https://script.google.com/macros/s/AKfycbxnejxuyc7drWTg5M4LXAcaNRFqD5h2jEEeR9vYcHY8U2KALlOnz50loo_DZrQ0pPM/exec"; 

    $data = [
        'date'  => $currentDate,
        'time'  => $currentTime,
        'name'  => $name,
        'phone' => $phone,
        'city'  => $city
    ];

    $ch = curl_init($google_script_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $result = curl_exec($ch);
    curl_close($ch);

    // --- Email Sending ---
    $to = "info@gdwaterconsult.com"; 
    $subject = "New Lead: $name - $city";
    $message = "New Lead:\nDate: $currentDate\nTime: $currentTime\nName: $name\nPhone: $phone\nLocation: $city";
    $headers = "From: no-reply@gdwaterconsult.com";

    @mail($to, $subject, $message, $headers);

    echo "Success";
}
?>