<?php
session_start();
require_once '../config.php';

if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: ../admin_panel.php");
    exit;
}

$stmt = $pdo->prepare("SELECT * FROM admin WHERE id = ?");
$stmt->execute([$_SESSION['admin_id']]);
$admin = $stmt->fetch(PDO::FETCH_ASSOC);

// ==================== توابع دریافت اینباند مرزبان ====================
function get_marzban_token($url, $username, $password) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, rtrim($url, '/') . '/api/admin/token');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
        'username' => $username,
        'password' => $password
    ]));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/x-www-form-urlencoded',
        'Accept: application/json'
    ]);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($http_code == 200) {
        $data = json_decode($response, true);
        return $data['access_token'] ?? null;
    }
    return null;
}

function get_marzban_inbounds($url, $username, $password) {
    $token = get_marzban_token($url, $username, $password);
    if (!$token) {
        return ['error' => 'دریافت توکن ناموفق'];
    }
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, rtrim($url, '/') . '/api/inbounds');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Accept: application/json',
        'Authorization: Bearer ' . $token
    ]);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($http_code == 200) {
        $data = json_decode($response, true);
        $result = [];
        foreach ($data as $protocol => $inbounds) {
            foreach ($inbounds as $inbound) {
                $result[] = [
                    'tag' => $inbound['tag'],
                    'protocol' => $protocol,
                    'network' => $inbound['network'],
                    'port' => $inbound['port'],
                    'tls' => $inbound['tls']
                ];
            }
        }
        return ['success' => true, 'inbounds' => $result];
    }
    
    return ['error' => 'خطا در دریافت اینباندها'];
}
// ==================== پایان توابع ====================

// عملیات CRUD
if (isset($_POST['add_panel'])) {
    $panel_type = $_POST['panel_type'];
    $name = trim($_POST['name']);
    $url = trim($_POST['url']);
    $status = isset($_POST['status']) ? 1 : 0;
    
    $extra_traffic_enabled = isset($_POST['extra_traffic_enabled']) ? 1 : 0;
    $extra_traffic_price_per_gb = (float)$_POST['extra_traffic_price_per_gb'];
    $extra_traffic_min = (float)$_POST['extra_traffic_min'];
    $extra_traffic_max = (float)$_POST['extra_traffic_max'];
    
    $bulk_purchase_enabled = isset($_POST['bulk_purchase_enabled']) ? 1 : 0;
    $bulk_min_quantity = (int)$_POST['bulk_min_quantity'];
    $bulk_max_quantity = (int)$_POST['bulk_max_quantity'];
    
    $refund_enabled = isset($_POST['refund_enabled']) ? 1 : 0;
    $refund_min_remaining_gb = (float)$_POST['refund_min_remaining_gb'];
    $refund_min_remaining_days = (int)$_POST['refund_min_remaining_days'];
    
    $renewal_enabled = isset($_POST['renewal_enabled']) ? 1 : 0;
    
    // فیلدهای جدید خرید حجم دلخواه
    $custom_volume_enabled = isset($_POST['custom_volume_enabled']) ? 1 : 0;
    $custom_volume_price_per_gb = (float)$_POST['custom_volume_price_per_gb'];
    $custom_volume_min_gb = (float)$_POST['custom_volume_min_gb'];
    $custom_volume_max_gb = (float)$_POST['custom_volume_max_gb'];
    $custom_volume_price_per_day = (float)$_POST['custom_volume_price_per_day'];
    $custom_volume_min_days = (int)$_POST['custom_volume_min_days'];
    $custom_volume_max_days = (int)$_POST['custom_volume_max_days'];
    
    if ($panel_type == 'xui') {
        $api_token = trim($_POST['api_token'] ?? '');
        $inbound_id = (int)($_POST['inbound_id'] ?? 0);
        $sub_domain = trim($_POST['sub_domain'] ?? '');
        $sub_port = (int)($_POST['sub_port'] ?? 443);
        $sub_path = trim($_POST['sub_path'] ?? '');
        
        $stmt = $pdo->prepare("INSERT INTO panels (panel_type, name, url, api_token, inbound_id, sub_domain, sub_port, sub_path, status, extra_traffic_enabled, extra_traffic_price_per_gb, extra_traffic_min, extra_traffic_max, bulk_purchase_enabled, bulk_min_quantity, bulk_max_quantity, refund_enabled, refund_min_remaining_gb, refund_min_remaining_days, renewal_enabled, custom_volume_enabled, custom_volume_price_per_gb, custom_volume_min_gb, custom_volume_max_gb, custom_volume_price_per_day, custom_volume_min_days, custom_volume_max_days) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$panel_type, $name, $url, $api_token, $inbound_id, $sub_domain, $sub_port, $sub_path, $status, $extra_traffic_enabled, $extra_traffic_price_per_gb, $extra_traffic_min, $extra_traffic_max, $bulk_purchase_enabled, $bulk_min_quantity, $bulk_max_quantity, $refund_enabled, $refund_min_remaining_gb, $refund_min_remaining_days, $renewal_enabled, $custom_volume_enabled, $custom_volume_price_per_gb, $custom_volume_min_gb, $custom_volume_max_gb, $custom_volume_price_per_day, $custom_volume_min_days, $custom_volume_max_days]);
        
    } else {
        $marzban_username = trim($_POST['marzban_username']);
        $marzban_password = trim($_POST['marzban_password']);
        $selected_inbounds = isset($_POST['selected_inbounds']) ? json_encode($_POST['selected_inbounds']) : null;
        
        $stmt = $pdo->prepare("INSERT INTO panels (panel_type, name, url, marzban_username, marzban_password, selected_inbounds, status, extra_traffic_enabled, extra_traffic_price_per_gb, extra_traffic_min, extra_traffic_max, bulk_purchase_enabled, bulk_min_quantity, bulk_max_quantity, refund_enabled, refund_min_remaining_gb, refund_min_remaining_days, renewal_enabled, custom_volume_enabled, custom_volume_price_per_gb, custom_volume_min_gb, custom_volume_max_gb, custom_volume_price_per_day, custom_volume_min_days, custom_volume_max_days) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$panel_type, $name, $url, $marzban_username, $marzban_password, $selected_inbounds, $status, $extra_traffic_enabled, $extra_traffic_price_per_gb, $extra_traffic_min, $extra_traffic_max, $bulk_purchase_enabled, $bulk_min_quantity, $bulk_max_quantity, $refund_enabled, $refund_min_remaining_gb, $refund_min_remaining_days, $renewal_enabled, $custom_volume_enabled, $custom_volume_price_per_gb, $custom_volume_min_gb, $custom_volume_max_gb, $custom_volume_price_per_day, $custom_volume_min_days, $custom_volume_max_days]);
    }
    
    header("Location: panels.php");
    exit;
}

if (isset($_POST['edit_panel'])) {
    $id = (int)$_POST['id'];
    $panel_type = $_POST['panel_type'];
    $name = trim($_POST['name']);
    $url = trim($_POST['url']);
    $status = isset($_POST['status']) ? 1 : 0;
    
    $extra_traffic_enabled = isset($_POST['extra_traffic_enabled']) ? 1 : 0;
    $extra_traffic_price_per_gb = (float)$_POST['extra_traffic_price_per_gb'];
    $extra_traffic_min = (float)$_POST['extra_traffic_min'];
    $extra_traffic_max = (float)$_POST['extra_traffic_max'];
    
    $bulk_purchase_enabled = isset($_POST['bulk_purchase_enabled']) ? 1 : 0;
    $bulk_min_quantity = (int)$_POST['bulk_min_quantity'];
    $bulk_max_quantity = (int)$_POST['bulk_max_quantity'];
    
    $refund_enabled = isset($_POST['refund_enabled']) ? 1 : 0;
    $refund_min_remaining_gb = (float)$_POST['refund_min_remaining_gb'];
    $refund_min_remaining_days = (int)$_POST['refund_min_remaining_days'];
    
    $renewal_enabled = isset($_POST['renewal_enabled']) ? 1 : 0;
    
    // فیلدهای جدید خرید حجم دلخواه
    $custom_volume_enabled = isset($_POST['custom_volume_enabled']) ? 1 : 0;
    $custom_volume_price_per_gb = (float)$_POST['custom_volume_price_per_gb'];
    $custom_volume_min_gb = (float)$_POST['custom_volume_min_gb'];
    $custom_volume_max_gb = (float)$_POST['custom_volume_max_gb'];
    $custom_volume_price_per_day = (float)$_POST['custom_volume_price_per_day'];
    $custom_volume_min_days = (int)$_POST['custom_volume_min_days'];
    $custom_volume_max_days = (int)$_POST['custom_volume_max_days'];
    
    if ($panel_type == 'xui') {
        $api_token = trim($_POST['api_token'] ?? '');
        $inbound_id = (int)($_POST['inbound_id'] ?? 0);
        $sub_domain = trim($_POST['sub_domain'] ?? '');
        $sub_port = (int)($_POST['sub_port'] ?? 443);
        $sub_path = trim($_POST['sub_path'] ?? '');
        
        $stmt = $pdo->prepare("UPDATE panels SET panel_type=?, name=?, url=?, api_token=?, inbound_id=?, sub_domain=?, sub_port=?, sub_path=?, status=?, extra_traffic_enabled=?, extra_traffic_price_per_gb=?, extra_traffic_min=?, extra_traffic_max=?, bulk_purchase_enabled=?, bulk_min_quantity=?, bulk_max_quantity=?, refund_enabled=?, refund_min_remaining_gb=?, refund_min_remaining_days=?, renewal_enabled=?, custom_volume_enabled=?, custom_volume_price_per_gb=?, custom_volume_min_gb=?, custom_volume_max_gb=?, custom_volume_price_per_day=?, custom_volume_min_days=?, custom_volume_max_days=? WHERE id=?");
        $stmt->execute([$panel_type, $name, $url, $api_token, $inbound_id, $sub_domain, $sub_port, $sub_path, $status, $extra_traffic_enabled, $extra_traffic_price_per_gb, $extra_traffic_min, $extra_traffic_max, $bulk_purchase_enabled, $bulk_min_quantity, $bulk_max_quantity, $refund_enabled, $refund_min_remaining_gb, $refund_min_remaining_days, $renewal_enabled, $custom_volume_enabled, $custom_volume_price_per_gb, $custom_volume_min_gb, $custom_volume_max_gb, $custom_volume_price_per_day, $custom_volume_min_days, $custom_volume_max_days, $id]);
        
    } else {
        $marzban_username = trim($_POST['marzban_username']);
        $marzban_password = trim($_POST['marzban_password']);
        $selected_inbounds = isset($_POST['selected_inbounds']) ? json_encode($_POST['selected_inbounds']) : null;
        
        $stmt = $pdo->prepare("UPDATE panels SET panel_type=?, name=?, url=?, marzban_username=?, marzban_password=?, selected_inbounds=?, status=?, extra_traffic_enabled=?, extra_traffic_price_per_gb=?, extra_traffic_min=?, extra_traffic_max=?, bulk_purchase_enabled=?, bulk_min_quantity=?, bulk_max_quantity=?, refund_enabled=?, refund_min_remaining_gb=?, refund_min_remaining_days=?, renewal_enabled=?, custom_volume_enabled=?, custom_volume_price_per_gb=?, custom_volume_min_gb=?, custom_volume_max_gb=?, custom_volume_price_per_day=?, custom_volume_min_days=?, custom_volume_max_days=? WHERE id=?");
        $stmt->execute([$panel_type, $name, $url, $marzban_username, $marzban_password, $selected_inbounds, $status, $extra_traffic_enabled, $extra_traffic_price_per_gb, $extra_traffic_min, $extra_traffic_max, $bulk_purchase_enabled, $bulk_min_quantity, $bulk_max_quantity, $refund_enabled, $refund_min_remaining_gb, $refund_min_remaining_days, $renewal_enabled, $custom_volume_enabled, $custom_volume_price_per_gb, $custom_volume_min_gb, $custom_volume_max_gb, $custom_volume_price_per_day, $custom_volume_min_days, $custom_volume_max_days, $id]);
    }
    
    header("Location: panels.php");
    exit;
}

if (isset($_GET['delete_panel'])) {
    $id = (int)$_GET['delete_panel'];
    $pdo->prepare("DELETE FROM panels WHERE id = ?")->execute([$id]);
    header("Location: panels.php");
    exit;
}

if (isset($_GET['get_panel_json'])) {
    $stmt = $pdo->prepare("SELECT * FROM panels WHERE id = ?");
    $stmt->execute([$_GET['get_panel_json']]);
    $panel = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($panel['panel_type'] == 'marzban' && $panel['selected_inbounds']) {
        $panel['selected_inbounds'] = json_decode($panel['selected_inbounds'], true);
    }
    
    header('Content-Type: application/json');
    echo json_encode($panel);
    exit;
}

if (isset($_POST['fetch_inbounds'])) {
    $url = $_POST['url'];
    $username = $_POST['username'];
    $password = $_POST['password'];
    
    $result = get_marzban_inbounds($url, $username, $password);
    
    header('Content-Type: application/json');
    echo json_encode($result);
    exit;
}

$panels = $pdo->query("SELECT * FROM panels ORDER BY id DESC")->fetchAll();
?>
<!DOCTYPE html>
<html dir="rtl" lang="fa">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>مدیریت پنل‌ها</title>
    <style>
        :root {
            --glass-bg: rgba(255,255,255,0.75);
            --blur: blur(12px);
            --glass-border: rgba(255,255,255,0.5);
            --glass-border-mid: rgba(255,255,255,0.4);
            --glass-border-hi: rgba(255,255,255,0.7);
            --glass-inset: rgba(255,255,255,0.35);
            --glass-top-shine: rgba(255,255,255,0.6);
            --shadow-sm: 0 4px 12px rgba(0,0,0,0.05);
            --shadow-md: 0 8px 24px rgba(0,0,0,0.08);
            --r-sm: 8px;
            --r-md: 12px;
            --r-lg: 16px;
            --r-xl: 20px;
            --r-pill: 40px;
            --t-smooth: all 0.2s ease;
            --text-1: #1f2937;
            --text-2: #374151;
            --text-3: #6b7280;
        }

        * { margin: 0; padding: 0; box-sizing: border-box; }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #e0e7ff 0%, #f3e8ff 100%);
            min-height: 100vh;
            padding: 24px;
        }
        
        .page-wrap { max-width: 1440px; margin: 0 auto; position: relative; z-index: 1; }
        
        .admin-header {
            background: var(--glass-bg);
            backdrop-filter: var(--blur);
            border: 1px solid var(--glass-border-mid);
            border-radius: var(--r-lg);
            padding: 16px 24px;
            margin-bottom: 24px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: inset 0 1.5px 0 var(--glass-top-shine), var(--shadow-sm);
        }
        
        .brand {
            display: flex;
            align-items: center;
            gap: 12px;
        }
        
        .brand-logo { height: 40px; }
        .brand-name { font-size: 18px; font-weight: 700; color: var(--text-1); }
        
        .admin-info {
            display: flex;
            gap: 12px;
            align-items: center;
        }
        
        .admin-welcome {
            font-size: 13px;
            color: var(--text-2);
            background: rgba(0,0,0,0.05);
            padding: 6px 12px;
            border-radius: 20px;
        }
        
        .logout-btn {
            padding: 8px 16px;
            border-radius: var(--r-sm);
            background: rgba(239,68,68,0.12);
            border: 1px solid rgba(239,68,68,0.3);
            color: #dc2626;
            text-decoration: none;
            font-size: 13px;
            transition: var(--t-smooth);
        }
        
        .logout-btn:hover {
            background: rgba(239,68,68,0.25);
        }
        
        .table-card {
            background: var(--glass-bg);
            backdrop-filter: var(--blur);
            border: 1px solid var(--glass-border-mid);
            border-radius: var(--r-xl);
            overflow: hidden;
            box-shadow: inset 0 1.5px 0 var(--glass-top-shine), var(--shadow-md);
        }
        
        .table-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 18px 24px;
            border-bottom: 1px solid rgba(255,255,255,0.4);
            background: rgba(255,255,255,0.15);
        }
        
        .table-title {
            font-size: 16px;
            font-weight: 700;
            color: var(--text-1);
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .add-btn {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 8px 20px;
            background: rgba(16,185,129,0.15);
            border: 1px solid rgba(16,185,129,0.3);
            border-radius: var(--r-pill);
            color: #065f46;
            font-weight: 600;
            font-size: 13px;
            cursor: pointer;
            transition: var(--t-smooth);
        }
        
        .add-btn:hover {
            background: rgba(16,185,129,0.25);
            transform: translateY(-1px);
        }
        
        .table-scroll { overflow-x: auto; }
        
        .data-table {
            width: 100%;
            border-collapse: collapse;
            min-width: 1300px;
        }
        
        .data-table thead th {
            padding: 12px 14px;
            text-align: center;
            font-size: 11px;
            font-weight: 600;
            color: var(--text-3);
            background: rgba(255,255,255,0.18);
            border-bottom: 1px solid rgba(255,255,255,0.35);
        }
        
        .data-table tbody td {
            padding: 14px;
            text-align: center;
            border-bottom: 1px solid rgba(255,255,255,0.25);
            font-size: 13px;
            color: var(--text-2);
        }
        
        .panel-type-badge {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 700;
        }
        
        .badge-xui { background: rgba(59,130,246,0.15); color: #1e40af; border: 1px solid rgba(59,130,246,0.3); }
        .badge-marzban { background: rgba(139,92,246,0.15); color: #5b21b6; border: 1px solid rgba(139,92,246,0.3); }
        
        .badge-active {
            display: inline-block;
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 10px;
            font-weight: 700;
            background: rgba(16,185,129,0.15);
            color: #065f46;
            border: 1px solid rgba(16,185,129,0.3);
        }
        
        .badge-inactive {
            display: inline-block;
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 10px;
            font-weight: 700;
            background: rgba(107,114,128,0.15);
            color: #4b5563;
            border: 1px solid rgba(107,114,128,0.3);
        }
        
        .small-text {
            display: block;
            font-size: 10px;
            margin-top: 4px;
            color: var(--text-3);
        }
        
        .tbl-btn {
            display: inline-flex;
            align-items: center;
            gap: 5px;
            padding: 6px 13px;
            border-radius: var(--r-sm);
            font-size: 12px;
            font-weight: 600;
            border: 1px solid;
            cursor: pointer;
            transition: var(--t-smooth);
            background: transparent;
            text-decoration: none;
        }
        
        .tbl-btn-edit {
            background: rgba(59,130,246,0.12);
            border-color: rgba(59,130,246,0.3);
            color: #1e40af;
        }
        
        .tbl-btn-delete {
            background: rgba(239,68,68,0.12);
            border-color: rgba(239,68,68,0.3);
            color: #7f1d1d;
        }
        
        .action-buttons { display: flex; gap: 6px; justify-content: center; }
        
        /* مودال */
        .modal-overlay {
            display: none;
            position: fixed;
            inset: 0;
            background: rgba(80,60,160,0.22);
            backdrop-filter: blur(22px);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }
        
        .modal-overlay.active { display: flex; }
        
        .modal-sheet {
            background: rgba(255,255,255,0.95);
            backdrop-filter: blur(20px);
            border: 1px solid var(--glass-border-hi);
            border-radius: var(--r-xl);
            width: 100%;
            max-width: 760px;
            max-height: 90vh;
            overflow-y: auto;
            box-shadow: 0 25px 50px -12px rgba(0,0,0,0.25);
        }
        
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20px 24px;
            border-bottom: 1px solid rgba(0,0,0,0.1);
        }
        
        .modal-header h3 {
            font-size: 18px;
            margin: 0;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .close-modal {
            background: rgba(0,0,0,0.08);
            border: none;
            border-radius: 50%;
            width: 32px;
            height: 32px;
            cursor: pointer;
            font-size: 18px;
            transition: var(--t-smooth);
        }
        
        .close-modal:hover { background: rgba(0,0,0,0.15); }
        
        .form-group {
            margin-bottom: 18px;
            padding: 0 24px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            font-size: 13px;
            color: var(--text-2);
        }
        
        .form-group input, .form-group select {
            width: 100%;
            padding: 10px 12px;
            border-radius: var(--r-sm);
            border: 1px solid #e5e7eb;
            font-size: 13px;
            transition: all 0.2s;
            background: white;
        }
        
        .form-group input:focus, .form-group select:focus {
            outline: none;
            border-color: #8b5cf6;
            box-shadow: 0 0 0 3px rgba(139,92,246,0.1);
        }
        
        .checkbox-group {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 0 24px;
            margin-bottom: 16px;
        }
        
        .checkbox-group input { width: auto; margin: 0; }
        .checkbox-group label { margin: 0; cursor: pointer; }
        
        .extra-traffic-section, .bulk-purchase-section, .refund-section, .renewal-section, .custom-volume-section {
            background: rgba(255,255,255,0.5);
            border-radius: var(--r-md);
            margin: 16px 24px;
            padding: 16px;
            border: 1px solid var(--glass-border);
        }
        
        .inbounds-list {
            background: rgba(243,244,246,0.5);
            border-radius: var(--r-sm);
            padding: 12px;
            max-height: 250px;
            overflow-y: auto;
            border: 1px solid var(--glass-border);
        }
        
        .inbound-item {
            padding: 10px;
            margin: 5px 0;
            background: white;
            border-radius: var(--r-sm);
            border: 1px solid #e5e7eb;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .inbound-item input { margin: 0; width: auto; }
        
        .fetch-btn {
            background: rgba(16,185,129,0.15);
            border: 1px solid rgba(16,185,129,0.3);
            color: #065f46;
            padding: 8px 16px;
            border-radius: var(--r-pill);
            cursor: pointer;
            margin: 0 24px 16px 24px;
            font-weight: 600;
            transition: var(--t-smooth);
        }
        
        .fetch-btn:hover {
            background: rgba(16,185,129,0.25);
        }
        
        .info-text {
            font-size: 11px;
            color: var(--text-3);
            margin-top: 4px;
        }
        
        .form-actions {
            padding: 16px 24px;
            display: flex;
            gap: 10px;
            border-top: 1px solid rgba(0,0,0,0.1);
            margin-top: 10px;
        }
        
        .btn-submit {
            background: rgba(139,92,246,0.15);
            border: 1px solid rgba(139,92,246,0.3);
            color: #5b21b6;
            padding: 8px 24px;
            border-radius: var(--r-pill);
            cursor: pointer;
            font-weight: 600;
        }
        
        .btn-cancel {
            background: rgba(107,114,128,0.15);
            border: 1px solid rgba(107,114,128,0.3);
            color: #4b5563;
            padding: 8px 24px;
            border-radius: var(--r-pill);
            cursor: pointer;
            font-weight: 600;
        }
        
        svg.icon {
            width: 18px;
            height: 18px;
            stroke-width: 1.8;
        }
        
        code {
            background: rgba(0,0,0,0.05);
            padding: 2px 6px;
            border-radius: 4px;
            font-size: 11px;
        }
        
        .grid-2 {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 12px;
            padding: 0 24px;
        }
        
        .grid-2 .form-group {
            padding: 0;
        }
    </style>
</head>
<body>
<div class="page-wrap">
    
    <div class="admin-header">
        <div class="brand">
            <img src="../picture/rahgozar.png" alt="لوگو" class="brand-logo">
            <span class="brand-name">مدیریت پنل‌ها</span>
        </div>
        <div class="admin-info">
            <span class="admin-welcome">خوش آمدید، <strong><?= htmlspecialchars($admin['full_name'] ?? $admin['username']) ?></strong></span>
            <a href="../admin_panel.php" class="logout-btn">بازگشت</a>
            <a href="../admin_panel.php?logout=1" class="logout-btn">خروج</a>
        </div>
    </div>
    
    <div class="table-card">
        <div class="table-header">
            <div class="table-title">
                <svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
                    <rect x="2" y="7" width="20" height="14" rx="2"/>
                    <line x1="16" y1="21" x2="16" y2="15"/>
                    <line x1="8" y1="21" x2="8" y2="15"/>
                    <line x1="12" y1="21" x2="12" y2="15"/>
                    <line x1="12" y1="3" x2="12" y2="7"/>
                    <line x1="5" y1="3" x2="19" y2="3"/>
                </svg>
                لیست پنل‌ها
            </div>
            <button class="add-btn" onclick="openAddPanelModal()">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <line x1="12" y1="5" x2="12" y2="19"/>
                    <line x1="5" y1="12" x2="19" y2="12"/>
                </svg>
                افزودن پنل
            </button>
        </div>
        <div class="table-scroll">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>آیدی</th>
                        <th>نوع</th>
                        <th>نام</th>
                        <th>آدرس</th>
                        <th>ترافیک اضافه</th>
                        <th>خرید عمده</th>
                        <th>خرید حجم دلخواه</th>
                        <th>ریفاند</th>
                        <th>تمدید</th>
                        <th>وضعیت</th>
                        <th>عملیات</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($panels as $panel): ?>
                    <tr>
                        <td><?= $panel['id'] ?></td>
                        <td>
                            <span class="panel-type-badge <?= $panel['panel_type'] == 'xui' ? 'badge-xui' : 'badge-marzban' ?>">
                                <?= $panel['panel_type'] == 'xui' ? '⚡ X-UI' : '🟣 مرزبان' ?>
                            </span>
                         </td>
                        <td><?= htmlspecialchars($panel['name']) ?></td>
                        <td><code><?= htmlspecialchars($panel['url']) ?></code></td>
                        <td>
                            <?php if($panel['extra_traffic_enabled']): ?>
                                <span class="badge-active">فعال</span>
                                <span class="small-text"><?= number_format($panel['extra_traffic_price_per_gb']) ?> تومان/GB</span>
                            <?php else: ?>
                                <span class="badge-inactive">غیرفعال</span>
                            <?php endif; ?>
                         </td>
                        <td>
                            <?php if($panel['bulk_purchase_enabled']): ?>
                                <span class="badge-active">فعال</span>
                                <span class="small-text"><?= $panel['bulk_min_quantity'] ?>-<?= $panel['bulk_max_quantity'] ?></span>
                            <?php else: ?>
                                <span class="badge-inactive">غیرفعال</span>
                            <?php endif; ?>
                         </td>
                        <td>
                            <?php if($panel['custom_volume_enabled']): ?>
                                <span class="badge-active">فعال</span>
                                <span class="small-text"><?= number_format($panel['custom_volume_price_per_gb']) ?> تومان/GB<br><?= number_format($panel['custom_volume_price_per_day']) ?> تومان/روز</span>
                            <?php else: ?>
                                <span class="badge-inactive">غیرفعال</span>
                            <?php endif; ?>
                         </td>
                        <td>
                            <span class="<?= $panel['refund_enabled'] ? 'badge-active' : 'badge-inactive' ?>">
                                <?= $panel['refund_enabled'] ? 'فعال' : 'غیرفعال' ?>
                            </span>
                         </td>
                        <td>
                            <span class="<?= $panel['renewal_enabled'] ? 'badge-active' : 'badge-inactive' ?>">
                                <?= $panel['renewal_enabled'] ? 'فعال' : 'غیرفعال' ?>
                            </span>
                         </td>
                        <td>
                            <span class="<?= $panel['status'] ? 'badge-active' : 'badge-inactive' ?>">
                                <?= $panel['status'] ? 'فعال' : 'غیرفعال' ?>
                            </span>
                         </td>
                        <td class="action-buttons">
                            <button class="tbl-btn tbl-btn-edit" onclick="openEditPanelModal(<?= $panel['id'] ?>)">ویرایش</button>
                            <a href="?delete_panel=<?= $panel['id'] ?>" class="tbl-btn tbl-btn-delete" onclick="return confirm('آیا از حذف این پنل مطمئن هستید؟')">حذف</a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- مودال -->
<div id="panelModal" class="modal-overlay">
    <div class="modal-sheet">
        <div class="modal-header">
            <h3 id="panelModalTitle">افزودن پنل</h3>
            <button class="close-modal" onclick="closeModal()">✕</button>
        </div>
        <form id="panelForm" method="POST">
            <input type="hidden" name="id" id="panel_id">
            
            <div class="form-group">
                <label>نوع پنل</label>
                <select name="panel_type" id="panel_type" onchange="togglePanelType()" required>
                    <option value="xui">X-UI / 3x-UI (سنایی)</option>
                    <option value="marzban">مرزبان (Marzban)</option>
                </select>
            </div>
            
            <div class="form-group">
                <label>نام پنل</label>
                <input type="text" name="name" id="panel_name" required placeholder="مثال: پنل اصلی">
            </div>
            
            <div class="form-group">
                <label>آدرس پنل</label>
                <input type="url" name="url" id="panel_url" required placeholder="https://example.com:port">
            </div>
            
            <!-- بخش X-UI -->
            <div id="xui_fields">
                <div class="form-group">
                    <label>API Token</label>
                    <input type="text" name="api_token" id="panel_api_token" placeholder="توکن اتصال به API">
                </div>
                <div class="form-group">
                    <label>Inbound ID</label>
                    <input type="number" name="inbound_id" id="panel_inbound_id" placeholder="شناسه اینباند">
                </div>
                <div class="form-group">
                    <label>دامنه ساب</label>
                    <input type="text" name="sub_domain" id="panel_sub_domain" placeholder="sub.example.com">
                </div>
                <div class="form-group">
                    <label>پورت ساب</label>
                    <input type="number" name="sub_port" id="panel_sub_port" value="443">
                </div>
                <div class="form-group">
                    <label>مسیر ساب</label>
                    <input type="text" name="sub_path" id="panel_sub_path" placeholder="/sub/">
                </div>
            </div>
            
            <!-- بخش مرزبان -->
            <div id="marzban_fields" style="display: none;">
                <div class="form-group">
                    <label>نام کاربری پنل</label>
                    <input type="text" name="marzban_username" id="marzban_username" placeholder="نام کاربری ادمین">
                </div>
                <div class="form-group">
                    <label>رمز عبور پنل</label>
                    <input type="password" name="marzban_password" id="marzban_password" placeholder="رمز عبور ادمین">
                </div>
                <button type="button" class="fetch-btn" onclick="fetchInbounds()">📡 دریافت اینباندها</button>
                <div class="form-group">
                    <label>انتخاب اینباندها</label>
                    <div id="inbounds_container" class="inbounds-list">
                        <div class="info-text">⚠️ روی دکمه دریافت کلیک کنید</div>
                    </div>
                </div>
            </div>
            
            <!-- بخش ترافیک اضافه -->
            <div class="extra-traffic-section">
                <div class="checkbox-group">
                    <input type="checkbox" name="extra_traffic_enabled" id="extra_traffic_enabled" value="1" onchange="toggleExtraTrafficFields()">
                    <label>فعالسازی خرید ترافیک اضافه</label>
                </div>
                <div id="extra_traffic_fields" style="display: none; margin-top: 12px;">
                    <div class="form-group" style="padding: 0; margin-bottom: 12px;">
                        <label>قیمت هر گیگابایت (تومان)</label>
                        <input type="number" step="any" name="extra_traffic_price_per_gb" value="0">
                    </div>
                    <div class="form-group" style="padding: 0; margin-bottom: 12px;">
                        <label>حداقل خرید (گیگابایت)</label>
                        <input type="number" step="any" name="extra_traffic_min" value="1">
                    </div>
                    <div class="form-group" style="padding: 0;">
                        <label>حداکثر خرید (گیگابایت)</label>
                        <input type="number" step="any" name="extra_traffic_max" value="10">
                    </div>
                </div>
            </div>
            
            <!-- بخش خرید عمده -->
            <div class="bulk-purchase-section">
                <div class="checkbox-group">
                    <input type="checkbox" name="bulk_purchase_enabled" id="bulk_purchase_enabled" value="1" onchange="toggleBulkPurchaseFields()">
                    <label>فعالسازی خرید عمده</label>
                </div>
                <div id="bulk_purchase_fields" style="display: none; margin-top: 12px;">
                    <div class="form-group" style="padding: 0; margin-bottom: 12px;">
                        <label>حداقل تعداد</label>
                        <input type="number" name="bulk_min_quantity" value="1">
                    </div>
                    <div class="form-group" style="padding: 0;">
                        <label>حداکثر تعداد</label>
                        <input type="number" name="bulk_max_quantity" value="10">
                    </div>
                </div>
            </div>
            
            <!-- بخش خرید حجم دلخواه (جدید) -->
            <div class="custom-volume-section">
                <div class="checkbox-group">
                    <input type="checkbox" name="custom_volume_enabled" id="custom_volume_enabled" value="1" onchange="toggleCustomVolumeFields()">
                    <label>✅ فعالسازی خرید حجم دلخواه</label>
                </div>
                <div id="custom_volume_fields" style="display: none; margin-top: 12px;">
                    <div class="grid-2">
                        <div class="form-group" style="padding: 0;">
                            <label>💰 قیمت هر گیگابایت (تومان)</label>
                            <input type="number" step="any" name="custom_volume_price_per_gb" id="custom_volume_price_per_gb" value="0" placeholder="مثال: 5000">
                        </div>
                        <div class="form-group" style="padding: 0;">
                            <label>📊 حداقل خرید حجم (گیگابایت)</label>
                            <input type="number" step="any" name="custom_volume_min_gb" id="custom_volume_min_gb" value="1" placeholder="مثال: 1">
                        </div>
                        <div class="form-group" style="padding: 0;">
                            <label>📊 حداکثر خرید حجم (گیگابایت)</label>
                            <input type="number" step="any" name="custom_volume_max_gb" id="custom_volume_max_gb" value="100" placeholder="مثال: 100">
                        </div>
                        <div class="form-group" style="padding: 0;">
                            <label>⏰ قیمت هر روز تایم (تومان)</label>
                            <input type="number" step="any" name="custom_volume_price_per_day" id="custom_volume_price_per_day" value="0" placeholder="مثال: 2000">
                        </div>
                        <div class="form-group" style="padding: 0;">
                            <label>📅 حداقل تایم (روز)</label>
                            <input type="number" name="custom_volume_min_days" id="custom_volume_min_days" value="1" placeholder="مثال: 1">
                        </div>
                        <div class="form-group" style="padding: 0;">
                            <label>📅 حداکثر تایم (روز)</label>
                            <input type="number" name="custom_volume_max_days" id="custom_volume_max_days" value="30" placeholder="مثال: 30">
                        </div>
                    </div>
                    <div class="info-text" style="margin-top: 8px;">💡 کاربر می‌تواند حجم و تایم مورد نظر خود را به صورت دلخواه انتخاب کند</div>
                </div>
            </div>
            
            <!-- بخش ریفاند -->
            <div class="refund-section">
                <div class="checkbox-group">
                    <input type="checkbox" name="refund_enabled" id="refund_enabled" value="1" onchange="toggleRefundFields()">
                    <label>فعالسازی ریفاند (بازگشت وجه)</label>
                </div>
                <div id="refund_fields" style="display: none; margin-top: 12px;">
                    <div class="form-group" style="padding: 0; margin-bottom: 12px;">
                        <label>حداقل حجم باقیمانده (گیگابایت)</label>
                        <input type="number" step="0.1" name="refund_min_remaining_gb" value="1">
                    </div>
                    <div class="form-group" style="padding: 0;">
                        <label>حداقل روز باقیمانده</label>
                        <input type="number" name="refund_min_remaining_days" value="0">
                        <div class="info-text">0 = نامحدود</div>
                    </div>
                </div>
            </div>
            
            <!-- بخش تمدید -->
            <div class="renewal-section">
                <div class="checkbox-group">
                    <input type="checkbox" name="renewal_enabled" id="renewal_enabled" value="1">
                    <label>فعالسازی تمدید سرویس</label>
                </div>
            </div>
            
            <div class="checkbox-group">
                <input type="checkbox" name="status" id="panel_status" value="1" checked>
                <label>فعال بودن پنل</label>
            </div>
            
            <div class="form-actions">
                <button type="submit" class="btn-submit" id="submitBtn">افزودن</button>
                <button type="button" class="btn-cancel" onclick="closeModal()">انصراف</button>
            </div>
        </form>
    </div>
</div>

<script>
function closeModal() { 
    document.getElementById('panelModal').classList.remove('active'); 
}

function openModal() {
    document.getElementById('panelModal').classList.add('active');
}

function togglePanelType() {
    const type = document.getElementById('panel_type').value;
    if (type === 'xui') {
        document.getElementById('xui_fields').style.display = 'block';
        document.getElementById('marzban_fields').style.display = 'none';
    } else {
        document.getElementById('xui_fields').style.display = 'none';
        document.getElementById('marzban_fields').style.display = 'block';
    }
}

function toggleExtraTrafficFields() {
    const enabled = document.getElementById('extra_traffic_enabled').checked;
    document.getElementById('extra_traffic_fields').style.display = enabled ? 'block' : 'none';
}

function toggleBulkPurchaseFields() {
    const enabled = document.getElementById('bulk_purchase_enabled').checked;
    document.getElementById('bulk_purchase_fields').style.display = enabled ? 'block' : 'none';
}

function toggleRefundFields() {
    const enabled = document.getElementById('refund_enabled').checked;
    document.getElementById('refund_fields').style.display = enabled ? 'block' : 'none';
}

function toggleCustomVolumeFields() {
    const enabled = document.getElementById('custom_volume_enabled').checked;
    document.getElementById('custom_volume_fields').style.display = enabled ? 'block' : 'none';
}

function fetchInbounds() {
    const url = document.getElementById('panel_url').value;
    const username = document.getElementById('marzban_username').value;
    const password = document.getElementById('marzban_password').value;
    
    if (!url || !username || !password) {
        alert('لطفاً آدرس، نام کاربری و رمز عبور را وارد کنید');
        return;
    }
    
    const container = document.getElementById('inbounds_container');
    container.innerHTML = '<div class="info-text">⏳ در حال دریافت...</div>';
    
    fetch('', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams({
            'fetch_inbounds': '1',
            'url': url,
            'username': username,
            'password': password
        })
    })
    .then(r => r.json())
    .then(result => {
        if (result.success && result.inbounds.length > 0) {
            container.innerHTML = '<div class="info-text">✅ ' + result.inbounds.length + ' اینباند یافت شد:</div>';
            result.inbounds.forEach(inbound => {
                const div = document.createElement('div');
                div.className = 'inbound-item';
                div.innerHTML = `
                    <input type="checkbox" name="selected_inbounds[]" value="${inbound.tag.replace(/"/g, '&quot;')}" id="inb_${inbound.tag.replace(/[^a-zA-Z0-9]/g, '_')}">
                    <label for="inb_${inbound.tag.replace(/[^a-zA-Z0-9]/g, '_')}">
                        <strong>${inbound.tag}</strong>
                        <small> | ${inbound.protocol} | ${inbound.network} | پورت: ${inbound.port}</small>
                    </label>
                `;
                container.appendChild(div);
            });
        } else {
            container.innerHTML = '<div class="info-text" style="color:#dc2626;">❌ خطا: ' + (result.error || 'اتصال ناموفق') + '</div>';
        }
    })
    .catch(error => {
        container.innerHTML = '<div class="info-text" style="color:#dc2626;">❌ خطا در ارتباط با سرور</div>';
    });
}

function openAddPanelModal() {
    document.getElementById('panelModalTitle').innerHTML = '➕ افزودن پنل';
    document.getElementById('panelForm').reset();
    document.getElementById('panel_status').checked = true;
    document.getElementById('panel_type').value = 'xui';
    document.getElementById('submitBtn').innerHTML = 'افزودن';
    togglePanelType();
    toggleExtraTrafficFields();
    toggleBulkPurchaseFields();
    toggleRefundFields();
    toggleCustomVolumeFields();
    
    let oldInput = document.querySelector('#panelForm input[name="add_panel"], #panelForm input[name="edit_panel"]');
    if (oldInput) oldInput.remove();
    let input = document.createElement('input');
    input.type = 'hidden'; 
    input.name = 'add_panel'; 
    input.value = '1';
    document.getElementById('panelForm').appendChild(input);
    openModal();
}

function openEditPanelModal(id) {
    fetch('?get_panel_json=' + id)
        .then(r => r.json())
        .then(panel => {
            document.getElementById('panelModalTitle').innerHTML = '✏️ ویرایش پنل';
            document.getElementById('panel_id').value = panel.id;
            document.getElementById('panel_type').value = panel.panel_type;
            document.getElementById('panel_name').value = panel.name;
            document.getElementById('panel_url').value = panel.url;
            document.getElementById('panel_status').checked = (panel.status == 1);
            document.getElementById('submitBtn').innerHTML = 'ویرایش';
            
            document.getElementById('extra_traffic_enabled').checked = (panel.extra_traffic_enabled == 1);
            document.querySelector('input[name="extra_traffic_price_per_gb"]').value = panel.extra_traffic_price_per_gb || 0;
            document.querySelector('input[name="extra_traffic_min"]').value = panel.extra_traffic_min || 1;
            document.querySelector('input[name="extra_traffic_max"]').value = panel.extra_traffic_max || 10;
            document.getElementById('bulk_purchase_enabled').checked = (panel.bulk_purchase_enabled == 1);
            document.querySelector('input[name="bulk_min_quantity"]').value = panel.bulk_min_quantity || 1;
            document.querySelector('input[name="bulk_max_quantity"]').value = panel.bulk_max_quantity || 10;
            document.getElementById('refund_enabled').checked = (panel.refund_enabled == 1);
            document.querySelector('input[name="refund_min_remaining_gb"]').value = panel.refund_min_remaining_gb || 1;
            document.querySelector('input[name="refund_min_remaining_days"]').value = panel.refund_min_remaining_days || 0;
            document.getElementById('renewal_enabled').checked = (panel.renewal_enabled == 1);
            
            // فیلدهای جدید خرید حجم دلخواه
            document.getElementById('custom_volume_enabled').checked = (panel.custom_volume_enabled == 1);
            document.getElementById('custom_volume_price_per_gb').value = panel.custom_volume_price_per_gb || 0;
            document.getElementById('custom_volume_min_gb').value = panel.custom_volume_min_gb || 1;
            document.getElementById('custom_volume_max_gb').value = panel.custom_volume_max_gb || 100;
            document.getElementById('custom_volume_price_per_day').value = panel.custom_volume_price_per_day || 0;
            document.getElementById('custom_volume_min_days').value = panel.custom_volume_min_days || 1;
            document.getElementById('custom_volume_max_days').value = panel.custom_volume_max_days || 30;
            
            togglePanelType();
            toggleExtraTrafficFields();
            toggleBulkPurchaseFields();
            toggleRefundFields();
            toggleCustomVolumeFields();
            
            if (panel.panel_type == 'xui') {
                document.getElementById('panel_api_token').value = panel.api_token || '';
                document.getElementById('panel_inbound_id').value = panel.inbound_id || '';
                document.getElementById('panel_sub_domain').value = panel.sub_domain || '';
                document.getElementById('panel_sub_port').value = panel.sub_port || 443;
                document.getElementById('panel_sub_path').value = panel.sub_path || '';
            } else {
                document.getElementById('marzban_username').value = panel.marzban_username || '';
                document.getElementById('marzban_password').value = panel.marzban_password || '';
                
                const container = document.getElementById('inbounds_container');
                if (panel.selected_inbounds && panel.selected_inbounds.length > 0) {
                    container.innerHTML = '<div class="info-text">✅ اینباندهای ذخیره شده:</div>';
                    panel.selected_inbounds.forEach(tag => {
                        const div = document.createElement('div');
                        div.className = 'inbound-item';
                        div.innerHTML = `
                            <input type="checkbox" name="selected_inbounds[]" value="${tag.replace(/"/g, '&quot;')}" checked id="inb_${tag.replace(/[^a-zA-Z0-9]/g, '_')}">
                            <label for="inb_${tag.replace(/[^a-zA-Z0-9]/g, '_')}">${tag}</label>
                        `;
                        container.appendChild(div);
                    });
                    container.innerHTML += '<div class="info-text" style="margin-top:10px;">💡 برای تغییر، دوباره دریافت کنید</div>';
                } else {
                    container.innerHTML = '<div class="info-text">⚠️ روی دکمه دریافت کلیک کنید</div>';
                }
            }
            
            let oldInput = document.querySelector('#panelForm input[name="add_panel"], #panelForm input[name="edit_panel"]');
            if (oldInput) oldInput.remove();
            let input = document.createElement('input');
            input.type = 'hidden'; 
            input.name = 'edit_panel'; 
            input.value = '1';
            document.getElementById('panelForm').appendChild(input);
            openModal();
        })
        .catch(error => {
            alert('خطا در بارگذاری اطلاعات پنل');
        });
}
</script>
</body>
</html>