<?php
// File: /thank-you/update-counter.php

// Tell the browser we’re returning JSON
header('Content-Type: application/json');

// Path to the JSON file in the same folder
$file = __DIR__ . '/counter.json';
$now  = time();
$window = 7 * 60; // 7 minutes in seconds

// Decide whether to record this visit
$record = false;
if (isset($_COOKIE['last_count_time'])) {
    $last = intval($_COOKIE['last_count_time']);
    if (($now - $last) >= $window) {
        $record = true;
    }
} else {
    // No cookie means first visit ever (or cookie expired)
    $record = true;
}

if ($record) {
    // Update the cookie so we don’t count again for another 7m
    // Expires in 1 day; path “/thank-you” so it applies here
    setcookie('last_count_time', $now, $now + 86400, '/thank-you');

    // Ensure the JSON file exists
    if (!file_exists($file)) {
        file_put_contents($file, json_encode([]));
    }

    // Read & decode
    $data = json_decode(file_get_contents($file), true);
    if (!is_array($data)) {
        $data = [];
    }

    // Increment today’s count
    $today = date('Y-m-d');
    if (!isset($data[$today])) {
        $data[$today] = 0;
    }
    $data[$today]++;

    // Save back
    file_put_contents($file, json_encode($data));

    // Send back the new total
    echo json_encode([
      'message' => 'Visit logged',
      'today'   => $data[$today]
    ]);
} else {
    // Skipped because within the 7-minute window
    // Read current value so we can return it
    $data = file_exists($file)
          ? json_decode(file_get_contents($file), true)
          : [];
    $today = date('Y-m-d');
    $count = isset($data[$today]) ? $data[$today] : 0;

    echo json_encode([
      'message' => 'Visit skipped (within 7 minutes)',
      'today'   => $count
    ]);
}
