<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../config.php';

if (!isLoggedIn() || !isAdmin()) {
    setMessage('دسترسی غیرمجاز', 'error');
    redirect('../login.php');
}

$page_title = 'چک کانفیگ پنل';

$panel_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($panel_id === 0) {
    setMessage('پنل انتخاب نشده', 'error');
    redirect('panels.php');
}

$panel = $pdo->prepare("SELECT * FROM panels WHERE id = ?");
$panel->execute([$panel_id]);
$panel = $panel->fetch();

if (!$panel) {
    setMessage('پنل یافت نشد', 'error');
    redirect('panels.php');
}

$config = null;
$check_result = ['valid' => false, 'errors' => [], 'warnings' => [], 'inboundCount' => 0, 'outboundCount' => 0];
$raw_config = null;

$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'])
    ];
}

require_once __DIR__ . '/../api/XrayAPI.php';

try {
    $xrayAPI = new XrayAPI($panel['url'], $panel['username'], $panel['password'], $proxy_config);
    $config = $xrayAPI->getConfigJson();
    $raw_config = $config;
    
    if (isset($config['raw'])) {
        $decoded = json_decode($config['raw'], true);
        $config = $decoded !== null ? $decoded : $config;
    }
    
    $check_result['inboundCount'] = isset($config['inbounds']) && is_array($config['inbounds']) ? count($config['inbounds']) : 0;
    $check_result['outboundCount'] = isset($config['outbounds']) && is_array($config['outbounds']) ? count($config['outbounds']) : 0;
    
    if (!isset($config['log'])) {
        $check_result['warnings'][] = 'بخش log تعریف نشده';
    }
    
    if (!isset($config['inbounds']) || !is_array($config['inbounds'])) {
        $check_result['errors'][] = 'inbounds نامعتبر یا خالی است';
    } else {
        foreach ($config['inbounds'] as $i => $ib) {
            if (empty($ib['port'])) {
                $check_result['errors'][] = 'اینباند ' . ($i + 1) . ': port تعریف نشده';
            }
            if (empty($ib['protocol'])) {
                $check_result['errors'][] = 'اینباند ' . ($i + 1) . ': protocol تعریف نشده';
            }
        }
    }
    
    if (!isset($config['outbounds']) || !is_array($config['outbounds'])) {
        $check_result['errors'][] = 'outbounds نامعتبر یا خالی است';
    }
    
    $check_result['valid'] = count($check_result['errors']) === 0;
    
} catch (Exception $e) {
    $check_result['errors'][] = $e->getMessage();
}

$show_raw = isset($_GET['raw']) && $_GET['raw'] === '1';

require_once '../includes/header.php';
?>

<div class="card admin-main-card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0"><i class="bi bi-file-earmark-check"></i> چک کانفیگ: <?= htmlspecialchars($panel['name']) ?></h5>
        <div>
            <a href="panel_monitor.php" class="btn btn-sm btn-secondary"><i class="bi bi-arrow-right"></i> بازگشت به مانیتور</a>
            <a href="panel_manage.php?id=<?= $panel_id ?>" class="btn btn-sm btn-primary"><i class="bi bi-gear"></i> مدیریت پنل</a>
        </div>
    </div>
    <div class="card-body">
        <?php if (!empty($check_result['errors']) && $config === null): ?>
            <div class="alert alert-danger">
                <strong>خطا در اتصال به پنل:</strong>
                <ul class="mb-0 mt-2">
                    <?php foreach ($check_result['errors'] as $err): ?>
                        <li><?= htmlspecialchars($err) ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
        <?php else: ?>
            <div class="alert alert-<?= $check_result['valid'] ? 'success' : 'danger' ?>">
                <h6>
                    <?php if ($check_result['valid']): ?>
                        <i class="bi bi-check-circle"></i> کانفیگ معتبر است
                    <?php else: ?>
                        <i class="bi bi-x-circle"></i> مشکلات در کانفیگ
                    <?php endif; ?>
                </h6>
                <?php if (!empty($check_result['errors'])): ?>
                    <ul class="mb-0">
                        <?php foreach ($check_result['errors'] as $err): ?>
                            <li><?= htmlspecialchars($err) ?></li>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>
                <?php if (!empty($check_result['warnings'])): ?>
                    <p class="text-warning mb-0 mt-2">
                        <strong>هشدارها:</strong>
                        <?php foreach ($check_result['warnings'] as $w): ?>
                            <br>• <?= htmlspecialchars($w) ?>
                        <?php endforeach; ?>
                    </p>
                <?php endif; ?>
                <p class="mb-0 mt-2">
                    <strong>اینباندها:</strong> <?= $check_result['inboundCount'] ?> |
                    <strong>اوت‌باندها:</strong> <?= $check_result['outboundCount'] ?>
                </p>
            </div>
            
            <?php if ($config !== null): ?>
                <div class="mt-3">
                    <?php if ($show_raw): ?>
                        <h6>Config کامل (JSON):</h6>
                        <pre class="bg-dark text-light p-3 rounded" style="max-height: 500px; overflow: auto; direction: ltr; text-align: left;"><?= htmlspecialchars(json_encode($raw_config, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)) ?></pre>
                        <a href="config_check.php?id=<?= $panel_id ?>" class="btn btn-sm btn-secondary">پنهان کردن config</a>
                    <?php else: ?>
                        <a href="config_check.php?id=<?= $panel_id ?>&raw=1" class="btn btn-primary">
                            <i class="bi bi-file-earmark-code"></i> مشاهده config کامل
                        </a>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        <?php endif; ?>
    </div>
</div>

<?php require_once '../includes/footer.php'; ?>
