<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// حماية الوصول
if (!defined('ALLOWED_ACCESS')) {
    http_response_code(403);
    die('Access denied.');
}

// السماح فقط بطلبات GET
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    die('Method Not Allowed');
}

// ملف اللوج للزيارات فقط
$logFile = __DIR__ . '/../private/logs/visits.txt';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../private/telegram_handler.php';
require_once __DIR__ . '/dashboard/utilits.php';

function getRealIP(): string {
    if (!empty($_SERVER['HTTP_CF_CONNECTING_IP'])) {
        return trim($_SERVER['HTTP_CF_CONNECTING_IP']);
    }
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        return trim($ips[0]);
    }
    return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
}

function logVisit(string $logFile): bool {
    try {
        $tz = new DateTimeZone('Africa/Cairo');
        $ip = getRealIP();
        $location = get_location_info($ip);
        $localTime = (new DateTime('now', $tz))->format('Y-m-d H:i:s');
        $country = $location['country'] ?? 'N/A';
        $region  = $location['region'] ?? $location['regionName'] ?? 'N/A';
        $city    = $location['city'] ?? 'N/A';
        $isp     = $location['isp'] ?? 'N/A';
        $osVer   = get_os_version($_SERVER['HTTP_USER_AGENT']);

        $visitData = sprintf(
            "%s - %s - %s - %s - %s - %s - %s\n",
            $localTime, $ip, $country, $region, $city, $isp, $osVer
        );

        file_put_contents($logFile, $visitData, FILE_APPEND | LOCK_EX);

        // Telegram Notification
        $message = "<b>📥 #New_Visit</b>\n"
            . "<b>Time:</b> <code>{$localTime}</code>\n"
            . "<b>IP:</b> <code>{$ip}</code>\n"
            . "<b>Location:</b> {$city}, {$country}\n"
            . "<b>OS:</b> <code>{$osVer}</code>\n"
            . "<b>ISP:</b> <code>{$isp}</code>";

        sendNotification($message, 'HTML');

        return true;
    } catch (Exception $e) {
        error_log('Logging failed: ' . $e->getMessage());
        return false;
    }
}

// سجل الزيارة مرة واحدة لكل جلسة
if (empty($_SESSION['visit_logged'])) {
    if (logVisit($logFile)) {
        $_SESSION['visit_logged'] = true;
    }
}
?>
