<?php
ini_set('display_errors', 0);
error_reporting(0);
ob_start();
session_start();

if (!isset($_SESSION['username'])) {
    ob_end_clean();
    header('Content-Type: application/json; charset=utf-8');
    http_response_code(401);
    echo json_encode(['success' => false, 'msg' => 'Unauthorized']);
    exit;
}

require_once __DIR__ . '/../includ/db.php';
require_once __DIR__ . '/../includ/plan_helpers.php';

$serverId = (int) ($_GET['server_id'] ?? $_POST['server_id'] ?? 0);
if ($serverId <= 0) {
    ob_end_clean();
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['success' => false, 'msg' => 'server_id required', 'inbounds' => [], 'server_type' => '']);
    exit;
}

PlanInboundHelper::ensureSchema($conn);

$row        = PlanInboundHelper::serverConfigRow($conn, $serverId);
$serverType = (string) ($row['type'] ?? '');

// Pasarguard: return available groups for group-based plan assignment
if ($serverType === 'pasarguard') {
    $botRoot = dirname(__DIR__, 2) . '/wizwizxui-timebot';
    if (file_exists($botRoot . '/services/PasarguardService.php')) {
        require_once $botRoot . '/services/PasarguardApiClient.php';
        require_once $botRoot . '/services/PasarguardConfig.php';
        require_once $botRoot . '/services/PasarguardService.php';
    }
    $groupList = [];
    if (class_exists('PasarguardService')) {
        $svc    = new PasarguardService($row);
        $groups = $svc->listGroups();
        foreach ($groups as $g) {
            $gid = (int) ($g->id ?? 0);
            if ($gid <= 0) continue;
            $name = trim((string) ($g->title ?? $g->name ?? ''));
            $groupList[] = ['id' => $gid, 'label' => ($name !== '' ? $name : 'Group #' . $gid)];
        }
    }
    $out = json_encode([
        'success'     => true,
        'server_type' => 'pasarguard',
        'inbounds'    => [],
        'groups'      => $groupList,
    ], JSON_UNESCAPED_UNICODE);
    ob_end_clean();
    header('Content-Type: application/json; charset=utf-8');
    echo $out;
    exit;
}

// Marzban: no inbounds
if ($serverType === 'marzban') {
    $out = json_encode([
        'success'     => true,
        'server_type' => 'marzban',
        'inbounds'    => [],
        'groups'      => [],
    ], JSON_UNESCAPED_UNICODE);
    ob_end_clean();
    header('Content-Type: application/json; charset=utf-8');
    echo $out;
    exit;
}

// X-UI variants: fetch inbounds from panel
// All known xui variants (normal, alireza) are treated as sanaei for the API call
$xuiVariants  = ['sanaei', 'normal', 'alireza'];
$effectiveRow = $row;
if (in_array($serverType, $xuiVariants, true) && $serverType !== 'sanaei') {
    $effectiveRow = array_merge($row, ['type' => 'sanaei']);
}
$inbounds = PlanInboundHelper::listInboundsFromRow($conn, $effectiveRow);
$out = json_encode([
    'success'     => true,
    'server_type' => in_array($serverType, $xuiVariants, true) ? 'xui' : ($serverType ?: 'xui'),
    'inbounds'    => $inbounds,
    'groups'      => [],
], JSON_UNESCAPED_UNICODE);
ob_end_clean();
header('Content-Type: application/json; charset=utf-8');
echo $out;
