<?php
if (session_status() === PHP_SESSION_NONE) session_start();
require_once '../config.php';
require_once __DIR__ . '/../api/XrayAPI.php';

header('Content-Type: application/json');

// Check if user is logged in and is an admin
if (!isLoggedIn() || !isAdmin()) {
    echo json_encode(['success' => false, 'message' => 'دسترسی غیرمجاز']);
    exit;
}

$panel_id = (int)($_GET['panel_id'] ?? 0);
if ($panel_id <= 0) {
    echo json_encode(['success' => false, 'message' => 'شناسه پنل نامعتبر است']);
    exit;
}

try {
    // Fetch panel credentials from the database
    $stmt = $pdo->prepare("SELECT url, username, password, config_domain FROM panels WHERE id = ?");
    $stmt->execute([$panel_id]);
    $panel_data = $stmt->fetch();

    if (!$panel_data) {
        throw new Exception('پنل یافت نشد');
    }

    // Get inbounds from the panel
    $xrayAPI = new XrayAPI($panel_data['url'], $panel_data['username'], $panel_data['password'], null, $panel_data['config_domain'] ?? null);
    $api_response = $xrayAPI->getInbounds();

    if (isset($api_response['success']) && $api_response['success'] === true) {
        echo json_encode(['success' => true, 'inbounds' => $api_response['obj'] ?? []]);
    } else {
        throw new Exception($api_response['msg'] ?? 'خطا در ارتباط با پنل');
    }

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
