<?php
$rawData = file_get_contents("php://input");
$data = json_decode($rawData, true);

// Ambil data
$page_url = $data['page_url'] ?? '';
$referer = $data['referer'] ?? '';
$user_agent = $data['user_agent'] ?? '';
$session_id = $data['session_id'] ?? '';
$ip_address = $_SERVER['REMOTE_ADDR'] ?? 'UNKNOWN';

// Ambil negara dari IP
$geo = @file_get_contents("http://ip-api.com/json/" . $ip_address);
$country = 'Unknown';
if ($geo !== false) {
    $geo = json_decode($geo, true);
    if ($geo['status'] === 'success') {
        $country = $geo['country'];
    }
}

// Simpan ke database
$conn = new mysqli("localhost", "daftczwl_login", "Masuksini123@", "daftczwl_visitor_logs");
if ($conn->connect_error) {
    http_response_code(500);
    exit("Database connection failed");
}

$stmt = $conn->prepare("INSERT INTO visitor_logs (page_url, referer, ip_address, user_agent, session_id, country) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bind_param("ssssss", $page_url, $referer, $ip_address, $user_agent, $session_id, $country);
$stmt->execute();
$stmt->close();
$conn->close();

echo "Logged";
