<?php
/**
 * تست و دیباگ Cookie ها
 */

require_once 'config.php';

$page_title = 'تست Cookie ها';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $url = $_POST['url'] ?? '';
    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';
    
    if (empty($url) || empty($username) || empty($password)) {
        $error = 'لطفاً تمام فیلدها را پر کنید';
    } else {
        echo "<h3>نتایج تست Cookie:</h3>";
        
        // استخراج base_path
        $url_clean = rtrim($url, '/');
        $url_parts = parse_url($url_clean);
        $base_path = isset($url_parts['path']) ? rtrim($url_parts['path'], '/') : '';
        
        if ($base_path) {
            $base_url = $url_parts['scheme'] . '://' . $url_parts['host'];
            if (isset($url_parts['port'])) {
                $base_url .= ':' . $url_parts['port'];
            }
        } else {
            $base_url = $url_clean;
        }
        
        $cookie_file = sys_get_temp_dir() . '/3xui_cookie_' . md5($base_url . ($base_path ?? '')) . '.txt';
        
        echo "<div class='alert alert-info'>";
        echo "<strong>اطلاعات URL:</strong><br>";
        echo "URL کامل: $url_clean<br>";
        echo "Base URL: $base_url<br>";
        echo "Base Path: '" . ($base_path ?: '(خالی)') . "'<br>";
        echo "Cookie File: $cookie_file<br>";
        echo "</div>";
        
        // تست Login
        echo "<h4>1. تست Login:</h4>";
        $login_endpoints = ['/login', '/xui/login', '/api/login'];
        
        foreach ($login_endpoints as $login_endpoint) {
            $login_urls = [];
            if ($base_path) {
                $login_urls[] = $base_url . $login_endpoint;
                $login_urls[] = $url_clean . $login_endpoint;
            } else {
                $login_urls[] = $url_clean . $login_endpoint;
            }
            
            foreach ($login_urls as $login_url) {
                $ch = curl_init();
                curl_setopt_array($ch, [
                    CURLOPT_URL => $login_url,
                    CURLOPT_POST => true,
                    CURLOPT_POSTFIELDS => json_encode([
                        'username' => $username,
                        'password' => $password
                    ]),
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_FOLLOWLOCATION => true,
                    CURLOPT_MAXREDIRS => 5,
                    CURLOPT_HTTPHEADER => [
                        'Content-Type: application/json'
                    ],
                    CURLOPT_COOKIEJAR => $cookie_file,
                    CURLOPT_COOKIEFILE => $cookie_file,
                    CURLOPT_TIMEOUT => 10,
                    CURLOPT_CONNECTTIMEOUT => 5
                ]);
                
                $response = curl_exec($ch);
                $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                $error = curl_error($ch);
                curl_close($ch);
                
                echo "<div class='alert " . ($httpCode === 200 ? 'alert-success' : 'alert-danger') . "'>";
                echo "<strong>Login URL:</strong> $login_url<br>";
                echo "<strong>HTTP Code:</strong> $httpCode<br>";
                if ($error) echo "<strong>Error:</strong> $error<br>";
                if ($httpCode === 200) {
                    $data = json_decode($response, true);
                    echo "<strong>Response:</strong> " . substr(json_encode($data, JSON_UNESCAPED_UNICODE), 0, 200) . "<br>";
                    if (isset($data['success']) && $data['success']) {
                        echo "✓ Login موفق بود!<br>";
                        break 2; // خروج از هر دو حلقه
                    }
                }
                echo "</div>";
            }
        }
        
        // بررسی Cookie File
        echo "<h4>2. بررسی Cookie File:</h4>";
        if (file_exists($cookie_file)) {
            $cookie_content = file_get_contents($cookie_file);
            $cookie_size = filesize($cookie_file);
            echo "<div class='alert alert-success'>";
            echo "✓ Cookie file موجود است ($cookie_size bytes)<br>";
            echo "<pre>" . htmlspecialchars($cookie_content) . "</pre>";
            echo "</div>";
        } else {
            echo "<div class='alert alert-danger'>✗ Cookie file موجود نیست</div>";
        }
        
        // تست دریافت Inbound ها
        echo "<h4>3. تست دریافت Inbound ها:</h4>";
        $inbound_endpoints = [
            '/xui/API/inbounds/',
            '/xui/inbound/list',
            '/panel/inbound/list',
            '/api/inbound/list',
            '/inbound/list'
        ];
        
        foreach ($inbound_endpoints as $endpoint) {
            $full_url = $base_url . ($base_path ? $base_path : '') . $endpoint;
            
            $ch = curl_init();
            curl_setopt_array($ch, [
                CURLOPT_URL => $full_url,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_MAXREDIRS => 5,
                CURLOPT_HTTPHEADER => [
                    'Content-Type: application/json',
                    'Accept: application/json'
                ],
                CURLOPT_COOKIEFILE => $cookie_file,
                CURLOPT_COOKIEJAR => $cookie_file,
                CURLOPT_TIMEOUT => 10,
                CURLOPT_CONNECTTIMEOUT => 5
            ]);
            
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $effective_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
            $error = curl_error($ch);
            curl_close($ch);
            
            echo "<div class='alert " . ($httpCode === 200 ? 'alert-success' : ($httpCode === 404 ? 'alert-warning' : 'alert-danger')) . "'>";
            echo "<strong>Endpoint:</strong> $endpoint<br>";
            echo "<strong>URL:</strong> $full_url<br>";
            echo "<strong>Effective URL:</strong> $effective_url<br>";
            echo "<strong>HTTP Code:</strong> $httpCode<br>";
            if ($error) echo "<strong>Error:</strong> $error<br>";
            if ($httpCode === 200) {
                $result = json_decode($response, true);
                echo "<strong>Response:</strong> " . substr(json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE), 0, 500) . "<br>";
                echo "✓ موفق بود!<br>";
                break;
            } else {
                echo "<strong>Response:</strong> " . substr($response, 0, 200) . "<br>";
            }
            echo "</div>";
        }
    }
}

?>
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $page_title ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-5">
        <div class="card">
            <div class="card-header bg-primary text-white">
                <h4>تست و دیباگ Cookie ها</h4>
            </div>
            <div class="card-body">
                <?php if (isset($error)): ?>
                    <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
                <?php endif; ?>
                
                <form method="POST">
                    <div class="mb-3">
                        <label class="form-label">آدرس پنل (URL)</label>
                        <input type="url" name="url" class="form-control" value="<?= htmlspecialchars($_POST['url'] ?? '') ?>" required>
                        <small class="form-text text-muted">مثال: http://168.119.186.37:2053</small>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">نام کاربری</label>
                        <input type="text" name="username" class="form-control" value="<?= htmlspecialchars($_POST['username'] ?? '') ?>" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">رمز عبور</label>
                        <input type="password" name="password" class="form-control" required>
                    </div>
                    <button type="submit" class="btn btn-primary">تست Cookie ها</button>
                </form>
            </div>
        </div>
    </div>
</body>
</html>
