<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Methods: GET, POST, DELETE, OPTIONS");
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");
$ip = $_SERVER['REMOTE_ADDR'];
$log_file = 'log_ip.txt';
$ip_json_file = 'dashboard/ip.json';

file_put_contents($log_file, date('Y-m-d H:i:s') . " - $ip" . PHP_EOL, FILE_APPEND);

$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);

$visitor = [
    'ip'        => $ip,
    'city'      => $data['city'] ?? '-',
    'state'     => $data['regionName'] ?? '-',  // <-- Fix di sini
    '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' => $data]);
?>
