<?php
$file = 'remote_data.txt';
$googleSheetsURL = 'https://script.google.com/macros/s/AKfycby-IR-oKKjLPSFCcMnJdqx0QlCsl9w6PqM1fSWjwF-F8YaMCi4AG7FhHwKSo7hTcbAr/exec'; // Replace with your Google Apps Script deployment URL

if (!file_exists($file)) {
    echo "No data found.";
    exit;
}

$rows = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if (empty($rows)) {
    echo "No data available.";
    exit;
}

$updatedRows = [];
$now = time();
$sentCount = 0;

foreach ($rows as $row) {
    $data = explode("\t", $row);
    $timestamp = strtotime($data[1]);
    $sentToGoogle = $data[11];

    // Check if the row hasn't been updated in the last 3 minutes and hasn't been sent yet
    if (($now - $timestamp) >= 180 && $sentToGoogle === "false") {
        $postData = [
            'timestamp' => $data[1],
            'name' => $data[2],
            'phone' => $data[3],
            'whatsapp' => $data[4],
            'email' => $data[5],
            'address' => $data[6],
            'state' => $data[7],
            'gender' => $data[8],
            'package' => $data[9],
            'source' => $data[10],
        ];

        // Send data to Google Sheets using cURL
        $ch = curl_init($googleSheetsURL);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));

        $response = curl_exec($ch);

        if (!curl_errno($ch)) {
            // Mark the row as sent if the request was successful
            $data[11] = "true";
            $sentCount++;
        }

        curl_close($ch);
    }

    $updatedRows[] = implode("\t", $data);
}

// Write back updated rows to the file
file_put_contents($file, implode("\n", $updatedRows) . "\n");

echo "Sent $sentCount rows to Google Sheets.";
?>
