<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once '../../vippanneladmin56329803/config.php';
require_once '../../vippanneladmin56329803/api.php';
require_once 'marzban_api.php';

function displayText($text) {
    if ($text === null) return '';
    return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
}

if (!isset($_SESSION['agent_id'])) {
    header("Location: ../agent.php");
    exit;
}

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

if (!$agent) {
    session_destroy();
    header("Location: ../agent.php");
    exit;
}

$message = null;
$error = null;
$last_created_sub_link = null;

function createCustomVolumeService($pdo, $agent, $panel, $username, $volume_gb, $days, $panel_config) {
    $price_per_gb = $panel['custom_volume_price_per_gb'];
    $price_per_day = $panel['custom_volume_price_per_day'];
    $total_price = ($volume_gb * $price_per_gb) + ($days * $price_per_day);
    
    if ($agent['discount'] > 0) {
        $total_price = round($total_price - ($total_price * $agent['discount'] / 100));
    }
    
    if ($agent['balance'] < $total_price) {
        return ['success' => false, 'error' => 'موجودی کافی نیست'];
    }
    
    if ($panel['panel_type'] == 'marzban') {
        $result = marzban_create_client($panel, $username, $volume_gb, $days);
    } else {
        $result = add_client($panel_config, $username, $volume_gb, $days);
    }
    
    if ($result['success']) {
        $expiry_date = $days > 0 ? date('Y-m-d H:i:s', strtotime("+{$days} days")) : null;
        $stmt = $pdo->prepare("INSERT INTO agent_servers (agent_id, panel_id, plan_id, username, uuid, sub_id, sub_link, volume_gb, days, price, expiry_date, status, is_custom_volume) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 1)");
        $stmt->execute([$agent['id'], $panel['id'], 0, $username, $result['uuid'], $result['subId'], $result['sub_link'], $volume_gb, $days, $total_price, $expiry_date]);
        
        $pdo->prepare("UPDATE agents SET balance = balance - ? WHERE id = ?")->execute([$total_price, $agent['id']]);
        
        return ['success' => true, 'sub_link' => $result['sub_link'], 'price' => $total_price];
    }
    
    return ['success' => false, 'error' => $result['msg'] ?? 'خطا در ساخت سرویس'];
}

if (isset($_POST['action']) && $_POST['action'] == 'custom_volume_service') {
    $panel_id = intval($_POST['panel_id']);
    $username = trim($_POST['username']);
    $volume_gb = floatval($_POST['volume_gb']);
    $days = intval($_POST['days']);
    
    if ($volume_gb <= 0 || $days <= 0) {
        $error = "مقدار حجم و تایم باید بیشتر از صفر باشد";
    } else {
        $stmt = $pdo->prepare("SELECT * FROM panels WHERE id = ? AND status = 1 AND custom_volume_enabled = 1");
        $stmt->execute([$panel_id]);
        $panel = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$panel) {
            $error = "پنل یافت نشد یا خرید حجم دلخواه برای آن فعال نیست";
        } else {
            if ($volume_gb < $panel['custom_volume_min_gb'] || $volume_gb > $panel['custom_volume_max_gb']) {
                $error = "حجم وارد شده باید بین {$panel['custom_volume_min_gb']} و {$panel['custom_volume_max_gb']} گیگابایت باشد";
            } elseif ($days < $panel['custom_volume_min_days'] || $days > $panel['custom_volume_max_days']) {
                $error = "تایم وارد شده باید بین {$panel['custom_volume_min_days']} و {$panel['custom_volume_max_days']} روز باشد";
            } else {
                $panel_config = [
                    'url' => $panel['url'],
                    'username' => $panel['username'],
                    'password' => $panel['password'],
                    'inbound_id' => $panel['inbound_id'],
                    'version' => $panel['version'],
                    'api_token' => $panel['api_token'],
                    'sub_port' => $panel['sub_port'],
                    'sub_path' => $panel['sub_path'],
                    'sub_domain' => $panel['sub_domain']
                ];
                
                $result = createCustomVolumeService($pdo, $agent, $panel, $username, $volume_gb, $days, $panel_config);
                
                if ($result['success']) {
                    $message = "سرویس با حجم دلخواه با موفقیت ساخته شد!";
                    $last_created_sub_link = $result['sub_link'];
                    $stmt = $pdo->prepare("SELECT * FROM agents WHERE id = ?");
                    $stmt->execute([$agent['id']]);
                    $agent = $stmt->fetch(PDO::FETCH_ASSOC);
                } else {
                    $error = $result['error'];
                }
            }
        }
    }
}

if (isset($_POST['action']) && $_POST['action'] == 'bulk_create_service') {
    $panel_id = intval($_POST['panel_id']);
    $plan_id = intval($_POST['plan_id']);
    $base_username = trim($_POST['base_username']);
    $quantity = intval($_POST['quantity']);
    
    $stmt = $pdo->prepare("SELECT * FROM panels WHERE id = ? AND status = 1");
    $stmt->execute([$panel_id]);
    $panel = $stmt->fetch(PDO::FETCH_ASSOC);
    
    $stmt = $pdo->prepare("SELECT * FROM plans WHERE id = ? AND status = 1");
    $stmt->execute([$plan_id]);
    $plan = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$panel || !$plan) {
        $error = "پنل یا پلن یافت نشد";
    } else {
        $price_per_service = $plan['price'];
        if ($agent['discount'] > 0) {
            $price_per_service = round($plan['price'] - ($plan['price'] * $agent['discount'] / 100));
        }
        $total_price = $price_per_service * $quantity;
        
        if ($agent['balance'] < $total_price) {
            $error = "موجودی کافی نیست";
        }
    }
    
    if (!$error) {
        $created = 0;
        $last_link = '';
        for ($i = 1; $i <= $quantity; $i++) {
            $username = $base_username . '_' . $i . '_' . rand(100, 999);
            
            if ($panel['panel_type'] == 'marzban') {
                $result = marzban_create_client($panel, $username, $plan['volume_gb'], $plan['days']);
            } else {
                $panel_info = [
                    'url' => $panel['url'],
                    'username' => $panel['username'],
                    'password' => $panel['password'],
                    'inbound_id' => $panel['inbound_id'],
                    'version' => $panel['version'],
                    'api_token' => $panel['api_token'],
                    'sub_port' => $panel['sub_port'],
                    'sub_path' => $panel['sub_path'],
                    'sub_domain' => $panel['sub_domain']
                ];
                $result = add_client($panel_info, $username, $plan['volume_gb'], $plan['days']);
            }
            
            if ($result['success']) {
                $expiry_date = $plan['days'] > 0 ? date('Y-m-d H:i:s', strtotime("+{$plan['days']} days")) : null;
                $stmt = $pdo->prepare("INSERT INTO agent_servers (agent_id, panel_id, plan_id, username, uuid, sub_id, sub_link, volume_gb, days, price, expiry_date, status, is_custom_volume) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 0)");
                $stmt->execute([$agent['id'], $panel_id, $plan_id, $username, $result['uuid'], $result['subId'], $result['sub_link'], $plan['volume_gb'], $plan['days'], $price_per_service, $expiry_date]);
                $created++;
                $last_link = $result['sub_link'];
            }
        }
        
        if ($created > 0) {
            $actual_total = $price_per_service * $created;
            $pdo->prepare("UPDATE agents SET balance = balance - ? WHERE id = ?")->execute([$actual_total, $agent['id']]);
            $stmt = $pdo->prepare("SELECT * FROM agents WHERE id = ?");
            $stmt->execute([$agent['id']]);
            $agent = $stmt->fetch(PDO::FETCH_ASSOC);
            $message = "$created سرویس با موفقیت ساخته شد!";
            $last_created_sub_link = $last_link;
        } else {
            $error = "هیچ سرویسی ساخته نشد";
        }
    }
}

if (isset($_POST['action']) && $_POST['action'] == 'create_service') {
    $panel_id = intval($_POST['panel_id']);
    $plan_id = intval($_POST['plan_id']);
    $username = trim($_POST['username']);
    
    $stmt = $pdo->prepare("SELECT * FROM panels WHERE id = ? AND status = 1");
    $stmt->execute([$panel_id]);
    $panel = $stmt->fetch(PDO::FETCH_ASSOC);
    
    $stmt = $pdo->prepare("SELECT * FROM plans WHERE id = ? AND status = 1");
    $stmt->execute([$plan_id]);
    $plan = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$panel || !$plan) {
        $error = "پنل یا پلن یافت نشد";
    } else {
        $final_price = $plan['price'];
        if ($agent['discount'] > 0) {
            $final_price = round($plan['price'] - ($plan['price'] * $agent['discount'] / 100));
        }
        
        if ($agent['balance'] < $final_price) {
            $error = "موجودی کافی نیست";
        }
    }
    
    if (!$error) {
        if ($panel['panel_type'] == 'marzban') {
            $result = marzban_create_client($panel, $username, $plan['volume_gb'], $plan['days']);
        } else {
            $panel_info = [
                'url' => $panel['url'],
                'username' => $panel['username'],
                'password' => $panel['password'],
                'inbound_id' => $panel['inbound_id'],
                'version' => $panel['version'],
                'api_token' => $panel['api_token'],
                'sub_port' => $panel['sub_port'],
                'sub_path' => $panel['sub_path'],
                'sub_domain' => $panel['sub_domain']
            ];
            $result = add_client($panel_info, $username, $plan['volume_gb'], $plan['days']);
        }
        
        if ($result['success']) {
            $expiry_date = $plan['days'] > 0 ? date('Y-m-d H:i:s', strtotime("+{$plan['days']} days")) : null;
            $stmt = $pdo->prepare("INSERT INTO agent_servers (agent_id, panel_id, plan_id, username, uuid, sub_id, sub_link, volume_gb, days, price, expiry_date, status, is_custom_volume) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 0)");
            $stmt->execute([$agent['id'], $panel_id, $plan_id, $username, $result['uuid'], $result['subId'], $result['sub_link'], $plan['volume_gb'], $plan['days'], $final_price, $expiry_date]);
            
            $pdo->prepare("UPDATE agents SET balance = balance - ? WHERE id = ?")->execute([$final_price, $agent['id']]);
            $stmt = $pdo->prepare("SELECT * FROM agents WHERE id = ?");
            $stmt->execute([$agent['id']]);
            $agent = $stmt->fetch(PDO::FETCH_ASSOC);
            
            $message = "سرویس با موفقیت ساخته شد!";
            $last_created_sub_link = $result['sub_link'];
        } else {
            $error = "خطا در ساخت: " . ($result['msg'] ?? '');
        }
    }
}

$panels = $pdo->query("SELECT * FROM panels WHERE status = 1 ORDER BY name")->fetchAll();
$plans = $pdo->query("SELECT plans.*, panels.name as panel_name FROM plans LEFT JOIN panels ON plans.panel_id = panels.id WHERE plans.status = 1 ORDER BY panels.name, plans.price")->fetchAll();

$plans_by_panel = [];
foreach ($plans as $plan) {
    $plans_by_panel[$plan['panel_id']][] = $plan;
}

$custom_volume_panels = array_filter($panels, function($p) {
    return isset($p['custom_volume_enabled']) && $p['custom_volume_enabled'] == 1;
});
?>
<!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>
    <link rel="stylesheet" href="style/services.css">
</head>
<body>
<div class="container">

    <div class="admin-header">
        <div class="brand">
            <span class="brand-name">
                <svg class="svg-icon" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M12 2L2 7l10 5 10-5-10-5z"/>
                    <path d="M2 17l10 5 10-5"/>
                    <path d="M2 12l10 5 10-5"/>
                </svg>
                ساخت سرویس جدید
            </span>
        </div>
        <div class="admin-info">
            <div class="info-item">
                <svg class="svg-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <circle cx="12" cy="8" r="4"/>
                    <path d="M4 20c0-4 3.6-7 8-7s8 3 8 7"/>
                </svg>
                <span>خوش آمدید، <strong><?= displayText($agent['name']) ?></strong></span>
            </div>
            <div class="info-item">
                <svg class="svg-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <rect x="2" y="6" width="20" height="14" rx="3"/>
                    <path d="M2 10h20"/>
                    <circle cx="7" cy="15" r="1.5"/>
                </svg>
                موجودی: <span class="balance-amount"><?= number_format($agent['balance']) ?> تومان</span>
            </div>
            <a href="manage_services.php" class="my-services-btn">
                <svg class="svg-icon" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <rect x="3" y="3" width="7" height="7" rx="1.5"/>
                    <rect x="14" y="3" width="7" height="7" rx="1.5"/>
                    <rect x="3" y="14" width="7" height="7" rx="1.5"/>
                    <rect x="14" y="14" width="7" height="7" rx="1.5"/>
                </svg>
                سرویس‌های من
            </a>
            <a href="../agent.php" class="admin-link">
                <svg class="svg-icon" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M19 12H5M12 5l-7 7 7 7"/>
                </svg>
                بازگشت
            </a>
            <a href="../agent.php?logout=1" class="admin-link logout-link">
                <svg class="svg-icon" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M9 21H5a2 2 0 01-2-2V5a2 2 0 012-2h4"/>
                    <path d="M16 17l5-5-5-5M21 12H9"/>
                </svg>
                خروج
            </a>
        </div>
    </div>

    <?php if($message): ?>
    <div class="alert alert-success">
        <svg class="svg-icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <circle cx="12" cy="12" r="10"/>
            <path d="M7.5 12l3 3 6-6"/>
        </svg>
        <span><?= displayText($message) ?></span>
    </div>
    <?php endif; ?>

    <?php if($error): ?>
    <div class="alert alert-error">
        <svg class="svg-icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <circle cx="12" cy="12" r="10"/>
            <line x1="12" y1="8" x2="12" y2="12"/>
            <line x1="12" y1="16" x2="12.01" y2="16"/>
        </svg>
        <span><?= displayText($error) ?></span>
    </div>
    <?php endif; ?>

    <?php if($last_created_sub_link): ?>
    <div class="sub-link-box">
        <div class="sub-link-header">
            <svg class="svg-icon" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <circle cx="12" cy="12" r="10"/>
                <path d="M7.5 12l3 3 6-6"/>
            </svg>
            سرویس با موفقیت ساخته شد
        </div>
        <div class="sub-link-url">
            <a href="<?= $last_created_sub_link ?>" target="_blank"><?= $last_created_sub_link ?></a>
        </div>
        <button onclick="copyToClipboard('<?= $last_created_sub_link ?>')" class="copy-btn">
            <svg class="svg-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <rect x="8" y="8" width="13" height="13" rx="2"/>
                <path d="M16 8V5a2 2 0 00-2-2H5a2 2 0 00-2 2v9a2 2 0 002 2h3"/>
            </svg>
            کپی لینک
        </button>
    </div>
    <?php endif; ?>

    <div class="content-card">
        
        <div class="mode-switch">
            <button class="mode-btn active" id="singleModeBtn" onclick="setMode('single')">
                <svg class="svg-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <circle cx="12" cy="12" r="3"/>
                    <path d="M12 2v3M12 19v3M2 12h3M19 12h3"/>
                </svg>
                خرید تکی
            </button>
            <button class="mode-btn" id="bulkModeBtn" onclick="setMode('bulk')">
                <svg class="svg-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <rect x="2" y="3" width="6" height="6" rx="1.5"/>
                    <rect x="9" y="3" width="6" height="6" rx="1.5"/>
                    <rect x="16" y="3" width="6" height="6" rx="1.5"/>
                    <rect x="2" y="15" width="6" height="6" rx="1.5"/>
                    <rect x="9" y="15" width="6" height="6" rx="1.5"/>
                    <rect x="16" y="15" width="6" height="6" rx="1.5"/>
                </svg>
                خرید عمده
            </button>
            <?php if(count($custom_volume_panels) > 0): ?>
            <button class="mode-btn" id="customModeBtn" onclick="setMode('custom')">
                <svg class="svg-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/>
                    <path d="M14 2v6h6"/>
                    <line x1="12" y1="18" x2="12" y2="12"/>
                    <line x1="9" y1="15" x2="15" y2="15"/>
                </svg>
                خرید حجم دلخواه
            </button>
            <?php endif; ?>
        </div>

        <!-- فرم تکی -->
        <form method="POST" id="singleForm" class="service-form">
            <input type="hidden" name="action" value="create_service">
            <input type="hidden" name="panel_id" id="single_panel_id">
            <input type="hidden" name="plan_id" id="single_plan_id">

            <div class="form-group">
                <label>
                    <svg class="svg-icon label-svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <rect x="3" y="3" width="7" height="7" rx="2"/>
                        <rect x="14" y="3" width="7" height="7" rx="2"/>
                        <rect x="3" y="14" width="7" height="7" rx="2"/>
                        <rect x="14" y="14" width="7" height="7" rx="2"/>
                    </svg>
                    انتخاب پنل
                </label>
                <div class="panel-chips" id="single_panel_list">
                    <?php foreach($panels as $p): ?>
                        <div class="panel-chip" data-id="<?= $p['id'] ?>" data-name="<?= displayText($p['name']) ?>" onclick="selectPanel('single', this)"><?= displayText($p['name']) ?></div>
                    <?php endforeach; ?>
                </div>
            </div>

            <div class="form-group" id="single_plan_group" style="display: none;">
                <label>
                    <svg class="svg-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2"/>
                        <path d="M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"/>
                        <path d="M9 12h6M9 16h4"/>
                    </svg>
                    انتخاب پلن
                </label>
                <div class="plans-grid" id="single_plans"></div>
            </div>

            <div class="form-group">
                <label>
                    <svg class="svg-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <circle cx="12" cy="8" r="4"/>
                        <path d="M4 20c0-4 3.6-7 8-7s8 3 8 7"/>
                    </svg>
                    نام کاربری
                </label>
                <div class="username-group">
                    <input type="text" name="username" id="username" placeholder="نام کاربری سرویس را وارد کنید" required>
                    <button type="button" class="random-btn" onclick="genUsername()">
                        <svg class="svg-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <path d="M17 3l4 4-4 4M3 7h18M7 21l-4-4 4-4M21 17H3"/>
                        </svg>
                        تصادفی
                    </button>
                </div>
            </div>

            <div class="order-summary" id="summary" style="display: none;">
                <div class="order-summary-title">
                    <svg class="svg-icon" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2"/>
                        <path d="M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"/>
                        <path d="M9 12h6M9 16h4"/>
                    </svg>
                    خلاصه سفارش
                </div>
                <div class="order-summary-row">
                    <span class="sum-label">
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <rect x="3" y="3" width="7" height="7" rx="2"/>
                            <rect x="14" y="3" width="7" height="7" rx="2"/>
                        </svg>
                        پنل
                    </span>
                    <span class="sum-value" id="sum_panel">-</span>
                </div>
                <div class="order-summary-row">
                    <span class="sum-label">
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <path d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2"/>
                        </svg>
                        پلن
                    </span>
                    <span class="sum-value" id="sum_plan">-</span>
                </div>
                <div class="order-summary-row">
                    <span class="sum-label">
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <circle cx="12" cy="8" r="4"/>
                            <path d="M4 20c0-4 3.6-7 8-7s8 3 8 7"/>
                        </svg>
                        نام کاربری
                    </span>
                    <span class="sum-value" id="sum_username">-</span>
                </div>
                <div class="order-summary-row total">
                    <span class="sum-label">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <rect x="2" y="6" width="20" height="14" rx="3"/>
                            <path d="M2 10h20"/>
                            <circle cx="7" cy="15" r="1.5"/>
                        </svg>
                        مبلغ قابل پرداخت
                    </span>
                    <span class="sum-value" id="sum_price">-</span>
                </div>
            </div>

            <div class="form-actions">
                <button type="submit" id="submitBtn" class="btn-submit" disabled>
                    <svg class="svg-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path d="M12 2L2 7l10 5 10-5-10-5z"/>
                        <path d="M2 17l10 5 10-5M2 12l10 5 10-5"/>
                    </svg>
                    ساخت سرویس
                </button>
                <button type="button" class="btn-cancel" onclick="resetForm()">
                    <svg class="svg-icon" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <line x1="18" y1="6" x2="6" y2="18"/>
                        <line x1="6" y1="6" x2="18" y2="18"/>
                    </svg>
                    انصراف
                </button>
            </div>
        </form>

        <!-- فرم عمده -->
        <form method="POST" id="bulkForm" class="service-form" style="display: none;">
            <input type="hidden" name="action" value="bulk_create_service">
            <input type="hidden" name="panel_id" id="bulk_panel_id">
            <input type="hidden" name="plan_id" id="bulk_plan_id">

            <div class="form-group">
                <label>
                    <svg class="svg-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <rect x="3" y="3" width="7" height="7" rx="2"/>
                        <rect x="14" y="3" width="7" height="7" rx="2"/>
                        <rect x="3" y="14" width="7" height="7" rx="2"/>
                        <rect x="14" y="14" width="7" height="7" rx="2"/>
                    </svg>
                    انتخاب پنل
                </label>
                <div class="panel-chips" id="bulk_panel_list">
                    <?php foreach($panels as $p): ?>
                        <div class="panel-chip" data-id="<?= $p['id'] ?>" data-name="<?= displayText($p['name']) ?>" data-bulk="<?= $p['bulk_purchase_enabled'] ?? 0 ?>" data-min="<?= $p['bulk_min_quantity'] ?? 1 ?>" data-max="<?= $p['bulk_max_quantity'] ?? 10 ?>" onclick="selectBulkPanel(this)"><?= displayText($p['name']) ?></div>
                    <?php endforeach; ?>
                </div>
            </div>

            <div class="form-group" id="bulk_plan_group" style="display: none;">
                <label>
                    <svg class="svg-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2"/>
                        <path d="M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"/>
                        <path d="M9 12h6M9 16h4"/>
                    </svg>
                    انتخاب پلن
                </label>
                <div class="plans-grid" id="bulk_plans"></div>
            </div>

            <div class="form-group">
                <label>
                    <svg class="svg-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <circle cx="12" cy="8" r="4"/>
                        <path d="M4 20c0-4 3.6-7 8-7s8 3 8 7"/>
                    </svg>
                    نام پایه کاربری
                </label>
                <input type="text" name="base_username" id="base_username" placeholder="مثال: user">
            </div>

            <div class="form-group">
                <label>
                    <svg class="svg-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/>
                        <circle cx="9" cy="7" r="4"/>
                        <path d="M23 21v-2a4 4 0 00-3-3.87M16 3.13a4 4 0 010 7.75"/>
                    </svg>
                    تعداد سرویس‌ها
                </label>
                <input type="number" name="quantity" id="quantity" value="1" min="1">
                <div id="bulk_range_text" class="bulk-range-badge" style="display: none;"></div>
            </div>

            <div class="order-summary" id="bulk_summary" style="display: none;">
                <div class="order-summary-title">
                    <svg class="svg-icon" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <rect x="2" y="6" width="20" height="14" rx="3"/>
                        <path d="M2 10h20"/>
                        <circle cx="7" cy="15" r="1.5"/>
                        <path d="M11 15h6"/>
                    </svg>
                    پیش‌فاکتور
                </div>
                <div class="order-summary-row">
                    <span class="sum-label">
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <rect x="2" y="6" width="20" height="14" rx="3"/>
                            <path d="M2 10h20"/>
                        </svg>
                        قیمت هر سرویس
                    </span>
                    <span class="sum-value" id="bulk_price_per">0</span>
                </div>
                <div class="order-summary-row total">
                    <span class="sum-label">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <rect x="2" y="6" width="20" height="14" rx="3"/>
                            <path d="M2 10h20"/>
                            <circle cx="7" cy="15" r="1.5"/>
                        </svg>
                        مبلغ کل
                    </span>
                    <span class="sum-value" id="bulk_total">0</span>
                </div>
            </div>

            <div class="form-actions">
                <button type="submit" id="bulkSubmitBtn" class="btn-submit" disabled>
                    <svg class="svg-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/>
                        <circle cx="9" cy="7" r="4"/>
                        <path d="M23 21v-2a4 4 0 00-3-3.87M16 3.13a4 4 0 010 7.75"/>
                    </svg>
                    خرید عمده
                </button>
                <button type="button" class="btn-cancel" onclick="resetBulkForm()">
                    <svg class="svg-icon" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <line x1="18" y1="6" x2="6" y2="18"/>
                        <line x1="6" y1="6" x2="18" y2="18"/>
                    </svg>
                    انصراف
                </button>
            </div>
        </form>

        <!-- فرم حجم دلخواه -->
        <form method="POST" id="customForm" class="service-form" style="display: none;">
            <input type="hidden" name="action" value="custom_volume_service">
            <input type="hidden" name="panel_id" id="custom_panel_id">

            <div class="form-group">
                <label>
                    <svg class="svg-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <rect x="3" y="3" width="7" height="7" rx="2"/>
                        <rect x="14" y="3" width="7" height="7" rx="2"/>
                        <rect x="3" y="14" width="7" height="7" rx="2"/>
                        <rect x="14" y="14" width="7" height="7" rx="2"/>
                    </svg>
                    انتخاب پنل (خرید حجم دلخواه)
                </label>
                <div class="panel-chips" id="custom_panel_list">
                    <?php foreach($custom_volume_panels as $p): ?>
                        <div class="panel-chip" data-id="<?= $p['id'] ?>" data-name="<?= displayText($p['name']) ?>" data-price-gb="<?= $p['custom_volume_price_per_gb'] ?>" data-price-day="<?= $p['custom_volume_price_per_day'] ?>" data-min-gb="<?= $p['custom_volume_min_gb'] ?>" data-max-gb="<?= $p['custom_volume_max_gb'] ?>" data-min-days="<?= $p['custom_volume_min_days'] ?>" data-max-days="<?= $p['custom_volume_max_days'] ?>" onclick="selectCustomPanel(this)"><?= displayText($p['name']) ?></div>
                    <?php endforeach; ?>
                </div>
            </div>

            <div id="custom_volume_details" style="display: none;">
                <div class="custom-volume-section">
                    <div class="custom-volume-header">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/>
                            <path d="M14 2v6h6"/>
                            <line x1="12" y1="18" x2="12" y2="12"/>
                            <line x1="9" y1="15" x2="15" y2="15"/>
                        </svg>
                        <h4>مشخصات سرویس دلخواه</h4>
                    </div>

                    <div class="custom-range-info" id="custom_range_info"></div>

                    <div class="input-group">
                        <label>
                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <rect x="2" y="3" width="20" height="16" rx="3"/>
                                <path d="M8 12h8M8 16h5"/>
                            </svg>
                            حجم مورد نظر (گیگابایت)
                        </label>
                        <input type="number" step="any" name="volume_gb" id="volume_gb" placeholder="مثال: 50">
                    </div>

                    <div class="input-group">
                        <label>
                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <circle cx="12" cy="12" r="10"/>
                                <path d="M12 6v6l3 3"/>
                            </svg>
                            تایم مورد نظر (روز)
                        </label>
                        <input type="number" name="days" id="custom_days" placeholder="مثال: 30">
                    </div>

                    <div class="price-breakdown" id="price_breakdown" style="display: none;">
                        <div class="price-row">
                            <span>قیمت حجم:</span>
                            <span id="volume_price">0 تومان</span>
                        </div>
                        <div class="price-row">
                            <span>قیمت تایم:</span>
                            <span id="time_price">0 تومان</span>
                        </div>
                        <div class="price-row total">
                            <span>مبلغ قابل پرداخت :</span>
                            <span id="total_price">0 تومان</span>
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <label>
                        <svg class="svg-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <circle cx="12" cy="8" r="4"/>
                            <path d="M4 20c0-4 3.6-7 8-7s8 3 8 7"/>
                        </svg>
                        نام کاربری
                    </label>
                    <div class="username-group">
                        <input type="text" name="username" id="custom_username" placeholder="نام کاربری سرویس را وارد کنید" required>
                        <button type="button" class="random-btn" onclick="genCustomUsername()">
                            <svg class="svg-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M17 3l4 4-4 4M3 7h18M7 21l-4-4 4-4M21 17H3"/>
                            </svg>
                            تصادفی
                        </button>
                    </div>
                </div>

                <div class="form-actions">
                    <button type="submit" id="customSubmitBtn" class="btn-submit" disabled>
                        <svg class="svg-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <path d="M12 2L2 7l10 5 10-5-10-5z"/>
                            <path d="M2 17l10 5 10-5M2 12l10 5 10-5"/>
                        </svg>
                        ساخت سرویس دلخواه
                    </button>
                    <button type="button" class="btn-cancel" onclick="resetCustomForm()">
                        <svg class="svg-icon" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <line x1="18" y1="6" x2="6" y2="18"/>
                            <line x1="6" y1="6" x2="18" y2="18"/>
                        </svg>
                        انصراف
                    </button>
                </div>
            </div>
        </form>

    </div>
</div>

<script>
function copyToClipboard(text) {
    navigator.clipboard.writeText(text);
    const btn = document.querySelector('.copy-btn');
    const orig = btn.innerHTML;
    btn.innerHTML = '<svg class="svg-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M7.5 12l3 3 6-6"/></svg> کپی شد!';
    setTimeout(() => btn.innerHTML = orig, 2000);
}

const plansByPanel = <?= json_encode($plans_by_panel) ?>;
const discount = <?= $agent['discount'] ?>;
let selectedPanelId = null, selectedPlan = null, selectedPlanPrice = null, selectedPlanDiscountPrice = null;
let bulkSelectedPanelId = null, bulkSelectedPlan = null, bulkSelectedPlanPrice = null, bulkSelectedPlanDiscountPrice = null;
let bulkMinQty = 1, bulkMaxQty = 10;

let customSelectedPanel = null;
let customPricePerGb = 0, customPricePerDay = 0;
let customMinGb = 0, customMaxGb = 0, customMinDays = 0, customMaxDays = 0;

function setMode(mode) {
    const singleForm = document.getElementById('singleForm');
    const bulkForm = document.getElementById('bulkForm');
    const customForm = document.getElementById('customForm');
    const singleBtn = document.getElementById('singleModeBtn');
    const bulkBtn = document.getElementById('bulkModeBtn');
    const customBtn = document.getElementById('customModeBtn');
    
    if (mode === 'single') {
        singleForm.style.display = 'block';
        bulkForm.style.display = 'none';
        customForm.style.display = 'none';
        singleBtn.classList.add('active');
        bulkBtn.classList.remove('active');
        if(customBtn) customBtn.classList.remove('active');
    } else if (mode === 'bulk') {
        singleForm.style.display = 'none';
        bulkForm.style.display = 'block';
        customForm.style.display = 'none';
        singleBtn.classList.remove('active');
        bulkBtn.classList.add('active');
        if(customBtn) customBtn.classList.remove('active');
    } else {
        singleForm.style.display = 'none';
        bulkForm.style.display = 'none';
        customForm.style.display = 'block';
        singleBtn.classList.remove('active');
        bulkBtn.classList.remove('active');
        if(customBtn) customBtn.classList.add('active');
    }
}

function buildPlanCards(plans, containerId, clickFn) {
    const container = document.getElementById(containerId);
    if (!plans.length) {
        container.innerHTML = `<div class="empty-plans"><svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="8" y1="12" x2="16" y2="12"/><line x1="12" y1="8" x2="12" y2="16"/></svg><span>هیچ پلنی موجود نیست</span></div>`;
        return;
    }
    container.innerHTML = plans.map(p => {
        let vol = p.volume_gb == 0 ? 'نامحدود' : (p.volume_gb < 1 ? (p.volume_gb * 1000) + ' MB' : p.volume_gb + ' GB');
        let days = p.days == 0 ? 'نامحدود' : p.days + ' روز';
        let origPrice = parseInt(p.price);
        let discPrice = discount > 0 ? Math.round(origPrice - (origPrice * discount / 100)) : origPrice;
        let priceHtml = discount > 0
            ? `<span class="old-price">${origPrice.toLocaleString()} تومان</span><span class="new-price">${discPrice.toLocaleString()} تومان</span>`
            : `<span class="new-price">${origPrice.toLocaleString()} تومان</span>`;
        return `<div class="plan-card" data-id="${p.id}" data-name="${p.name}" data-price="${origPrice}" data-discount="${discPrice}" onclick="${clickFn}(this)">
            <div class="plan-name">${p.name}</div>
            <div class="plan-meta">
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l3 3"/></svg>${days}
                &nbsp;&nbsp;
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="3" width="20" height="16" rx="3"/><path d="M8 12h8M8 16h5"/></svg>${vol}
            </div>
            <div class="plan-price">${priceHtml}</div>
        </div>`;
    }).join('');
}

function selectPanel(type, element) {
    document.querySelectorAll('#single_panel_list .panel-chip').forEach(c => c.classList.remove('active'));
    element.classList.add('active');
    selectedPanelId = element.dataset.id;
    document.getElementById('single_panel_id').value = selectedPanelId;
    document.getElementById('single_plan_group').style.display = 'block';
    buildPlanCards(plansByPanel[selectedPanelId] || [], 'single_plans', 'selectPlan');
    selectedPlan = null;
    document.getElementById('single_plan_id').value = '';
    updateSummary();
    checkSubmitReady();
}

function selectPlan(element) {
    document.querySelectorAll('#single_plans .plan-card').forEach(c => c.classList.remove('selected'));
    element.classList.add('selected');
    selectedPlan = element.dataset.name;
    selectedPlanPrice = element.dataset.price;
    selectedPlanDiscountPrice = element.dataset.discount;
    document.getElementById('single_plan_id').value = element.dataset.id;
    updateSummary();
    checkSubmitReady();
}

function updateSummary() {
    const username = document.getElementById('username').value.trim();
    const panelName = document.querySelector('#single_panel_list .panel-chip.active')?.innerText || '-';
    if (!selectedPanelId || !selectedPlan || !username) {
        document.getElementById('summary').style.display = 'none';
        return;
    }
    document.getElementById('summary').style.display = 'block';
    document.getElementById('sum_panel').textContent = panelName;
    document.getElementById('sum_plan').textContent = selectedPlan;
    document.getElementById('sum_username').textContent = username;
    let price = discount > 0 ? parseInt(selectedPlanDiscountPrice) : parseInt(selectedPlanPrice);
    document.getElementById('sum_price').textContent = price.toLocaleString() + ' تومان';
}

function checkSubmitReady() {
    const username = document.getElementById('username').value.trim();
    document.getElementById('submitBtn').disabled = !(selectedPanelId && selectedPlan && username.length >= 2);
}

function genUsername() {
    const names = ['saeed', 'reza', 'ali', 'mohammad', 'hossein', 'sara', 'zahra', 'fatemeh'];
    const name = names[Math.floor(Math.random() * names.length)];
    const num = Math.floor(100 + Math.random() * 900);
    document.getElementById('username').value = name + '_' + num;
    updateSummary();
    checkSubmitReady();
}

function resetForm() {
    selectedPanelId = null; selectedPlan = null;
    document.getElementById('single_panel_id').value = '';
    document.getElementById('single_plan_id').value = '';
    document.getElementById('username').value = '';
    document.getElementById('summary').style.display = 'none';
    document.getElementById('single_plan_group').style.display = 'none';
    document.querySelectorAll('#single_panel_list .panel-chip').forEach(c => c.classList.remove('active'));
    document.getElementById('single_plans').innerHTML = '';
    checkSubmitReady();
}

function selectBulkPanel(element) {
    if (element.dataset.bulk !== '1') {
        alert('خرید عمده برای این پنل فعال نیست!');
        return;
    }
    document.querySelectorAll('#bulk_panel_list .panel-chip').forEach(c => c.classList.remove('active'));
    element.classList.add('active');
    bulkSelectedPanelId = element.dataset.id;
    bulkMinQty = parseInt(element.dataset.min) || 1;
    bulkMaxQty = parseInt(element.dataset.max) || 10;
    document.getElementById('bulk_panel_id').value = bulkSelectedPanelId;
    document.getElementById('bulk_plan_group').style.display = 'block';
    document.getElementById('quantity').min = bulkMinQty;
    document.getElementById('quantity').max = bulkMaxQty;
    const rangeEl = document.getElementById('bulk_range_text');
    rangeEl.style.display = 'inline-flex';
    rangeEl.innerHTML = `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="9"/><path d="M12 8v4l2 2"/></svg> حداقل ${bulkMinQty} و حداکثر ${bulkMaxQty} سرویس`;
    buildPlanCards(plansByPanel[bulkSelectedPanelId] || [], 'bulk_plans', 'selectBulkPlan');
    bulkSelectedPlan = null;
    document.getElementById('bulk_plan_id').value = '';
    updateBulkPreview();
}

function selectBulkPlan(element) {
    document.querySelectorAll('#bulk_plans .plan-card').forEach(c => c.classList.remove('selected'));
    element.classList.add('selected');
    bulkSelectedPlan = element.dataset.name;
    bulkSelectedPlanPrice = element.dataset.price;
    bulkSelectedPlanDiscountPrice = element.dataset.discount;
    document.getElementById('bulk_plan_id').value = element.dataset.id;
    updateBulkPreview();
}

function updateBulkPreview() {
    const baseUser = document.getElementById('base_username').value.trim();
    const qty = parseInt(document.getElementById('quantity').value) || 0;
    if (!bulkSelectedPanelId || !bulkSelectedPlan || !baseUser || qty < bulkMinQty || qty > bulkMaxQty) {
        document.getElementById('bulk_summary').style.display = 'none';
        document.getElementById('bulkSubmitBtn').disabled = true;
        return;
    }
    let pricePer = discount > 0 ? parseInt(bulkSelectedPlanDiscountPrice) : parseInt(bulkSelectedPlanPrice);
    let total = pricePer * qty;
    document.getElementById('bulk_price_per').textContent = pricePer.toLocaleString() + ' تومان';
    document.getElementById('bulk_total').textContent = total.toLocaleString() + ' تومان';
    document.getElementById('bulk_summary').style.display = 'block';
    document.getElementById('bulkSubmitBtn').disabled = false;
}

function resetBulkForm() {
    bulkSelectedPanelId = null; bulkSelectedPlan = null;
    document.getElementById('bulk_panel_id').value = '';
    document.getElementById('bulk_plan_id').value = '';
    document.getElementById('base_username').value = '';
    document.getElementById('quantity').value = '1';
    document.getElementById('bulk_plan_group').style.display = 'none';
    document.getElementById('bulk_summary').style.display = 'none';
    document.getElementById('bulk_range_text').style.display = 'none';
    document.querySelectorAll('#bulk_panel_list .panel-chip').forEach(c => c.classList.remove('active'));
}

function selectCustomPanel(element) {
    document.querySelectorAll('#custom_panel_list .panel-chip').forEach(c => c.classList.remove('active'));
    element.classList.add('active');
    
    customSelectedPanel = element.dataset.id;
    customPricePerGb = parseFloat(element.dataset.priceGb) || 0;
    customPricePerDay = parseFloat(element.dataset.priceDay) || 0;
    customMinGb = parseFloat(element.dataset.minGb) || 1;
    customMaxGb = parseFloat(element.dataset.maxGb) || 100;
    customMinDays = parseInt(element.dataset.minDays) || 1;
    customMaxDays = parseInt(element.dataset.maxDays) || 30;
    
    document.getElementById('custom_panel_id').value = customSelectedPanel;
    
    const rangeInfo = document.getElementById('custom_range_info');
    rangeInfo.innerHTML = `
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 8v4l3 3"/></svg>
        محدوده حجم: <span>${customMinGb} تا ${customMaxGb} گیگابایت</span> | 
        محدوده تایم: <span>${customMinDays} تا ${customMaxDays} روز</span>
    `;
    
    document.getElementById('volume_gb').min = customMinGb;
    document.getElementById('volume_gb').max = customMaxGb;
    document.getElementById('custom_days').min = customMinDays;
    document.getElementById('custom_days').max = customMaxDays;
    
    document.getElementById('custom_volume_details').style.display = 'block';
    
    document.getElementById('volume_gb').addEventListener('input', calculateCustomPrice);
    document.getElementById('custom_days').addEventListener('input', calculateCustomPrice);
    document.getElementById('custom_username').addEventListener('input', checkCustomSubmitReady);
    
    calculateCustomPrice();
}

function calculateCustomPrice() {
    const volume = parseFloat(document.getElementById('volume_gb').value) || 0;
    const days = parseInt(document.getElementById('custom_days').value) || 0;
    
    let volumePrice = volume * customPricePerGb;
    let timePrice = days * customPricePerDay;
    let total = volumePrice + timePrice;
    
    if (discount > 0) {
        volumePrice = Math.round(volumePrice - (volumePrice * discount / 100));
        timePrice = Math.round(timePrice - (timePrice * discount / 100));
        total = Math.round(total - (total * discount / 100));
    }
    
    if (volume >= customMinGb && volume <= customMaxGb && days >= customMinDays && days <= customMaxDays && volume > 0 && days > 0) {
        document.getElementById('price_breakdown').style.display = 'block';
        document.getElementById('volume_price').textContent = volumePrice.toLocaleString() + ' تومان';
        document.getElementById('time_price').textContent = timePrice.toLocaleString() + ' تومان';
        document.getElementById('total_price').textContent = total.toLocaleString() + ' تومان';
        checkCustomSubmitReady();
    } else {
        document.getElementById('price_breakdown').style.display = 'none';
        document.getElementById('customSubmitBtn').disabled = true;
    }
}

function checkCustomSubmitReady() {
    const volume = parseFloat(document.getElementById('volume_gb').value) || 0;
    const days = parseInt(document.getElementById('custom_days').value) || 0;
    const username = document.getElementById('custom_username').value.trim();
    
    const volumeValid = volume >= customMinGb && volume <= customMaxGb && volume > 0;
    const daysValid = days >= customMinDays && days <= customMaxDays && days > 0;
    
    document.getElementById('customSubmitBtn').disabled = !(volumeValid && daysValid && username.length >= 2);
}

function genCustomUsername() {
    const names = ['saeed', 'reza', 'ali', 'mohammad', 'hossein', 'sara', 'zahra', 'fatemeh'];
    const name = names[Math.floor(Math.random() * names.length)];
    const num = Math.floor(100 + Math.random() * 900);
    document.getElementById('custom_username').value = name + '_' + num;
    checkCustomSubmitReady();
}

function resetCustomForm() {
    customSelectedPanel = null;
    document.getElementById('custom_panel_id').value = '';
    document.getElementById('volume_gb').value = '';
    document.getElementById('custom_days').value = '';
    document.getElementById('custom_username').value = '';
    document.getElementById('custom_volume_details').style.display = 'none';
    document.getElementById('price_breakdown').style.display = 'none';
    document.querySelectorAll('#custom_panel_list .panel-chip').forEach(c => c.classList.remove('active'));
}

document.getElementById('username')?.addEventListener('input', function() { updateSummary(); checkSubmitReady(); });
document.getElementById('base_username')?.addEventListener('input', updateBulkPreview);
document.getElementById('quantity')?.addEventListener('input', updateBulkPreview);
</script>
</body>
</html>