<?php
session_start();
require "config.php";

date_default_timezone_set('Asia/Jakarta');

$session = session_id();
$ip = $_SERVER['REMOTE_ADDR'] ?? '';
$agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
$url = $_SERVER['REQUEST_URI'] ?? '';
$date = date('Y-m-d');

/* DEBUG (hapus nanti kalau sudah normal) */
file_put_contents("visitor_debug.txt", $session." | ".$date."\n", FILE_APPEND);

/* CEK DATA */
$stmt = $conn->prepare("
SELECT id FROM visitors 
WHERE session_id = ? AND visit_date = ?
LIMIT 1
");
$stmt->bind_param("ss", $session, $date);
$stmt->execute();
$res = $stmt->get_result();

if ($res->num_rows == 0) {

    $insert = $conn->prepare("
    INSERT INTO visitors 
    (session_id, ip_address, user_agent, url, visit_date, created_at)
    VALUES (?, ?, ?, ?, ?, NOW())
    ");
    $insert->bind_param("sssss", $session, $ip, $agent, $url, $date);
    $insert->execute();

} else {

    $update = $conn->prepare("
    UPDATE visitors 
    SET created_at = NOW(), url = ?
    WHERE session_id = ? AND visit_date = ?
    ");
    $update->bind_param("sss", $url, $session, $date);
    $update->execute();
}
?>