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

require_once '../config.php';

// بررسی لاگین
if (!isLoggedIn()) {
    redirect('../login.php');
}

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

$page_title = 'مدیریت کامل پنل';

// دریافت ID پنل
$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');
}

// آماده‌سازی تنظیمات 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'])
    ];
}

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

// عملیات‌های مدیریتی
$error_message = null;
$success_message = null;

try {
    $xrayAPI = new XrayAPI($panel['url'], $panel['username'], $panel['password'], $proxy_config);
    
    // دریافت اطلاعات پنل
    $inbounds = $xrayAPI->getInbounds();
    $inbounds_list = $inbounds['obj'] ?? [];
    
    // دریافت آمار ترافیک
    $traffic_stats = $xrayAPI->getDetailedPanelTraffic();
    
    // دریافت آمار سیستم
    $system_stats = null;
    try {
        $system_stats = $xrayAPI->getSystemStats();
    } catch (Exception $e) {
        // ممکن است این endpoint در برخی نسخه‌ها موجود نباشد
    }
    
    // عملیات‌های POST
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $action = $_POST['action'] ?? '';
        
        switch ($action) {
            case 'toggle_inbound':
                $inbound_id = (int)($_POST['inbound_id'] ?? 0);
                $enable = isset($_POST['enable']) && $_POST['enable'] == '1';
                $xrayAPI->toggleInbound($inbound_id, $enable);
                $success_message = 'وضعیت Inbound تغییر کرد';
                // بارگذاری مجدد
                $inbounds = $xrayAPI->getInbounds();
                $inbounds_list = $inbounds['obj'] ?? [];
                break;
                
            case 'toggle_client':
                $inbound_id = (int)($_POST['inbound_id'] ?? 0);
                $client_id = $_POST['client_id'] ?? '';
                $enable = isset($_POST['enable']) && $_POST['enable'] == '1';
                $xrayAPI->toggleClient($inbound_id, $client_id, $enable);
                $success_message = 'وضعیت کلاینت تغییر کرد';
                // بارگذاری مجدد
                $inbounds = $xrayAPI->getInbounds();
                $inbounds_list = $inbounds['obj'] ?? [];
                break;
                
            case 'reset_client_traffic':
                $inbound_id = (int)($_POST['inbound_id'] ?? 0);
                $client_id = $_POST['client_id'] ?? '';
                $xrayAPI->resetClientTraffic($inbound_id, $client_id);
                $success_message = 'ترافیک کلاینت ریست شد';
                // بارگذاری مجدد
                $inbounds = $xrayAPI->getInbounds();
                $inbounds_list = $inbounds['obj'] ?? [];
                $traffic_stats = $xrayAPI->getDetailedPanelTraffic();
                break;
                
            case 'reset_inbound_traffic':
                $inbound_id = (int)($_POST['inbound_id'] ?? 0);
                $xrayAPI->resetInboundTraffic($inbound_id);
                $success_message = 'ترافیک Inbound ریست شد';
                // بارگذاری مجدد
                $inbounds = $xrayAPI->getInbounds();
                $inbounds_list = $inbounds['obj'] ?? [];
                $traffic_stats = $xrayAPI->getDetailedPanelTraffic();
                break;
                
            case 'reset_all_traffic':
                $xrayAPI->resetAllTraffic();
                $success_message = 'ترافیک کل پنل ریست شد';
                // بارگذاری مجدد
                $inbounds = $xrayAPI->getInbounds();
                $inbounds_list = $inbounds['obj'] ?? [];
                $traffic_stats = $xrayAPI->getDetailedPanelTraffic();
                break;
                
            case 'save_inbound_limits':
                $limits = isset($_POST['inbound_limit']) && is_array($_POST['inbound_limit']) ? $_POST['inbound_limit'] : [];
                try {
                    foreach ($limits as $inbound_id => $user_limit) {
                        $inbound_id = (int)$inbound_id;
                        $user_limit = (int)$user_limit;
                        if ($inbound_id > 0) {
                            $stmt = $pdo->prepare("INSERT INTO panel_inbounds (panel_id, inbound_id, user_limit) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE user_limit = VALUES(user_limit)");
                            $stmt->execute([$panel_id, $inbound_id, $user_limit]);
                        }
                    }
                    $success_message = 'محدودیت اینباندها ذخیره شد';
                } catch (Exception $ex) {
                    $success_message = 'خطا در ذخیره: ' . $ex->getMessage();
                }
                $inbounds = $xrayAPI->getInbounds();
                $inbounds_list = $inbounds['obj'] ?? [];
                break;
        }
    }
    
    // بارگذاری محدودیت هر اینباند در سطح پنل
    $panel_inbound_limits = [];
    try {
        $stmt = $pdo->prepare("SELECT inbound_id, user_limit FROM panel_inbounds WHERE panel_id = ?");
        $stmt->execute([$panel_id]);
        while ($row = $stmt->fetch()) {
            $panel_inbound_limits[(int)$row['inbound_id']] = (int)$row['user_limit'];
        }
    } catch (Exception $e) {
        // جدول ممکن است وجود نداشته باشد
    }
    
} catch (Exception $e) {
    $error_message = 'خطا در اتصال به پنل: ' . $e->getMessage();
    $inbounds_list = [];
    $traffic_stats = ['total' => 0, 'total_up' => 0, 'total_down' => 0, 'inbounds' => []];
    $panel_inbound_limits = [];
}

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

<?php if ($error_message): ?>
    <div class="alert alert-danger alert-dismissible fade show">
        <?= htmlspecialchars($error_message) ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<?php if ($success_message): ?>
    <div class="alert alert-success alert-dismissible fade show">
        <?= htmlspecialchars($success_message) ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

    <!-- Page Title -->
    <div class="row">
        <div class="col-12">
            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                <h4 class="mb-sm-0 font-size-18">مدیریت پنل: <?= htmlspecialchars($panel['name']) ?></h4>
                <div class="page-title-right">
                    <ol class="breadcrumb m-0">
                        <li class="breadcrumb-item"><a href="dashboard.php">داشبورد</a></li>
                        <li class="breadcrumb-item"><a href="panels.php">مدیریت پنل‌ها</a></li>
                        <li class="breadcrumb-item active"><?= htmlspecialchars($panel['name']) ?></li>
                    </ol>
                </div>
            </div>
        </div>
    </div>

    <!-- Stats Cards -->
    <div class="row g-4 mb-4">
        <div class="col-md-6 col-xl-3">
            <div class="card stat-card-pro h-100">
                <div class="card-body d-flex align-items-center">
                    <div class="stat-icon bg-soft-primary text-primary me-3"><i class="bi bi-box-arrow-in-down"></i></div>
                    <div>
                        <h6 class="text-muted fw-normal mt-0">ترافیک دانلود</h6>
                        <h3 class="mt-1 mb-0"><?= formatBytes($traffic_stats['total_down']) ?></h3>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-6 col-xl-3">
            <div class="card stat-card-pro h-100">
                 <div class="card-body d-flex align-items-center">
                    <div class="stat-icon bg-soft-primary text-primary me-3"><i class="bi bi-box-arrow-in-up"></i></div>
                    <div>
                        <h6 class="text-muted fw-normal mt-0">ترافیک آپلود</h6>
                        <h3 class="mt-1 mb-0"><?= formatBytes($traffic_stats['total_up']) ?></h3>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-6 col-xl-3">
            <div class="card stat-card-pro h-100">
                 <div class="card-body d-flex align-items-center">
                    <div class="stat-icon bg-soft-info text-info me-3"><i class="bi bi-hdd-stack"></i></div>
                    <div>
                        <h6 class="text-muted fw-normal mt-0">تعداد Inbound ها</h6>
                        <h3 class="mt-1 mb-0"><?= count($inbounds_list) ?></h3>
                    </div>
                </div>
            </div>
        </div>
        <?php if ($system_stats && isset($system_stats['mem'])): ?>
        <div class="col-md-6 col-xl-3">
            <div class="card stat-card-pro h-100">
                 <div class="card-body d-flex align-items-center">
                    <div class="stat-icon bg-soft-success text-success me-3"><i class="bi bi-memory"></i></div>
                    <div>
                        <h6 class="text-muted fw-normal mt-0">مصرف RAM</h6>
                        <h3 class="mt-1 mb-0"><?= formatBytes($system_stats['mem']['current']) ?> / <?= formatBytes($system_stats['mem']['total']) ?></h3>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>

<div class="card">
    <div class="card-header">
        <div class="d-flex flex-wrap align-items-center">
            <h5 class="card-title flex-grow-1 mb-0"> <i class="bi bi-diagram-3"></i> لیست Inbound ها</h5>
            <div class="flex-shrink-0">
                <form method="POST" class="d-inline-block" onsubmit="return confirm('آیا مطمئن هستید که می‌خواهید ترافیک کل پنل را ریست کنید؟')">
                    <input type="hidden" name="action" value="reset_all_traffic">
                    <button type="submit" class="btn btn-sm btn-danger">
                        <i class="bi bi-arrow-clockwise"></i> ریست ترافیک کل
                    </button>
                </form>
            </div>
        </div>
    </div>
    <div class="card-body">
        <?php if (empty($inbounds_list)): ?>
            <div class="alert alert-info">
                <i class="bi bi-info-circle"></i> هیچ Inbound یافت نشد
            </div>
        <?php else: ?>
            <form method="POST" class="mb-3">
                <input type="hidden" name="action" value="save_inbound_limits">
                <div class="table-responsive">
                    <table class="table table-striped table-hover align-middle">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>نام</th>
                                <th>پورت</th>
                                <th>پروتکل</th>
                                <th>وضعیت</th>
                                <th>تعداد کلاینت</th>
                                <th>ترافیک</th>
                                <th>ظرفیت کاربر</th>
                                <th>عملیات</th>
                            </tr>
                        </thead>
                            <tbody>
                                <?php foreach ($inbounds_list as $inbound): 
                                    $inbound_traffic = null;
                                    foreach ($traffic_stats['inbounds'] as $t) {
                                        if ($t['id'] == $inbound['id']) {
                                            $inbound_traffic = $t;
                                            break;
                                        }
                                    }
                                    $clients_count = isset($inbound['clients']) ? count($inbound['clients']) : 0;
                                    $is_enabled = isset($inbound['enable']) ? $inbound['enable'] : true;
                                    $inbound_id = $inbound['id'] ?? 'inbound-' . uniqid();
                                ?>
                                    <tr class="inbound-row">
                                        <td><?= $inbound['id'] ?></td>
                                        <td><strong><?= htmlspecialchars($inbound['remark'] ?? 'بدون نام') ?></strong></td>
                                        <td><?= $inbound['port'] ?? '-' ?></td>
                                        <td><span class="badge bg-primary"><?= htmlspecialchars($inbound['protocol'] ?? '-') ?></span></td>
                                        <td>
                                            <?php if ($is_enabled): ?>
                                                <span class="badge bg-success">فعال</span>
                                            <?php else: ?>
                                                <span class="badge bg-danger">غیرفعال</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <span class="badge rounded-pill bg-info"><?= $clients_count ?></span>
                                        </td>
                                        <td>
                                            <?php if ($inbound_traffic): ?>
                                                <div class="traffic-cell">
                                                    <span><i class="bi bi-arrow-up text-muted"></i> <?= formatBytes($inbound_traffic['up']) ?></span>
                                                    <span class="mx-1">|</span>
                                                    <span><i class="bi bi-arrow-down text-muted"></i> <?= formatBytes($inbound_traffic['down']) ?></span>
                                                    <strong class="d-block mt-1">کل: <?= formatBytes($inbound_traffic['total']) ?></strong>
                                                </div>
                                            <?php else: ?>
                                                <span class="text-muted">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php $pid = (int)($inbound['id'] ?? 0); $lim = (int)($panel_inbound_limits[$pid] ?? defaultInboundUserLimit($pdo)); ?>
                                            <input type="number" name="inbound_limit[<?= $pid ?>]" value="<?= $lim ?>" min="0" class="form-control form-control-sm" style="width:80px" placeholder="<?= defaultInboundUserLimit($pdo) ?: '0=نامحدود' ?>" title="حداکثر کاربر کل روی این اینباند">
                                        </td>
                                        <td>
                                            <div class="btn-group btn-group-sm">
                                                <button type="button" class="btn btn-<?= $is_enabled ? 'warning' : 'success' ?>" 
                                                        onclick="toggleInbound(<?= $inbound['id'] ?>, <?= $is_enabled ? 'false' : 'true' ?>)" title="<?= $is_enabled ? 'غیرفعال کردن' : 'فعال کردن' ?>">
                                                    <i class="bi bi-power"></i>
                                                </button>
                                                <?php if ($inbound_traffic): ?>
                                                    <form method="POST" class="d-inline" onsubmit="return confirm('آیا از ریست ترافیک این اینباند مطمئنید؟')">
                                                        <input type="hidden" name="action" value="reset_inbound_traffic">
                                                        <input type="hidden" name="inbound_id" value="<?= $inbound['id'] ?>">
                                                        <button type="submit" class="btn btn-danger" title="ریست ترافیک">
                                                            <i class="bi bi-arrow-clockwise"></i>
                                                        </button>
                                                    </form>
                                                <?php endif; ?>
                                                <?php if ($clients_count > 0): ?>
                                                <button type="button" class="btn btn-info" data-bs-toggle="collapse" data-bs-target="#clients-<?= $inbound_id ?>" title="نمایش/مخفی کردن کلاینت‌ها">
                                                    <i class="bi bi-people"></i>
                                                </button>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                    </tr>
                                    
                                    <?php if ($clients_count > 0): ?>
                                    <tr class="collapse" id="clients-<?= $inbound_id ?>">
                                        <td colspan="9" class="p-0">
                                            <div class="p-3 bg-body-tertiary rounded-3">
                                                <h6 class="mb-3"> <i class="bi bi-person-circle"></i> لیست کلاینت‌های: <?= htmlspecialchars($inbound['remark'] ?? '') ?></h6>
                                                <div class="table-responsive">
                                                    <table class="table table-sm table-bordered table-hover align-middle">
                                                        <thead class="table-dark">
                                                            <tr>
                                                                <th>ایمیل</th>
                                                                <th>وضعیت</th>
                                                                <th>ترافیک مصرفی</th>
                                                                <th>تاریخ انقضا</th>
                                                                <th>عملیات</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            <?php foreach ($inbound['clients'] as $client): 
                                                                $client_traffic = null;
                                                                if (LIVE_USER_STATS) {
                                                                    try {
                                                                        $client_traffic = $xrayAPI->getClientStats($inbound['id'], $client['id']);
                                                                    } catch (Exception $e) { /* نادیده گرفتن خطا */ }
                                                                }
                                                                $is_client_enabled = $client['enable'] ?? true;
                                                                $expiry_time = ($client['expiryTime'] ?? 0) > 0 ? date('Y/m/d H:i', $client['expiryTime'] / 1000) : 'نامحدود';
                                                                $total_traffic = $client['totalGB'] ?? 0;
                                                                $used_traffic = $client_traffic ? ($client_traffic['up'] + $client_traffic['down']) : 0;
                                                            ?>
                                                            <tr>
                                                                <td><?= htmlspecialchars($client['email']) ?></td>
                                                                <td>
                                                                    <span class="badge bg-<?= $is_client_enabled ? 'success' : 'danger' ?>"><?= $is_client_enabled ? 'فعال' : 'غیرفعال' ?></span>
                                                                </td>
                                                                <td>
                                                                    <?php if($total_traffic > 0): ?>
                                                                        <div class="progress" style="height: 20px;">
                                                                            <div class="progress-bar" role="progressbar" style="width: <?= ($used_traffic / ($total_traffic * 1024*1024*1024)) * 100 ?>%;" aria-valuenow="<?= $used_traffic ?>" aria-valuemin="0" aria-valuemax="<?= $total_traffic * 1024*1024*1024 ?>">
                                                                                <?= formatBytes($used_traffic) ?> / <?= $total_traffic ?> GB
                                                                            </div>
                                                                        </div>
                                                                    <?php else: ?>
                                                                        <i class="bi bi-infinity"></i> نامحدود
                                                                    <?php endif; ?>
                                                                </td>
                                                                <td><?= $expiry_time ?></td>
                                                                <td>
                                                                    <div class="btn-group btn-group-sm">
                                                                        <button type="button" class="btn btn-<?= $is_client_enabled ? 'warning' : 'success' ?>" onclick="toggleClient(<?= $inbound['id'] ?>, '<?= $client['id'] ?>', <?= $is_client_enabled ? 'false' : 'true' ?>)" title="<?= $is_client_enabled ? 'غیرفعال' : 'فعال' ?> کردن">
                                                                            <i class="bi bi-power"></i>
                                                                        </button>
                                                                        <form method="POST" class="d-inline" onsubmit="return confirm('آیا از ریست ترافیک این کلاینت مطمئنید؟')">
                                                                            <input type="hidden" name="action" value="reset_client_traffic">
                                                                            <input type="hidden" name="inbound_id" value="<?= $inbound['id'] ?>">
                                                                            <input type="hidden" name="client_id" value="<?= $client['id'] ?>">
                                                                            <button type="submit" class="btn btn-danger" title="ریست ترافیک">
                                                                                <i class="bi bi-arrow-clockwise"></i>
                                                                            </button>
                                                                        </form>
                                                                    </div>
                                                                </td>
                                                            </tr>
                                                            <?php endforeach; ?>
                                                        </tbody>
                                                    </table>
                                                </div>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                        <button type="submit" class="btn btn-primary btn-sm mt-2"><i class="bi bi-check2"></i> ذخیره محدودیت اینباندها</button>
                    </form>
                <?php endif; ?>
            </div>
        </div>

<!-- Modal جزئیات Inbound -->
<div class="modal fade" id="inboundDetailsModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">جزئیات Inbound</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="inboundDetailsContent">
                <!-- محتوا از طریق JavaScript پر می‌شود -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">بستن</button>
            </div>
        </div>
    </div>
</div>

<script>
function toggleInbound(inboundId, enable) {
    const form = document.createElement('form');
    form.method = 'POST';
    form.innerHTML = `
        <input type="hidden" name="action" value="toggle_inbound">
        <input type="hidden" name="inbound_id" value="${inboundId}">
        <input type="hidden" name="enable" value="${enable ? '1' : '0'}">
    `;
    document.body.appendChild(form);
    form.submit();
}

function toggleClient(inboundId, clientId, enable) {
    const form = document.createElement('form');
    form.method = 'POST';
    form.innerHTML = `
        <input type="hidden" name="action" value="toggle_client">
        <input type="hidden" name="inbound_id" value="${inboundId}">
        <input type="hidden" name="client_id" value="${clientId}">
        <input type="hidden" name="enable" value="${enable ? '1' : '0'}">
    `;
    document.body.appendChild(form);
    form.submit();
}

function showInboundDetails(inbound) {
    const content = document.getElementById('inboundDetailsContent');
    content.innerHTML = `
        <div class="row">
            <div class="col-md-6">
                <p><strong>ID:</strong> ${inbound.id}</p>
                <p><strong>نام:</strong> ${inbound.remark || '-'}</p>
                <p><strong>پورت:</strong> ${inbound.port || '-'}</p>
                <p><strong>پروتکل:</strong> ${inbound.protocol || '-'}</p>
            </div>
            <div class="col-md-6">
                <p><strong>وضعیت:</strong> ${inbound.enable ? '<span class="badge bg-success">فعال</span>' : '<span class="badge bg-danger">غیرفعال</span>'}</p>
                <p><strong>Tag:</strong> ${inbound.tag || '-'}</p>
                <p><strong>تعداد کلاینت:</strong> ${inbound.clients ? inbound.clients.length : 0}</p>
            </div>
        </div>
        ${inbound.settings ? '<pre class="mt-3">' + JSON.stringify(JSON.parse(inbound.settings), null, 2) + '</pre>' : ''}
    `;
    new bootstrap.Modal(document.getElementById('inboundDetailsModal')).show();
}
</script>

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