<?php
// monitor.php
date_default_timezone_set('Asia/Taipei');

$scriptName = basename($_SERVER['SCRIPT_NAME']);
$ip = $_SERVER['REMOTE_ADDR'];
$logFile = 'visitor_log.csv';

// 1. Get Location Info (City/Country)
// We use a @ to suppress errors if the API is down
$locationData = @json_decode(file_get_contents("http://ip-api.com/json/{$ip}?fields=status,country,city"));

if ($locationData && $locationData->status == 'success') {
    $area = $locationData->city . ', ' . $locationData->country;
} else {
    $area = "Unknown Area";
}

// 2. Save to CSV: Time, Script, IP, Area
$data = [
    date('Y-m-d H:i:s'),
    $scriptName,
    $ip,
    $area
];

$f = fopen($logFile, 'a');
fputcsv($f, $data);
fclose($f);

// 3. Update the total counts (for the summary table)
$statsFile = 'script_stats.json';
$stats = file_exists($statsFile) ? json_decode(file_get_contents($statsFile), true) : [];
$stats[$scriptName]['hits'] = ($stats[$scriptName]['hits'] ?? 0) + 1;
$stats[$scriptName]['last_seen'] = date('Y-m-d H:i:s');
file_put_contents($statsFile, json_encode($stats));
?>