<?php
// Lightweight visit tracker — logs each page view to a CSV
// Called by a 1x1 pixel or fetch() from the frontend

// ─── Deduplicate: skip bots and repeated hits ────────────────
$ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
if (preg_match('/bot|crawl|spider|slurp|Googlebot|Bingbot/i', $ua)) {
    http_response_code(204);
    exit();
}

$ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
$now = time();

// Skip if same IP visited in the last 30 minutes (session dedup)
$dedup_file = sys_get_temp_dir() . '/claire_visit_' . md5($ip);
if (file_exists($dedup_file) && ($now - filemtime($dedup_file)) < 1800) {
    // Return the tracking pixel but don't log
    header('Content-Type: image/gif');
    header('Cache-Control: no-store, no-cache');
    echo base64_decode('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7');
    exit();
}
touch($dedup_file);

// ─── Geo lookup (free, no API key, ~45 req/min limit) ────────
$region = 'Unknown';
$country = 'Unknown';
$city = 'Unknown';
try {
    $geo_url = "http://ip-api.com/json/{$ip}?fields=status,country,regionName,city";
    $ctx = stream_context_create(['http' => ['timeout' => 2]]);
    $geo_raw = @file_get_contents($geo_url, false, $ctx);
    if ($geo_raw) {
        $geo = json_decode($geo_raw, true);
        if (($geo['status'] ?? '') === 'success') {
            $country = $geo['country'] ?? 'Unknown';
            $region = $geo['regionName'] ?? 'Unknown';
            $city = $geo['city'] ?? 'Unknown';
        }
    }
} catch (Exception $e) { /* silent */
}

// ─── Log the visit ───────────────────────────────────────────
$page = $_GET['p'] ?? '/';
$referrer = $_SERVER['HTTP_REFERER'] ?? 'direct';

$data = [
    date("Y-m-d H:i:s"),
    $ip,
    htmlspecialchars($page, ENT_QUOTES, 'UTF-8'),
    htmlspecialchars($referrer, ENT_QUOTES, 'UTF-8'),
    $country,
    $region,
    $city,
    substr(htmlspecialchars($ua, ENT_QUOTES, 'UTF-8'), 0, 200)
];

$file_path = __DIR__ . '/customers/visits.csv';

// Create header row if file is new
if (!file_exists($file_path) || filesize($file_path) === 0) {
    $fp = fopen($file_path, 'w');
    if ($fp) {
        fputcsv($fp, ['timestamp', 'ip', 'page', 'referrer', 'country', 'region', 'city', 'user_agent']);
        fclose($fp);
    }
}

$fp = fopen($file_path, 'a');
if ($fp && flock($fp, LOCK_EX)) {
    fputcsv($fp, $data);
    fflush($fp);
    flock($fp, LOCK_UN);
}
if ($fp)
    fclose($fp);

// ─── Return 1x1 transparent GIF ─────────────────────────────
header('Content-Type: image/gif');
header('Cache-Control: no-store, no-cache');
echo base64_decode('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7');
exit();
?>