<?php
// Visitor counter — tracks total, by-month (YYYY-MM), and by-day (YYYY-MM-DD)
// NO output before this point - not even whitespace
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Accept');
header('Content-Type: application/json; charset=utf-8');

// Suppress PHP notices/warnings so they never corrupt the JSON response
@ini_set('display_errors', '0');

// Handle preflight
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

$storageFile = __DIR__ . '/visitors_count.json';

// ── helpers ───────────────────────────────────────────────────────────────────

function visitors_parse(string $raw): array {
    $default = ['total' => 0, 'by_month' => [], 'by_day' => []];
    if ($raw === '') return $default;
    $data = json_decode($raw, true);
    if (!is_array($data)) return $default;
    return array_merge($default, $data);
}

// ── main ──────────────────────────────────────────────────────────────────────

$fp = fopen($storageFile, 'c+');
if (!$fp) {
    echo json_encode(['success' => false, 'message' => 'Unable to open storage file']);
    exit;
}

flock($fp, LOCK_EX);

// Read through the open handle (avoids Windows permission-denied on a second open)
rewind($fp);
$raw  = stream_get_contents($fp);
$data = visitors_parse((string)$raw);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $now   = new DateTimeImmutable('now', new DateTimeZone('Asia/Kuala_Lumpur'));
    $day   = $now->format('Y-m-d');
    $month = $now->format('Y-m');

    $data['total']               = ($data['total']               ?? 0) + 1;
    $data['by_month'][$month]    = ($data['by_month'][$month]    ?? 0) + 1;
    $data['by_day'][$day]        = ($data['by_day'][$day]        ?? 0) + 1;

    // Keep by_day entries for the last 90 days only
    if (count($data['by_day']) > 90) {
        ksort($data['by_day']);
        $data['by_day'] = array_slice($data['by_day'], -90, 90, true);
    }

    $json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    ftruncate($fp, 0);
    rewind($fp);
    fwrite($fp, $json);
    fflush($fp);
}

flock($fp, LOCK_UN);
fclose($fp);

$now   = new DateTimeImmutable('now', new DateTimeZone('Asia/Kuala_Lumpur'));
$day   = $now->format('Y-m-d');
$month = $now->format('Y-m');

echo json_encode([
    'success'    => true,
    'count'      => $data['total'],             // back-compat alias
    'total'      => $data['total'],
    'today'      => $data['by_day'][$day]       ?? 0,
    'this_month' => $data['by_month'][$month]   ?? 0,
    'by_month'   => $data['by_month'],
    'by_day'     => $data['by_day'],
]);
exit;
