<?php
// Abilita il buffering di output implicito in modo che l'output venga scaricato immediatamente
ob_implicit_flush(true);
ob_end_flush();

// Clear log files before starting other processes
$log_dir = '/var/www/html/reseller/log/';

if (is_dir($log_dir)) {
    $files = glob($log_dir . '*'); // Fetch all files in the directory
    foreach ($files as $file) {
        if (is_file($file)) {
            unlink($file); // Remove each log file
        }
    }
}
?>
<!DOCTYPE html>
<html lang="it">
<head>
    <meta charset="UTF-8">
    <title>Risultati Verifica Proxy Exclusive</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        table, th, td {
            border: 1px solid #ddd;
        }
        th, td {
            padding: 8px;
            text-align: left;
        }
        th {
            background-color: #f2f2f2;
        }
        .status {
            font-weight: bold;
        }
        .status-success {
            color: green;
        .status-fail {
            color: red;
        }
        /* CSS for the progress bar */
        .progress-container {
            width: 100%;
            background-color: #f3f3f3;
            border: 1px solid #ddd;
            margin-bottom: 20px;
        }
        .progress-bar {
            width: 0;
            height: 25px;
            background-color: #4caf50;
            text-align: center;
            line-height: 25px;
            color: white;
        }
    </style>
</head>
<body>
    <h2>Risultati Verifica Proxy Exclusive</h2>
    <div class="progress-container">
        <div class="progress-bar" id="progress-bar">0%</div>
    </div>
    <table>
        <thead>
            <tr>
                <th>Proxy</th>
                <th>Ping</th>
                <th>Download Video (HTTP)</th>
                <th>Link Generato (HTTP)</th>
            </tr>
        </thead>
        <tbody id="results">
            <?php
            function flushResult($content) {
                echo $content;
                ob_flush();
                flush();
            }

            function updateProgressBar($current, $total) {
                $percent = ($current / $total) * 100;
                echo "<script>document.getElementById('progress-bar').style.width = '{$percent}%'; document.getElementById('progress-bar').innerText = '".round($percent)."%';</script>";
                ob_flush();
                flush();
            }

            // Function to ping hosts
            function ping($host) {
                $output = [];
                $command = "ping -c 1 $host";
                exec($command, $output, $result);
                $parsed_output = "";
                if ($result === 0) {
                    foreach ($output as $line) {
                        if (strpos($line, 'icmp_seq') !== false) {
                            $parsed_output = $line;
                            break;
                        }
                    }
                }
                $ping_status = $result === 0 ? 'Riuscito' : 'Fallito';
                $ping_result = $result === 0 ? '<span class="status status-success">'.$ping_status.'</span>' : '<span class="status status-fail">'.$ping_status.'</span>';
                error_log("[DEBUG] Ping risultato per $host: $ping_result - $parsed_output");
                return ['result' => $ping_result, 'output' => $parsed_output];
            }

            function checkVideoDownloadHTTP($proxy, $url_path) {
                $url = 'http://' . $proxy . ':80' . $url_path;
                $url = 'http://' . $proxy . ':80' . $url_path;
                error_log("[DEBUG] Verifica URL: $url");
                $log_dir = '/var/www/html/reseller/log/';

                if (!is_dir($log_dir)) {
                    mkdir($log_dir, 0777, true);
                }

                $log_file = $log_dir . 'wget_' . str_replace('.', '_', $proxy) . '.log';
                $tries = 0;
                $max_tries = 3;
                $success = false;
                $log_content = '';

                while (!$success && $tries < $max_tries) {
                    $command = "timeout 5s wget --proxy=on --header='User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:95.0) Gecko/20100101 Firefox/95.0' --timeout=50 --output-document=- {$url} > {$log_file} 2>&1";
                    error_log("[DEBUG] Comando eseguito (tentativo " . ($tries + 1) . "): $command");
                    exec($command, $output, $result);
                    $log_content = @file_get_contents($log_file);
                    error_log("[DEBUG] Contenuto log wget (tentativo " . ($tries + 1) . "): $log_content");

                    if (strpos($log_content, '200 OK') !== false) {
                        $success = true;
                    } else if (strpos($log_content, '403 Forbidden') !== false) {
                        $tries++;
                    } else {
                        break;
                    }
                }

                // Verifica salvatura log
                if (file_exists($log_file)) {
                    error_log("[DEBUG] File di log creato con successo: $log_file");
                } else {
                    error_log("[ERROR] Impossibile creare il file di log: $log_file");
                }

                // Effettiva verifica del download
                $success = strpos($log_content, '200 OK') !== false;

                // Log di debug
                error_log("[DEBUG] Risultato esecuzione wget: $result");
                error_log("[DEBUG] Stato del download: " . ($success ? "Riuscito" : "Fallito"));

                return $success;
            }

            $proxies_exclusive = [
                '160.238.67.240', '160.238.67.241', '160.238.67.242', '160.238.67.243',
                '160.238.67.244', '160.238.67.245', '160.238.67.246', '160.238.67.247',
                '160.238.67.248', '160.238.67.249', '160.238.67.250', '160.238.67.251',
                '160.238.67.252', '160.238.67.253', '160.238.67.254', '103.240.148.215','fastweb.mggteam.site','mgg.mggteam.site'
            ];

            $url_path_exclusive = '/live/mgg_mytest2/secapir/51525.ts';
            $total_proxies = count($proxies_exclusive);
            $current_proxy = 0;
            foreach ($proxies_exclusive as $proxy) {
                $current_proxy++;
                $ping_result_info = ping($proxy);
                $ping_result = $ping_result_info['result'];
                $ping_output = $ping_result_info['output'];
                $video_http_result = checkVideoDownloadHTTP($proxy, $url_path_exclusive) ? '<span class="status-success">Download Riuscito</span>' : '<span class="status-fail">Download Fallito</span>';
                $http_link = "http://$proxy:80/live/mgg_001001001/secapir/63461.ts";
                $content = "<tr>
                        <td>$proxy</td>
                        <td>$ping_result <br><small>$ping_output</small></td>
                        <td>$video_http_result</td>
                        <td><a href='$http_link'>Vai al link</a></td>
                      </tr>";
                flushResult($content);
                updateProgressBar($current_proxy, $total_proxies);
            }
            ?>
        </tbody>
    </table>

    <h2>Risultati Verifica Proxy Fonseca</h2>
    <table>
        <thead>
            <tr>
                <th>Proxy</th>
                <th>Ping</th>
                <th>Download Video (HTTP)</th>
                <th>Link Generato (HTTP)</th>
            </tr>
        </thead>
        <tbody id="results-fonseca">
            <?php
            $proxies_fonseca = ['test.mggteam.live'];
            $url_path_fonseca = '/mgg_multi052/tgs2g6mp/289';
            $total_proxies_fonseca = count($proxies_fonseca);
            $current_proxy_fonseca = 0;
            foreach ($proxies_fonseca as $proxy) {
                $current_proxy_fonseca++;
                $ping_result_info = ping($proxy);
                $ping_result = $ping_result_info['result'];
                $ping_output = $ping_result_info['output'];
                $video_http_result = checkVideoDownloadHTTP($proxy, $url_path_fonseca) ? '<span class="status-success">Download Riuscito</span>' : '<span class="status-fail">Download Fallito</span>';
                $http_link = "http://$proxy:80$url_path_fonseca";
                $content = "<tr>
                        <td>$proxy</td>
                        <td>$ping_result <br><small>$ping_output</small></td>
                        <td>$video_http_result</td>
                        <td><a href='$http_link'>Vai al link</a></td>
                      </tr>";
                flushResult($content);
                updateProgressBar($current_proxy_fonseca, $total_proxies_fonseca);
            }
            ?>
        </tbody>
    </table>
</body>
</html>
