<?php
// Google Apps Script Deployment URL
$googleSheetsURL = 'https://script.google.com/macros/s/AKfycbx5d_P2u5Xu4GDT7Eb_eDWVdxbFm_kn3XFpYHLZDs0VfwdpAD5oXiCgeoT5ht-sy_T60g/exec'; // Replace with your actual URL

// Check if the form was submitted via POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Collect form data
    $postData = [
        'timestamp' => "'" . date('j/n/Y H:i:s'), // Day/Month/Year format wrapped in single quotes
        'name' => $_POST['name'] ?? '',
        'phone' => $_POST['phone'] ?? '',
        'whatsapp' => $_POST['whatsapp'] ?? '',
        'email' => $_POST['email'] ?? '',
        'address' => $_POST['address'] ?? '',
        'state' => $_POST['state'] ?? '',
        'gender' => $_POST['gender'] ?? '',
        'package' => $_POST['package'] ?? '',
        'source' => $_POST['source'] ?? 'Custom Form', // Default source
    ];

    // Send data to Google Sheets via cURL
    $ch = curl_init($googleSheetsURL);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the response
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']); // Set content type
    curl_setopt($ch, CURLOPT_POST, true); // Set method to POST
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData)); // Add POST data as JSON

    $response = curl_exec($ch); // Execute the cURL request
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Get HTTP status code
    curl_close($ch); // Close the cURL session

    // Check response from Google Sheets
    if ($httpCode === 200) {
        // Success: Redirect to Thank You page
        header('Location: https://ekbrahmi.bpfree.xyz/thank-you/');
        exit;
    } else {
        // Failure: Display an error message
        echo "Failed to send data. Please try again later.";
        exit;
    }
} else {
    echo "Invalid request method.";
    exit;
}
?>
