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

function getUserIP() {
    return $_SERVER['REMOTE_ADDR'] ?? 'UNKNOWN';
}

function getBrowser() {
    return $_SERVER['HTTP_USER_AGENT'] ?? 'UNKNOWN';
}

function getDevice() {
    $ua = strtolower($_SERVER['HTTP_USER_AGENT']);
    if (strpos($ua, "mobile") !== false) return "Mobile";
    if (strpos($ua, "tablet") !== false) return "Tablet";
    return "Desktop";
}

// Geo IP Lookup (FREE API)
$ip = getUserIP();
$geo = json_decode(file_get_contents("https://ipapi.co/{$ip}/json/"), true);

$country = $geo["country_name"] ?? "Unknown";
$region  = $geo["region"] ?? "Unknown";
$city    = $geo["city"] ?? "Unknown";
$browser = getBrowser();
$device  = getDevice();

$page = $_SERVER['REQUEST_URI'];
$session = session_id();

// If visitor is new
if (!isset($_SESSION["visitor_logged"])) {

    $_SESSION["visitor_logged"] = true;
    $_SESSION["start_time"] = date("Y-m-d H:i:s");
    $_SESSION["first_page"] = $page;

    $stmt = $conn->prepare("
        INSERT INTO visitors_log 
        (session_id, ip_address, country, region, city, browser, device, first_page, start_time)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");

    $stmt->bind_param(
        "sssssssss",
        $session, $ip, $country, $region, $city, $browser, $device,
        $_SESSION["first_page"], $_SESSION["start_time"]
    );
    $stmt->execute();

    $_SESSION["visitor_db_id"] = $conn->insert_id;
}

// Update last page + time spent
$end_time = date("Y-m-d H:i:s");
$start_time = $_SESSION["start_time"];
$duration = strtotime($end_time) - strtotime($start_time);

$stmt = $conn->prepare("
    UPDATE visitors_log SET 
        last_page=?, 
        end_time=?, 
        duration_seconds=?
    WHERE id=?
");
$stmt->bind_param("ssii", $page, $end_time, $duration, $_SESSION["visitor_db_id"]);
$stmt->execute();
?>
