<?php
/**
 * تست دقیق endpoint های inbound
 */

require_once 'config.php';

$page_title = 'تست دقیق Endpoint های Inbound';

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>نتایج تست Endpoint های Inbound:</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', '/panel/login'];
        $successful_login_url = null;
        $login_base_path = null;
        
        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);
                
                if (!$error && $httpCode === 200) {
                    $data = json_decode($response, true);
                    if (isset($data['success']) && $data['success']) {
                        echo "<div class='alert alert-success'>";
                        echo "✓ Login موفق بود!<br>";
                        echo "<strong>Login URL:</strong> $login_url<br>";
                        echo "<strong>Token:</strong> " . ($data['token'] ?? 'N/A') . "<br>";
                        echo "</div>";
                        $successful_login_url = $login_url;
                        $login_url_parts = parse_url($login_url);
                        $login_base_path = isset($login_url_parts['path']) ? dirname($login_url_parts['path']) : '';
                        if ($login_base_path === '/' || $login_base_path === '.') {
                            $login_base_path = '';
                        }
                        break 2;
                    }
                }
            }
        }
        
        if (!$successful_login_url) {
            echo "<div class='alert alert-danger'>✗ Login ناموفق بود</div>";
            exit;
        }
        
        // بررسی 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 style='max-height: 200px; overflow: auto;'>" . htmlspecialchars($cookie_content) . "</pre>";
            echo "</div>";
        } else {
            echo "<div class='alert alert-danger'>✗ Cookie file موجود نیست</div>";
        }
        
        // تست دریافت Inbound ها با endpoint های مختلف
        echo "<h4>3. تست دریافت Inbound ها:</h4>";
        
        // ساخت endpoint ها بر اساس login URL
        $inbound_endpoints = [];
        
        // از login_base_path استفاده کن
        if ($login_base_path) {
            $inbound_endpoints[] = $login_base_path . '/inbound/list';
            $inbound_endpoints[] = $login_base_path . '/API/inbounds/';
            $inbound_endpoints[] = $login_base_path . '/api/inbound/list';
            $inbound_endpoints[] = $login_base_path . '/panel/inbound/list';
        }
        
        // endpoint های استاندارد
        $inbound_endpoints = array_merge($inbound_endpoints, [
            '/xui/API/inbounds/',
            '/xui/inbound/list',
            '/panel/inbound/list',
            '/api/inbound/list',
            '/inbound/list'
        ]);
        
        // حذف تکراری ها
        $inbound_endpoints = array_unique($inbound_endpoints);
        
        foreach ($inbound_endpoints as $endpoint) {
            // ساخت URL کامل
            if ($base_path) {
                $full_url = $base_url . $base_path . $endpoint;
            } else {
                $full_url = $base_url . $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);
            
            $alert_class = 'alert-warning';
            if ($httpCode === 200) {
                $alert_class = 'alert-success';
            } else if ($httpCode >= 400) {
                $alert_class = 'alert-danger';
            }
            
            echo "<div class='alert $alert_class'>";
            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><br>";
                echo "<pre style='max-height: 300px; overflow: auto;'>" . htmlspecialchars(json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)) . "</pre>";
                echo "✓ موفق بود!<br>";
            } else {
                echo "<strong>Response:</strong> " . htmlspecialchars(substr($response, 0, 300)) . "<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>تست دقیق Endpoint های Inbound</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">تست Endpoint ها</button>
                </form>
            </div>
        </div>
    </div>
</body>
</html>
