<?php
// tracker.php

function track_visitor($konek) {
    // 1. Ambil data pengunjung
    $ip         = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    $referrer   = $_SERVER['HTTP_REFERER'] ?? 'Direct';
    $page_url   = $_SERVER['REQUEST_URI'] ?? '/';
    $module     = $_GET['module'] ?? 'home';

    // Filter bot/crawler
    if (preg_match('/bot|crawl|slurp|spider|mediapartners/i', $user_agent)) {
        return;
    }

    // Deteksi Device
    $device = 'Desktop';
    if (preg_match('/mobile|android|iphone|ipad/i', $user_agent)) {
        $device = 'Mobile';
    }

    // Sanitasi data
    $ip         = mysqli_real_escape_string($konek, $ip);
    $user_agent = mysqli_real_escape_string($konek, substr($user_agent, 0, 255));
    $referrer   = mysqli_real_escape_string($konek, substr($referrer, 0, 255));
    $page_url   = mysqli_real_escape_string($konek, substr($page_url, 0, 255));
    $module     = mysqli_real_escape_string($konek, $module);

    // 2. Simpan log baru
    $query = "INSERT INTO visitor_logs (ip_address, user_agent, module, page_url, referrer, device) 
              VALUES ('$ip', '$user_agent', '$module', '$page_url', '$referrer', '$device')";
    mysqli_query($konek, $query);

    // 3. PEMBERSIH OTOMATIS (Lazy Cleanup)
    // Berjalan secara acak (1 banding 100 request) agar tidak membebani server setiap saat
    if (rand(1, 100) === 1) {
        // Hapus otomatis log yang usianya sudah lebih dari 30 hari
        $purge_query = "DELETE FROM visitor_logs WHERE created_at < DATE_SUB(NOW(), INTERVAL 30 DAY)";
        mysqli_query($konek, $purge_query);
    }
}