<?php
// ************ IP LOG ************
function getClientIP(): string {
    $ipKeys = [
        'HTTP_X_FORWARDED_FOR',
        'HTTP_CLIENT_IP', 
        'HTTP_X_CLUSTER_CLIENT_IP',
        'REMOTE_ADDR'
    ];
    foreach ($ipKeys as $key) {
        if (!empty($_SERVER[$key])) {
            foreach (explode(',', $_SERVER[$key]) as $ip) {
                $ip = trim($ip);
                if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
                    return $ip;
                }
            }
        }
    }
    return $_SERVER['REMOTE_ADDR'] ?? 'IP non trouvée';
}
$ip = getClientIP();
$logDir ='/var/www/html/log/';
$fileCount = $logDir . 'Compteur.NB';
$fileVisits = $logDir . 'VisitesIP.txt';
$fileLog = $logDir . 'Visites.log';
if (!is_dir($logDir)) {
    mkdir($logDir, 0775, true);
}
if (!file_exists($fileCount)) {
    file_put_contents($fileCount, "0");
}
if (!file_exists($fileVisits))
 {
    file_put_contents($fileVisits, "");
}
$count = (int)file_get_contents($fileCount);
$timeNow = time();
$delay = 86400; // 24 heures en secondes
$lines = file_exists($fileVisits) 
    ? file($fileVisits, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) 
    : [];
$newLines = [];
$found = false;
foreach ($lines as $line) {
    [$ipLogged, $timestamp] = explode('|', $line) + [null, 0];
    $timestamp = (int)$timestamp;
    if ($timeNow - $timestamp <= $delay) {
        if ($ip === $ipLogged) {
            $found = true;
        }
        $newLines[] = $ipLogged . '|' . $timestamp;
    }
}
if (!$found) {
    $count++;
    file_put_contents($fileCount, $count);
    $newLines[] = $ip . '|' . $timeNow;
    $date = date('Y-m-d H:i:s');
    $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown agent';
    $logLine = "$date | $ip | $userAgent" . PHP_EOL;
    file_put_contents($fileLog, $logLine, FILE_APPEND);
}
file_put_contents($fileVisits, implode("\n", $newLines) . "\n");
?>