<?php
// شروع session قبل از هر چیز
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once '../config.php';

if (!isAdmin()) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'دسترسی غیرمجاز']);
    exit;
}

$panel_id = (int)($_GET['panel_id'] ?? 0);

if ($panel_id === 0) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'پنل انتخاب نشده']);
    exit;
}

try {
    $panel = $pdo->prepare("SELECT * FROM panels WHERE id = ?");
    $panel->execute([$panel_id]);
    $panel = $panel->fetch();
    
    if (!$panel) {
        throw new Exception("پنل یافت نشد");
    }
    
    require_once __DIR__ . '/../api/XrayAPI.php';
    
    // آماده‌سازی تنظیمات proxy
    $proxy_config = null;
    if (!empty($panel['proxy_host'])) {
        $proxy_config = [
            'type' => $panel['proxy_type'] ?? 'socks5',
            'host' => $panel['proxy_host'],
            'port' => $panel['proxy_port'] ?? 1080,
            'username' => $panel['proxy_username'] ?? null,
            'password' => $panel['proxy_password'] ?? null,
            'use_on_error' => !empty($panel['use_proxy'])
        ];
    }
    
    $xrayAPI = new XrayAPI($panel['url'], $panel['username'], $panel['password'], $proxy_config);
    $inbounds_result = $xrayAPI->getInbounds();
    $inbounds = $inbounds_result['obj'] ?? [];
    
    header('Content-Type: application/json');
    echo json_encode([
        'success' => true,
        'inbounds' => $inbounds
    ]);
    
} catch (Exception $e) {
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
