<?php
$ip = $_SERVER['REMOTE_ADDR'];
$log_file = 'log_ip.txt';
$ip_json_file = 'admin/ip.json';

$apiUrl = 'http://ip-api.com/json/' . urlencode($ip);
$ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

if ($response === false) {
    echo json_encode(['error' => 'Gagal mengambil data lokasi.']);
    exit();
}

$data = json_decode($response, true);

$city    = $data['city'] ?? '-';
$state   = $data['regionName'] ?? '-';
$country = $data['country'] ?? '-';

$log_entry = sprintf(
    "%s - %s - %s, %s\n",
    date('Y-m-d H:i:s'),
    $ip,
    $country,
    $state
);

file_put_contents($log_file, $log_entry, FILE_APPEND);

$visitor = array_merge($data, [
    'ip'        => $ip,
    'city'      => $data['city'] ?? '-',
    'state'     => $data['regionName'] ?? '-',
    'country'   => $data['country'] ?? '-',
    'timestamp' => date('Y-m-d H:i:s')
]);

$existing = file_exists($ip_json_file) ? json_decode(file_get_contents($ip_json_file), true) : [];
$existing[] = $visitor;

file_put_contents($ip_json_file, json_encode($existing, JSON_PRETTY_PRINT));

echo json_encode(['status' => 'saved', 'visitor' => $visitor]);
?>
