<?php
// ─── SunScope — Rudimentary tracking ─────────────────────────────────────────
// Accepts POST { event: "visit" | "profile", profile?: string }
// Writes daily tallies to data/tracking.json as { "YYYY-MM-DD": { visits, profiles: { key: n } } }

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

$body    = json_decode(file_get_contents('php://input'), true);
$event   = $body['event'] ?? '';
$profile = $body['profile'] ?? '';

if (!in_array($event, ['visit', 'profile'], true)) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid event']);
    exit;
}

if ($event === 'profile' && $profile === '') {
    http_response_code(400);
    echo json_encode(['error' => 'Missing profile']);
    exit;
}

$data_dir  = __DIR__ . '/data';
$data_file = $data_dir . '/tracking.json';

if (!is_dir($data_dir)) {
    mkdir($data_dir, 0755, true);
    // Block direct web access to the data folder
    file_put_contents($data_dir . '/.htaccess', "Deny from all\n");
}

$fp = fopen($data_file, 'c+');
if (!$fp) {
    http_response_code(500);
    echo json_encode(['error' => 'Could not open tracking file']);
    exit;
}

flock($fp, LOCK_EX);

$size     = fstat($fp)['size'];
$tracking = [];
if ($size > 0) {
    $tracking = json_decode(fread($fp, $size), true) ?? [];
}

$day = date('Y-m-d');
if (!isset($tracking[$day])) {
    $tracking[$day] = ['visits' => 0, 'profiles' => []];
}

if ($event === 'visit') {
    $tracking[$day]['visits']++;
} else {
    $tracking[$day]['profiles'][$profile] = ($tracking[$day]['profiles'][$profile] ?? 0) + 1;
}

ftruncate($fp, 0);
rewind($fp);
fwrite($fp, json_encode($tracking, JSON_PRETTY_PRINT));

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

echo json_encode(['ok' => true]);
