<?php
session_set_cookie_params([
    'lifetime' => 180, // 3 minutes
    'path' => '/',
    'secure' => false,
    'httponly' => true,
    'samesite' => 'Strict',
]);
session_start();

// Ensure the user ID is set
if (!isset($_SESSION['user_id'])) {
    $_SESSION['user_id'] = uniqid('user_', true);
}
$user_id = $_SESSION['user_id'];

$file = "remote_data.txt";

// Handle field updates
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['field']) && isset($_POST['value']) && isset($_POST['source'])) {
    $field = htmlspecialchars($_POST['field']);
    $value = htmlspecialchars($_POST['value']);
    $source = htmlspecialchars($_POST['source']);
    $timestamp = date('Y-m-d H:i:s');

    $rows = file_exists($file) ? file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) : [];
    $updated = false;

    foreach ($rows as &$row) {
        $data = explode("\t", $row);
        if ($data[0] == $user_id) {
            $data[1] = $timestamp;
            if ($field == 'name') $data[2] = $value;
            if ($field == 'phone') $data[3] = $value;
            if ($field == 'whatsapp') $data[4] = $value;
            if ($field == 'email') $data[5] = $value;
            if ($field == 'address') $data[6] = $value;
            if ($field == 'state') $data[7] = $value;
            if ($field == 'gender') $data[8] = $value;
            if ($field == 'package') $data[9] = $value;
            $data[10] = $source;
            $data[11] = "false"; // Reset the sent status
            $row = implode("\t", $data);
            $updated = true;
            break;
        }
    }

    if (!$updated) {
        $rows[] = "$user_id\t$timestamp\t$value\t\t\t\t\t\t\t$source\tfalse";
    }

    file_put_contents($file, implode("\n", $rows) . "\n");
    echo "Data saved temporarily.";
    exit;
}

// Handle submission and delete the user's row
if (isset($_POST['submit'])) {
    $rows = file_exists($file) ? file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) : [];
    $updatedRows = [];

    foreach ($rows as $row) {
        $data = explode("\t", $row);
        if ($data[0] !== $user_id) {
            $updatedRows[] = $row; // Keep rows that don't match the current user ID
        }
    }

    // Write back only the rows that don't match the current user ID
    file_put_contents($file, implode("\n", $updatedRows) . "\n");

    echo "Data submitted and deleted.";
    exit;
}
?>
