

<?php $__env->startSection('title', 'ایجاد سرور جدید'); ?>

<?php $__env->startSection('css'); ?>
<link rel="stylesheet" href="<?php echo e(asset('assets/css/vendors/select/bootstrap-select.min.css')); ?>">
<link href="https://cdn.jsdelivr.net/npm/remixicon/fonts/remixicon.css" rel="stylesheet">
<style>
/* 🎨 طراحی مدرن */
.sidebar-panel-main { display: none !important; }
body { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; }
.main-content { background: transparent; }
.page-content { padding: 2rem 0; }

/* کارت‌های مدرن */
.step-container { 
    background: rgba(255, 255, 255, 0.95); 
    backdrop-filter: blur(10px);
    border: none; 
    border-radius: 20px; 
    padding: 2rem; 
    margin-bottom: 2rem; 
    box-shadow: 0 20px 60px rgba(0,0,0,0.15);
    animation: slideUp 0.5s ease;
}

@keyframes slideUp {
    from { opacity: 0; transform: translateY(30px); }
    to { opacity: 1; transform: translateY(0); }
}

/* هدر مراحل */
.step-header { 
    display: flex; 
    justify-content: space-between; 
    align-items: center; 
    margin-bottom: 2rem; 
    padding-bottom: 1rem;
    border-bottom: 2px solid #f0f0f0;
}
.step-header h4 { 
    margin: 0; 
    font-weight: 700;
    color: #667eea;
    font-size: 1.5rem;
}

/* خلاصه سفارش */
.order-summary-card {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 20px;
    padding: 1.5rem;
    margin-bottom: 2rem;
    box-shadow: 0 10px 40px rgba(102, 126, 234, 0.3);
}
.order-summary-card h4 {
    color: #fff;
    font-weight: 700;
    margin-bottom: 1.5rem;
    text-align: center;
}
.summary-item {
    background: rgba(255, 255, 255, 0.15);
    backdrop-filter: blur(10px);
    border-radius: 12px;
    padding: 1rem;
    transition: all 0.3s ease;
}
.summary-item:hover {
    background: rgba(255, 255, 255, 0.25);
    transform: translateY(-3px);
}
.summary-item h6 {
    color: rgba(255, 255, 255, 0.9);
    font-size: 0.85rem;
    font-weight: 600;
    margin-bottom: 0.5rem;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}
.summary-item span {
    color: #fff;
    font-weight: 700;
    font-size: 1rem;
}

/* 💰 باکس قیمت - اصلاح شده */
.pricing-box {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 20px;
    padding: 2rem;
    margin-top: 2rem;
    box-shadow: 0 15px 40px rgba(102, 126, 234, 0.4);
    animation: pulse 2s infinite;
}
@keyframes pulse {
    0%, 100% { transform: scale(1); }
    50% { transform: scale(1.02); }
}
.pricing-box h5 {
    color: #fff;
    font-weight: 700;
    margin-bottom: 1.5rem;
    text-align: center;
    font-size: 1.5rem;
    text-shadow: 0 2px 10px rgba(0,0,0,0.2);
}
.price-item {
    background: rgba(255, 255, 255, 0.15);
    backdrop-filter: blur(10px);
    border-radius: 12px;
    padding: 1rem 1.5rem;
    margin-bottom: 1rem;
    display: flex;
    justify-content: space-between;
    align-items: center;
    transition: all 0.3s ease;
}
.price-item:hover {
    background: rgba(255, 255, 255, 0.25);
    transform: translateX(5px);
}
.price-item:last-child {
    background: rgba(255, 255, 255, 0.35);
    border: 2px solid rgba(255, 255, 255, 0.6);
    margin-top: 0.5rem;
}
.price-label {
    color: #1a1a2e; /* ✅ تیره شد */
    font-weight: 700;
    font-size: 1rem;
}
.price-label i {
    color: #667eea;
    margin-right: 0.5rem;
    font-size: 1.2rem;
}
.price-value {
    color: #1a1a2e; /* ✅ تیره شد */
    font-weight: 800;
    font-size: 1.3rem;
}

/* کارت‌های رادیویی */
.form-check.card-radio {
    margin-bottom: 0;
}
.form-check.card-radio .btn {
    border-radius: 12px;
    padding: 1rem 1.5rem;
    transition: all 0.3s ease;
    border: 2px solid #e0e0e0;
    background: #fff;
}
.form-check.card-radio .btn:hover {
    border-color: #667eea;
    transform: translateY(-3px);
    box-shadow: 0 10px 25px rgba(102, 126, 234, 0.2);
}
.form-check.card-radio input:checked + label {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #fff !important;
    border-color: transparent;
    box-shadow: 0 10px 30px rgba(102, 126, 234, 0.4);
}
.form-check.card-radio input:checked + label * {
    color: #fff !important;
}

/* ✅ کارت سیستم‌عامل - کوچکتر شده */
.os-card .btn {
    padding: 0.75rem 1rem !important;
}
.os-card .os-icon {
    width: 40px; /* ✅ از 60px به 40px */
    height: 40px;
    margin-bottom: 0.5rem;
    filter: grayscale(100%);
    opacity: 0.7;
    transition: all 0.3s ease;
}
.os-card:hover .os-icon {
    filter: grayscale(0%);
    opacity: 1;
    transform: scale(1.1);
}
.form-check.card-radio input:checked + label .os-icon {
    filter: grayscale(0%) brightness(2);
    opacity: 1;
}
.os-card .os-name {
    font-size: 0.85rem; /* ✅ کوچکتر */
    font-weight: 600;
}

/* دکمه‌ها */
.btn-primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
    border-radius: 10px;
    padding: 0.75rem 2rem;
    font-weight: 600;
    box-shadow: 0 10px 25px rgba(102, 126, 234, 0.3);
    transition: all 0.3s ease;
}
.btn-primary:hover {
    transform: translateY(-3px);
    box-shadow: 0 15px 35px rgba(102, 126, 234, 0.4);
}
.btn-success {
    background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
    border: none;
    border-radius: 10px;
    padding: 1rem 3rem;
    font-weight: 700;
    font-size: 1.1rem;
    box-shadow: 0 10px 25px rgba(17, 153, 142, 0.3);
}
.btn-success:hover {
    transform: translateY(-3px);
    box-shadow: 0 15px 35px rgba(17, 153, 142, 0.4);
}
.btn-danger {
    background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    border: none;
    border-radius: 10px;
}

/* تب‌ها */
.nav-tabs .nav-link, .nav-pills .nav-link {
    border: none;
    border-radius: 10px;
    padding: 0.75rem 1.5rem;
    margin: 0 0.25rem;
    font-weight: 600;
    color: #667eea;
    transition: all 0.3s ease;
}
.nav-tabs .nav-link:hover, .nav-pills .nav-link:hover {
    background: rgba(102, 126, 234, 0.1);
}
.nav-tabs .nav-link.active, .nav-pills .nav-link.active {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #fff;
    box-shadow: 0 5px 15px rgba(102, 126, 234, 0.3);
}

/* Toast */
.toast-custom { 
    background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%) !important;
    color: #fff !important; 
    border: none !important; 
    border-radius: 12px !important;
    box-shadow: 0 10px 30px rgba(245, 87, 108, 0.4);
}
.toast-custom-success { 
    background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%) !important;
    box-shadow: 0 10px 30px rgba(17, 153, 142, 0.4);
}
.toast-body {
    word-wrap: break-word;
    color: #fff !important;
    font-weight: 600;
}

/* Spinner */
.spin { 
    animation: spin 1s linear infinite; 
    display: inline-block; 
}
@keyframes spin { 
    100% { transform: rotate(360deg); } 
}

/* Responsive */
@media (max-width: 768px) {
    .step-container { padding: 1.5rem; }
    .order-summary-card { padding: 1rem; }
    .summary-item { padding: 0.75rem; }
    .pricing-box { padding: 1.5rem; }
}
</style>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('main_content'); ?>
<div class="main-content">
    <div class="page-content">
        <div class="container-fluid">
            <div class="p-2 pb-0">

                <!-- 🛒 خلاصه سفارش -->
                <div class="order-summary-card">
                    <h4><i class="ri-shopping-cart-line"></i> خلاصه سفارش شما</h4>
                    <div class="row g-3">
                        <div class="col-lg-3 col-md-6 col-6">
                            <div class="summary-item">
                                <h6><i class="ri-cpu-line"></i> منابع</h6>
                                <span id="selected-resources">انتخاب نشده</span>
                            </div>
                        </div>
                        <div class="col-lg-3 col-md-6 col-6">
                            <div class="summary-item">
                                <h6><i class="ri-map-pin-line"></i> موقعیت</h6>
                                <span id="selected-location">انتخاب نشده</span>
                            </div>
                        </div>
                        <div class="col-lg-3 col-md-6 col-6">
                            <div class="summary-item">
                                <h6><i class="ri-server-line"></i> پلن</h6>
                                <span id="selected-package">انتخاب نشده</span>
                            </div>
                        </div>
                        <div class="col-lg-3 col-md-6 col-6">
                            <div class="summary-item">
                                <h6><i class="ri-disc-line"></i> سیستم‌عامل</h6>
                                <span id="selected-image">انتخاب نشده</span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="content-show">
                    <input type="hidden" id="selectedProvider">
                    <input type="hidden" id="selectedPlanPrice" value="0">
                    <input type="hidden" id="selectedIPv4Price" value="250">

                    <!-- مرحله 1: منابع -->
                    <div id="step1Form" class="step-container">
                        <div class="step-header">
                            <h4><i class="ri-settings-3-line"></i> مرحله 1: انتخاب منابع</h4>
                        </div>
                        <?php echo csrf_field(); ?>
                        <div class="row mt-4 justify-content-center">
                            <div class="col-12 text-center mb-3"><h5>سیستم‌عامل:</h5></div>
                            <div class="col-lg-3 col-md-4 col-6 mb-3">
                                <div class="form-check card-radio">
                                    <input id="os1" name="os" type="radio" value="linux" class="form-check-input" checked>
                                    <label class="form-check-label btn btn-outline-primary w-100" for="os1">
                                        <i class="ri-ubuntu-fill" style="font-size: 2rem;"></i>
                                        <div class="mt-2"><strong>لینوکس</strong></div>
                                    </label>
                                </div>
                            </div>
                            <div class="col-lg-3 col-md-4 col-6 mb-3">
                                <div class="form-check card-radio">
                                    <input id="os2" name="os" type="radio" value="windows" class="form-check-input" disabled>
                                    <label class="form-check-label btn btn-outline-secondary w-100" for="os2">
                                        <i class="ri-windows-fill" style="font-size: 2rem;"></i>
                                        <div class="mt-2"><strong>ویندوز</strong><br><small>(به زودی)</small></div>
                                    </label>
                                </div>
                            </div>
                        </div>

                        <div class="row mt-5 justify-content-center">
                            <div class="col-12 text-center mb-3"><h5>نوع منابع:</h5></div>
                            <div class="col-lg-3 col-md-4 col-6 mb-3">
                                <div class="form-check card-radio">
                                    <input id="resources1" name="resources" type="radio" value="shared" class="form-check-input" checked>
                                    <label class="form-check-label btn btn-outline-primary w-100" for="resources1">
                                        <i class="ri-group-fill" style="font-size: 2rem;"></i>
                                        <div class="mt-2"><strong class="resources-name">اشتراکی</strong></div>
                                    </label>
                                </div>
                            </div>
                            <div class="col-lg-3 col-md-4 col-6 mb-3">
                                <div class="form-check card-radio">
                                    <input id="resources2" name="resources" type="radio" value="dedicated" class="form-check-input">
                                    <label class="form-check-label btn btn-outline-primary w-100" for="resources2">
                                        <i class="ri-server-fill" style="font-size: 2rem;"></i>
                                        <div class="mt-2"><strong class="resources-name">اختصاصی</strong></div>
                                    </label>
                                </div>
                            </div>
                        </div>

                        <div class="text-center mt-5">
                            <button id="nextToLocation" type="button" class="btn btn-primary btn-lg">
                                مرحله بعد: انتخاب موقعیت <i class="ri-arrow-right-line ms-2"></i>
                            </button>
                        </div>
                    </div>

                    <!-- مرحله 2: موقعیت -->
                    <div id="step2Location" class="step-container" style="display:none;">
                        <div class="step-header">
                            <h4><i class="ri-map-pin-2-line"></i> مرحله 2: انتخاب موقعیت</h4>
                            <button id="backToResources" type="button" class="btn btn-danger btn-sm">
                                <i class="ri-arrow-left-line me-2"></i> مرحله قبل
                            </button>
                        </div>
                        <div id="locationsContent"><p class="text-center">در حال بارگذاری موقعیت‌ها...</p></div>
                    </div>

                    <!-- مرحله 3: پلن -->
                    <div id="step3Plans" class="step-container" style="display:none;">
                        <div class="step-header">
                            <h4><i class="ri-stack-line"></i> مرحله 3: انتخاب پلن</h4>
                            <button type="button" class="btn btn-danger btn-sm" id="backToLocation">
                                <i class="ri-arrow-left-line me-2"></i> مرحله قبل
                            </button>
                        </div>
                        
                        <ul class="nav nav-tabs justify-content-center mb-4" id="plansTab" role="tablist" style="display:none;">
                            <li class="nav-item" role="presentation">
                                <button class="nav-link active" id="small-tab" data-bs-toggle="tab" data-bs-target="#small" type="button">کوچک</button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="medium-tab" data-bs-toggle="tab" data-bs-target="#medium" type="button">متوسط</button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="large-tab" data-bs-toggle="tab" data-bs-target="#large" type="button">بزرگ</button>
                            </li>
                        </ul>
                        <div class="tab-content" id="plansTabContent" style="display:none;">
                            <div class="tab-pane fade show active" id="small"></div>
                            <div class="tab-pane fade" id="medium"></div>
                            <div class="tab-pane fade" id="large"></div>
                        </div>
                        <div id="plansContent" class="row justify-content-center gx-3 gy-3"></div>
                    </div>

                    <!-- مرحله 4: سیستم‌عامل -->
                    <div id="step4Images" class="step-container" style="display:none;">
                        <div class="step-header">
                            <h4><i class="ri-disc-line"></i> مرحله 4: انتخاب سیستم‌عامل</h4>
                            <button type="button" class="btn btn-danger btn-sm" id="backToPlans">
                                <i class="ri-arrow-left-line me-2"></i> مرحله قبل
                            </button>
                        </div>
                        <div id="imagesContent" class="row justify-content-center gx-3 gy-3">
                            <p class="text-center">در حال بارگذاری...</p>
                        </div>
                    </div>

                    <!-- ✅ مرحله 5: جزئیات قیمت و تایید -->
                    <div id="step5Pricing" class="step-container" style="display:none;">
                        <div class="step-header">
                            <h4><i class="ri-shopping-bag-line"></i> مرحله 5: تایید نهایی و پرداخت</h4>
                            <button type="button" class="btn btn-danger btn-sm" id="backToImages">
                                <i class="ri-arrow-left-line me-2"></i> مرحله قبل
                            </button>
                        </div>

                        <!-- 💰 باکس قیمت -->
                        <div class="pricing-box">
                            <h5><i class="ri-money-dollar-circle-line"></i> جزئیات قیمت</h5>
                            <div class="price-item">
                                <span class="price-label"><i class="ri-server-line"></i> هزینه سرور (ساعتی)</span>
                                <span class="price-value" id="serverPriceDisplay">0 تومان</span>
                            </div>
                            <div class="price-item">
                                <span class="price-label"><i class="ri-global-line"></i> هزینه IPv4 Primary (ساعتی)</span>
                                <span class="price-value" id="ipv4PriceDisplay">250 تومان</span>
                            </div>
                            <div class="price-item">
                                <span class="price-label"><i class="ri-global-line"></i> IPv6 (رایگان)</span>
                                <span class="price-value">0 تومان</span>
                            </div>
                            <div class="price-item">
                                <span class="price-label"><i class="ri-flashlight-line"></i> جمع کل (ساعتی)</span>
                                <span class="price-value" id="totalPriceDisplay">0 تومان</span>
                            </div>
                            <div class="text-center mt-4">
                                <button id="createVM" class="btn btn-success btn-lg">
                                    <span class="default-text"><i class="ri-rocket-line me-2"></i> ساخت سرور</span>
                                    <span class="loading-text d-none"><i class="ri-loader-4-line spin"></i> در حال ایجاد...</span>
                                </button>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
        </div>
    </div>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('scripts'); ?>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
let dollarRate = 111000;
let euroRate = 165000;
let projectId = <?php echo e($project->id); ?>;
let arvanPlans = [];
let vultrPlans = [];
let hetznerPlans = [];
let hetznerLocations = [];
let hetznerImages = [];
let locationsData = {};
let parspackPlans = [];

// ✅ آیکون‌های سیستم‌عامل
const osIcons = {
    'ubuntu': 'https://assets.ubuntu.com/v1/29985a98-ubuntu-logo32.png',
    'debian': 'https://www.debian.org/logos/openlogo-nd-50.png',
    'centos': 'https://upload.wikimedia.org/wikipedia/commons/6/63/CentOS_color_logo.svg',
    'rocky': 'https://rockylinux.org/images/rocky-linux-icon.svg',
    'fedora': 'https://upload.wikimedia.org/wikipedia/commons/3/3f/Fedora_logo.svg',
    'almalinux': 'https://almalinux.org/images/icon.svg',
    'arch': 'https://archlinux.org/static/logos/archlinux-icon-crystal-64.svg',
    'windows': 'https://upload.wikimedia.org/wikipedia/commons/5/5f/Windows_logo_-_2012.svg',
    'default': 'https://cdn-icons-png.flaticon.com/512/888/888879.png'
};

function getOSIcon(osName) {
    osName = (osName || '').toLowerCase();
    for (let key in osIcons) {
        if (osName.includes(key)) return osIcons[key];
    }
    return osIcons.default;
}

function decodeUnicodeEscapes(str){
    if(!str || typeof str !== 'string') return str;
    try{
        return str.replace(/\\u([0-9a-fA-F]{4})/g, function(_, grp){
            return String.fromCharCode(parseInt(grp, 16));
        });
    }catch(e){ return str; }
}

function showToast(message, type='error'){
    const toastEl = $('#vmToast');
    toastEl.removeClass('toast-custom toast-custom-success');
    if(type === 'success') toastEl.addClass('toast-custom-success');
    else toastEl.addClass('toast-custom');
    let decoded = decodeUnicodeEscapes(String(message));
    try{ decoded = decodeUnicodeEscapes(decoded); }catch(e){}
    $('#vmToastBody').text(decoded);
    new bootstrap.Toast(toastEl[0]).show();
}

// ✅ تابع به‌روزرسانی قیمت
function updatePricing() {
    let serverPrice = parseInt($('#selectedPlanPrice').val()) || 0;
    let provider = $('#selectedProvider').val();
    
    // ✅ برای آروان IPv4 رایگان است
    let ipv4Price = 0;
    if (provider === 'hetzner') {
        ipv4Price = 250; // فقط هتزنر IPv4 هزینه داره
    }
    // والتر و آروان IPv4 رایگان دارن (شامل پلن)
    
    let totalPrice = serverPrice + ipv4Price;
    
    $('#serverPriceDisplay').text(serverPrice.toLocaleString() + ' تومان');
    
    // ✅ نمایش متفاوت برای IPv4
    if (ipv4Price > 0) {
        $('#ipv4PriceDisplay').text(ipv4Price.toLocaleString() + ' تومان');
    } else {
        $('#ipv4PriceDisplay').html('<strong class="text-success">رایگان (شامل پلن)</strong>');
    }
    
    $('#totalPriceDisplay').text(totalPrice.toLocaleString() + ' تومان');
}

// ✅ Hetzner Plans
function loadHetznerPlans(regionId) {
    $('#plansTab').hide();
    $('#plansTabContent').hide();
    $('#plansContent').show();
    $('#plansContent').html('<p class="text-center"><i class="ri-loader-4-line spin"></i> در حال بارگذاری...</p>');
    
    fetch('/cloud/hetzner/plans')
    .then(res => res.json())
    .then(data => {
        if(data.status === 'success' && Array.isArray(data.plans)) {
            hetznerPlans = data.plans.filter(plan =>
                plan.deprecated === false &&
                Array.isArray(plan.prices) &&
                plan.prices.some(p => p.location === regionId) &&
                Array.isArray(plan.locations) &&
                plan.locations.some(l => l.name === regionId)
            );

            hetznerPlans = hetznerPlans.sort((a, b) => {
                let pa = (a.prices || []).find(p => p.location === regionId);
                let pb = (b.prices || []).find(p => p.location === regionId);
                let priceA = pa && pa.price_hourly && pa.price_hourly.net ? parseFloat(pa.price_hourly.net) : 0;
                let priceB = pb && pb.price_hourly && pb.price_hourly.net ? parseFloat(pb.price_hourly.net) : 0;
                return priceA - priceB;
            });

            let html = '';
            hetznerPlans.forEach(plan => {
                let priceObj = (plan.prices || []).find(p => p.location === regionId);
                let hourlyEuro = priceObj && priceObj.price_hourly && priceObj.price_hourly.net ? parseFloat(priceObj.price_hourly.net) : 0;
                
                let priceToman = hourlyEuro * euroRate;
                let priceWithProfit = Math.round(priceToman * 1.25);
                let ipv4Cost = 250;
                let serverOnlyPrice = priceWithProfit - ipv4Cost;
                
                let archLabel = plan.architecture === 'arm' ? 'ARM' : 'x64';
                let catLabel = plan.category === 'cost_optimized' ? '<span class="badge bg-warning ms-1">Cost Optimized</span>' : '';
                
                html += `
                <div class="col-lg-4 col-md-6 mb-3">
                    <div class="form-check card-radio">
                        <input type="radio" class="btn-check" name="plans" id="plan-${plan.name}" value="${plan.name}" data-price="${serverOnlyPrice}">
                        <label class="btn btn-outline-primary w-100 text-start" for="plan-${plan.name}">
                            <div class="d-flex justify-content-between align-items-start mb-2">
                                <div>
                                    <strong style="font-size: 1.1rem;">${plan.description || plan.name}</strong>
                                    <div class="mt-1">
                                        <span class="badge bg-secondary">${archLabel}</span>
                                        ${catLabel}
                                    </div>
                                </div>
                                <div class="text-end">
                                    <div class="text-success fw-bold">${serverOnlyPrice.toLocaleString()}</div>
                                    <small class="text-muted">تومان/ساعت</small>
                                </div>
                            </div>
                            <div class="text-muted small">
                                <i class="ri-cpu-line"></i> ${plan.cores} Core
                                <span class="mx-2">|</span>
                                <i class="ri-hard-drive-line"></i> ${plan.memory}GB RAM
                                <span class="mx-2">|</span>
                                <i class="ri-database-line"></i> ${plan.disk}GB
                            </div>
                            <div class="mt-2 pt-2 border-top">
                                <small class="text-muted">
                                    <i class="ri-information-line"></i> 
                                    ماهانه: ${(serverOnlyPrice * 730).toLocaleString()} تومان
                                </small>
                            </div>
                        </label>
                    </div>
                </div>
                `;
            });
            $('#plansContent').html(html);
        } else {
            $('#plansContent').html('<p class="text-danger text-center">پلنی یافت نشد.</p>');
        }
    });
}

// ✅ Hetzner Images
function loadHetznerImages(){
    $('#step3Plans').hide();
    $('#step4Images').show();
    $('#imagesContent').html('<p class="text-center"><i class="ri-loader-4-line spin"></i> در حال بارگذاری...</p>');
    fetch('/cloud/hetzner/images')
    .then(res => res.json())
    .then(data => {
        if(data.status === 'success' && Array.isArray(data.images)) {
            hetznerImages = data.images;
            let html = '';
            hetznerImages.forEach(img => {
                let osName = img.description || img.name;
                let iconUrl = getOSIcon(osName);
                
                html += `
                <div class="col-lg-2 col-md-3 col-sm-4 col-6 mb-3">
                    <div class="form-check card-radio os-card">
                        <input type="radio" class="btn-check" name="images" id="img-${img.id}" value="${img.id}">
                        <label class="btn btn-outline-primary w-100 text-center" for="img-${img.id}">
                            <img src="${iconUrl}" alt="${osName}" class="os-icon" onerror="this.src='${osIcons.default}'">
                            <div class="mt-1 os-name">${osName}</div>
                        </label>
                    </div>
                </div>`;
            });
            $('#imagesContent').html(html);
        } else {
            $('#imagesContent').html('<p class="text-danger text-center">سیستم‌عاملی یافت نشد</p>');
        }
    });
}

// ✅ Vultr Plans
function loadVultrPlans(regionId) {
    $('#plansContent').hide();
    $('#plansTab').show();
    $('#plansTabContent').show();
    $('#small').html('<p class="text-center">در حال بارگذاری پلن‌ها...</p>');
    $('#medium').html('');
    $('#large').html('');
    
    fetch(`/cloud/vultr/plans/${regionId}`)
    .then(res => res.json())
    .then(data => {
        if(data.status === 'success' && data.plans.length > 0) {
            vultrPlans = data.plans;
            let small = [], medium = [], large = [];
            data.plans.forEach(plan => {
                let ram = plan.ram ?? plan.memory ?? 0;
                let cpu = plan.vcpu_count ?? plan.vcpu ?? 0;
                if(cpu <= 1 && ram <= 1024) small.push(plan);
                else if(cpu <= 2 && ram <= 4096) medium.push(plan);
                else large.push(plan);
            });
            renderPlanTabVultr('small', small, 'primary');
            renderPlanTabVultr('medium', medium, 'success');
            renderPlanTabVultr('large', large, 'danger');
        } else {
            $('#small').html('<p class="text-danger text-center">پلنی یافت نشد</p>');
        }
    });
}

function renderPlanTabVultr(tabId, plans, btnColor){
    let html = '<div class="row justify-content-center">';
    plans.forEach(plan=>{
        let ram = plan.ram ?? plan.memory ?? 0;
        let cpu = plan.vcpu_count ?? plan.vcpu ?? '-';
        let disk = plan.disk ?? '-';
        let monthly = Number(plan.monthly_cost ?? plan.price_per_month ?? 0);
        let hourly = Number(plan.hourly_cost ?? 0);

        let markupMonthlyUSD = Math.round(monthly * 1.3 * 100) / 100;
        let markupHourlyUSD = Math.round(hourly * 1.3 * 10000) / 10000;
        let monthlyToman = Math.round(markupMonthlyUSD * dollarRate);
        let hourlyToman = Math.round(markupHourlyUSD * dollarRate);

        html += `
        <div class="col-12 col-md-6 col-lg-5 mb-3">
            <div class="form-check card-radio">
                <input type="radio" class="btn-check" name="plans" id="plan-${plan.id}" value="${plan.id}" data-price="${hourlyToman}">
                <label class="btn btn-outline-${btnColor} w-100 text-start" for="plan-${plan.id}">
                    <div>
                        <strong>${plan.description || plan.id}</strong>
                        <span class="text-muted ms-2">| رم: ${ram ? (ram/1024) : '-'}GB | CPU: ${cpu} | دیسک: ${disk}GB</span>
                    </div>
                    <div class="small mt-1">
                        <span>ماهانه: <b>${monthlyToman.toLocaleString()} تومان</b></span>
                        <span class="ms-2">ساعتی: <b>${hourlyToman.toLocaleString()} تومان</b></span>
                    </div>
                </label>
            </div>
        </div>
        `;
    });
    html += '</div>';
    $('#' + tabId).html((plans.length ? html : '<p class="text-center">پلنی یافت نشد.</p>'));
}

function loadVultrImages(){
    $('#step3Plans').hide();
    $('#step4Images').show();
    $('#imagesContent').html('<p class="text-center">در حال بارگذاری سیستم عامل‌ها...</p>');
    fetch('/cloud/vultr/images')
    .then(res => res.json())
    .then(data => {
        if(data.status === 'success' && data.images.length > 0){
            let html = '';
            data.images.forEach(img => {
                let osName = img.name || img.id;
                let iconUrl = getOSIcon(osName);
                
                html += `
                <div class="col-lg-2 col-md-3 col-sm-4 col-6 mb-3">
                    <div class="form-check card-radio os-card">
                        <input type="radio" class="btn-check" name="images" id="img-${img.id}" value="${img.id}">
                        <label class="btn btn-outline-primary w-100 text-center" for="img-${img.id}">
                            <img src="${iconUrl}" alt="${osName}" class="os-icon" onerror="this.src='${osIcons.default}'">
                            <div class="mt-1 os-name">${osName}</div>
                        </label>
                    </div>
                </div>`;
            });
            $('#imagesContent').html(html);
        } else {
            $('#imagesContent').html('<p class="text-danger text-center">سیستم‌عاملی یافت نشد</p>');
        }
    });
}

// ✅ Arvan Plans
function loadArvanPlans(regionCode, regionName) {
    $('#plansContent').hide();
    $('#plansTab').show();
    $('#plansTabContent').show();
    $('#small').html('<p class="text-center">در حال بارگذاری پلن‌ها...</p>');
    $('#medium').html('');
    $('#large').html('');
    
    fetch('/cloud/arvan/plans/' + regionCode)
    .then(res => res.json())
    .then(data => {
        if(data.status === 'success' && (data.plans || []).length > 0){
            arvanPlans = data.plans;
            let small = [], medium = [], large = [];
            data.plans.forEach(plan => {
                if(/small|eco-1|nano|micro/i.test(plan.id) || /small/i.test(plan.name)) small.push(plan);
                else if(/medium|eco-2/i.test(plan.id) || /medium/i.test(plan.name)) medium.push(plan);
                else large.push(plan);
            });
            renderPlanTabArvan('small', small, 'primary');
            renderPlanTabArvan('medium', medium, 'success');
            renderPlanTabArvan('large', large, 'danger');
        } else {
            $('#small').html('<p class="text-danger text-center">پلنی یافت نشد</p>');
        }
    });
}

function renderPlanTabArvan(tabId, plans, btnColor){
    let html = '<div class="row justify-content-center">';
    plans.forEach(plan=>{
        let priceMonthlyRial = plan.price_per_month || 0;
        let priceMonthlyWithProfit = Math.round(priceMonthlyRial * 1.2);
        let priceMonthlyToman = Math.round(priceMonthlyWithProfit / 10);

        let priceHourlyRial = plan.price_per_hour || 0;
        let priceHourlyWithProfit = Math.round(priceHourlyRial * 1.2);
        let priceHourlyToman = Math.round(priceHourlyWithProfit / 10);

        html += `
        <div class="col-12 col-md-6 col-lg-5 mb-3">
            <div class="form-check card-radio">
                <input type="radio" class="btn-check" name="plans" id="plan-${plan.id}" value="${plan.id}" data-price="${priceHourlyToman}">
                <label class="btn btn-outline-${btnColor} w-100 text-start" for="plan-${plan.id}">
                    <div>
                        <strong>${plan.name || plan.id}</strong>
                        <span class="text-muted ms-2">| رم: ${plan.memory || '-'}GB | CPU: ${plan.cpu_count || '-'} | دیسک: ${plan.disk || '-'}GB</span>
                    </div>
                    <div class="small mt-1">
                        <span>ماهانه: <b>${priceMonthlyToman.toLocaleString()} تومان</b></span>
                        <span class="text-muted mx-2">|</span>
                        <span>ساعتی: <b>${priceHourlyToman.toLocaleString()} تومان</b></span>
                    </div>
                </label>
            </div>
        </div>`;
    });
    html += '</div>';
    $('#' + tabId).html((plans.length ? html : '<p class="text-center">پلنی یافت نشد.</p>'));
}

function loadArvanImages(regionCode) {
    $('#step3Plans').hide();
    $('#step4Images').show();
    $('#imagesContent').html('<p class="text-center">در حال بارگذاری تصاویر...</p>');
    fetch('/cloud/arvan/images/' + regionCode)
    .then(res => res.json())
    .then(data => {
        if(data.status === 'success' && (data.images || []).length > 0){
            let html = '';
            data.images.forEach(group => {
                if(!group.display) return;
                html += `<div class="col-12"><h6 class="border-bottom pb-1">${group.name}</h6></div>`;
                (group.images || []).forEach(img => {
                    let osName = group.name + ' ' + img.name;
                    let iconUrl = getOSIcon(osName);
                    
                    html += `
                    <div class="col-lg-2 col-md-3 col-sm-4 col-6 mb-3">
                        <div class="form-check card-radio os-card">
                            <input type="radio" class="btn-check" name="images" id="img-${img.id}" value="${img.id}">
                            <label class="btn btn-outline-primary w-100 text-center" for="img-${img.id}">
                                <img src="${iconUrl}" alt="${osName}" class="os-icon" onerror="this.src='${osIcons.default}'">
                                <div class="mt-1 os-name">${osName}</div>
                            </label>
                        </div>
                    </div>`;
                });
            });
            $('#imagesContent').html(html);
        } else {
            $('#imagesContent').html('<p class="text-danger text-center">تصویری یافت نشد</p>');
        }
    });
}

// ✅ OneProvider Plans
function loadOneProviderPlans(regionId) {
    $('#plansTab').hide();
    $('#plansTabContent').hide();
    $('#plansContent').show();
    $('#plansContent').html('<p class="text-center">در حال بارگذاری پلن‌ها ...</p>');

    fetch('/cloud/oneprovider/locations')
    .then(res => res.json())
    .then(locData => {
        let allLocations = [];
        Object.values(locData.response || {}).forEach(arr => { allLocations = allLocations.concat(arr); });
        let selectedLocation = allLocations.find(loc => String(loc.id) === String(regionId));
        let allowedSizeIds = (selectedLocation && Array.isArray(selectedLocation.available_sizes)) ? selectedLocation.available_sizes.map(String) : [];

        if(!allowedSizeIds.length) {
            $('#plansContent').html('<p class="text-danger text-center">در این موقعیت هیچ پلنی فعال نیست.</p>');
            return;
        }

        fetch('/cloud/oneprovider/plans')
        .then(res => res.json())
        .then(data => {
            if(data.response && Array.isArray(data.response)) {
                const plans = data.response.filter(plan =>
                    allowedSizeIds.includes(String(plan.id)) && String(plan.id) !== "69"
                );
                let html = '';
                plans.forEach(plan => {
                    let price = plan.hourly_price || 0;
                    let monthly = plan.monthly_price || 0;
                    let ram = plan.ram || plan.memory || '-';
                    let cpu = plan.cores || '-';
                    let disk = plan.hdd || plan.disk || '-';
                    
                    let hourlyToman = Math.round(price * euroRate * 1.25);
                    let monthlyToman = Math.round(monthly * euroRate * 1.25);
                    
                    html += `
                        <div class="col-md-4 col-sm-6 mb-2">
                            <div class="form-check card-radio">
                                <input type="radio" class="btn-check" name="plans" id="plan-${plan.id}" value="${plan.id}" data-price="${hourlyToman}">
                                <label class="btn btn-outline-primary w-100 text-start" for="plan-${plan.id}">
                                    <div>
                                        <strong>${plan.name || plan.id}</strong>
                                        <span class="text-muted ms-2">| رم: ${ram} | CPU: ${cpu} | دیسک: ${disk}GB</span>
                                    </div>
                                    <div class="small mt-1">
                                        <span>ماهانه: <b>${monthlyToman.toLocaleString()} تومان</b></span>
                                        <span class="ms-2">ساعتی: <b>${hourlyToman.toLocaleString()} تومان</b></span>
                                    </div>
                                </label>
                            </div>
                        </div>
                    `;
                });
                $('#plansContent').html(html || '<p class="text-danger text-center">در این موقعیت هیچ پلنی فعال نیست.</p>');
            } else {
                $('#plansContent').html('<p class="text-danger text-center">پلنی یافت نشد.</p>');
            }
        });
    });
}

function loadOneProviderImages(planId) {
    $('#step3Plans').hide();
    $('#step4Images').show();
    $('#imagesContent').html('<p class="text-center">در حال بارگذاری سیستم‌عامل‌ها...</p>');
    fetch('/cloud/oneprovider/images')
    .then(res => res.json())
    .then(data => {
        if(data.response && Array.isArray(data.response)) {
            let html = '';
            data.response.forEach(img => {
                let osName = img.display?.display || img.name;
                let iconUrl = getOSIcon(osName);
                
                html += `
                <div class="col-lg-2 col-md-3 col-sm-4 col-6 mb-3">
                    <div class="form-check card-radio os-card">
                        <input type="radio" class="btn-check" name="images" id="img-${img.id}" value="${img.id}">
                        <label class="btn btn-outline-primary w-100 text-center" for="img-${img.id}">
                            <img src="${iconUrl}" alt="${osName}" class="os-icon" onerror="this.src='${osIcons.default}'">
                            <div class="mt-1 os-name">${osName}</div>
                        </label>
                    </div>
                </div>`;
            });
            $('#imagesContent').html(html || '<p class="text-danger text-center">سیستم‌عاملی یافت نشد.</p>');
        } else {
            $('#imagesContent').html('<p class="text-danger text-center">سیستم‌عاملی یافت نشد.</p>');
        }
    });
}

$(document).ready(function(){

    $('input[name="resources"]').change(function(){
        $('#selected-resources').text($(this).next('label').find('.resources-name').text().trim());
    });
    
    $('#selected-resources').text('اشتراکی');

$('#nextToLocation').click(function(){
    $('#step1Form').hide();
    $('#step2Location').show();
    $('#locationsContent').html('<p class="text-center">در حال دریافت موقعیت‌ها...</p>');

    fetch('/cloud/locations/all')
    .then(r => r.json())
    .then(({vultr, arvan, parspack, parspack_plans}) => {
        parspackPlans = parspack_plans || [];
        arvanPlans = [];
        vultrPlans = [];
        hetznerPlans = [];
        hetznerLocations = [];
        hetznerImages = [];
        locationsData = {};

        if(vultr.regions && Array.isArray(vultr.regions)) {
            vultr.regions.forEach(loc => {
                let continent = loc.continent || 'Other';
                if(!locationsData[continent]) locationsData[continent] = [];
                locationsData[continent].push({
                    id: loc.id,
                    city: loc.city,
                    country_code: loc.country,
                    provider: 'vultr'
                });
            });
        }

        if(arvan.data && Array.isArray(arvan.data)) {
            arvan.data.forEach(loc => {
                if(loc.country === 'Iran') {
                    if(!locationsData['Asia']) locationsData['Asia'] = [];
                    let cityLat = loc.city + (loc.dc ? ' - ' + loc.dc : '');
                    locationsData['Asia'].push({
                        id: loc.code,
                        city: cityLat,
                        country_code: 'IR',
                        provider: 'arvan'
                    });
                }
            });
        }

        Promise.all([
            fetch('/cloud/hetzner/locations').then(res => res.json()),
            fetch('/cloud/oneprovider/locations').then(res => res.json())
        ])
        .then(([hetzData, oneData]) => {
            if(hetzData.status === 'success' && Array.isArray(hetzData.locations)) {
                hetzData.locations.forEach(loc => {
                    let continent = 'Europe';
                    if(['ash', 'hil'].includes(loc.name)) continent = 'North America';
                    if(['sin'].includes(loc.name)) continent = 'Asia';
                    if(!locationsData[continent]) locationsData[continent] = [];
                    locationsData[continent].push({
                        id: loc.name,
                        city: loc.city,
                        country_code: loc.country,
                        provider: 'hetzner',
                        regionName: loc.name
                    });
                });
            }

            const allowedOneProvider = [
                { country: 'PK', code: 'pk', city: 'Islamabad', continent: 'Asia', display: 'IslamAbad Pakistan (High Price)' },
                { country: 'TR', code: 'tr', city: 'Istanbul', continent: 'Asia', display: 'Izmir Turkey (High Price)' },
                { country: 'AE', code: 'ae', city: 'Dubai', continent: 'Asia', display: 'Dubai (Limited)' }
            ];
            if(oneData.response && oneData.response.Asia) {
                oneData.response.Asia.forEach(loc => {
                    let found = allowedOneProvider.find(target =>
                        loc.country === target.country && loc.city === target.city
                    );
                    if(found) {
                        if(!locationsData[found.continent]) locationsData[found.continent] = [];
                        locationsData[found.continent].push({
                            id: loc.id,
                            city: found.display,
                            country_code: found.code,
                            provider: 'oneprovider'
                        });
                    }
                });
            }

            let continents = Object.keys(locationsData);
            if(continents.length === 0) {
                $('#locationsContent').html('<p class="text-danger text-center">موقعیتی یافت نشد</p>');
                return;
            }

            let navTabs = '<ul class="nav nav-pills mb-4 justify-content-center" id="continentTabs" role="tablist">';
            let tabContent = '<div class="tab-content" id="continentTabsContent">';
            let first = true;
            continents.forEach(continent => {
                let continentId = continent.replace(/\s+/g, '-');
                navTabs += `
                    <li class="nav-item" role="presentation">
                        <button class="nav-link${first ? ' active' : ''}" id="${continentId}-tab"
                            data-bs-toggle="tab" data-bs-target="#${continentId}-tab-pane"
                            type="button" role="tab">${continent}</button>
                    </li>
                `;
                tabContent += `<div class="tab-pane fade${first ? ' show active' : ''}" id="${continentId}-tab-pane" role="tabpanel">`;

                tabContent += `<div class="row justify-content-center g-3 mb-4">`;
                locationsData[continent].forEach(loc => {
                    tabContent += `
                        <div class="col-auto">
                            <div class="form-check card-radio">
                                <input type="radio" class="btn-check" name="location_radio"
                                       id="region_${loc.provider}_${loc.id}" value="${loc.id}"
                                       data-provider="${loc.provider}"
                                       ${loc.sizes ? `data-sizes='${JSON.stringify(loc.sizes)}'` : ''} 
                                       ${loc.regionName ? `data-region="${loc.regionName}"` : ''}>
                                <label class="btn btn-outline-primary d-flex align-items-center px-3 py-2" for="region_${loc.provider}_${loc.id}">
                                    <img src="/assets/flags/${(loc.country_code || '').toLowerCase()}.svg" alt="${loc.country_code}" width="28" class="me-2">
                                    <span class="fw-bold">${loc.city}</span>
                                    ${loc.provider === 'hetzner' ? '<span class="badge bg-info ms-2">Hetzner</span>' : ''}
                                </label>
                            </div>
                        </div>
                    `;
                });
                tabContent += `</div></div>`;
                first = false;
            });
            navTabs += `</ul>`;
            tabContent += `</div>`;
            $('#locationsContent').html(navTabs + tabContent);

// ✅ اصلاح: پاک کردن داده‌های قبلی + بارگذاری صحیح
$(document).off('change', 'input[name="location_radio"]').on('change', 'input[name="location_radio"]', function(){
    let provider = $(this).data('provider');
    $('#selectedProvider').val(provider);
    let city = $(this).closest('.card-radio').find('span.fw-bold').text();
    $('#selected-location').text(city);

    let regionId = $(this).val();
    
    // ✅ پاک کردن پلن‌ها و ایمیج‌های قبلی
    $('#plansContent').html('');
    $('#imagesContent').html('');
    $('#small').html('');
    $('#medium').html('');
    $('#large').html('');
    
    // ✅ Reset کردن متغیرها
    arvanPlans = [];
    vultrPlans = [];
    hetznerPlans = [];
    hetznerImages = [];
    
    $('#step2Location').hide();
    $('#step3Plans').show();

    if(provider === 'hetzner') {
        loadHetznerPlans(regionId);
    } else if(provider === 'vultr') {
        loadVultrPlans(regionId);
    } else if(provider === 'arvan') {
        loadArvanPlans(regionId, city);
    } else if(provider === 'oneprovider') {
        loadOneProviderPlans(regionId);
    }
});
        });
    }).catch(err => {
        $('#locationsContent').html('<p class="text-danger text-center">خطا در دریافت موقعیت‌ها</p>');
    });
});

$('#backToResources').click(()=>{ $('#step2Location').hide(); $('#step1Form').show(); });
$('#backToLocation').click(()=>{ $('#step3Plans').hide(); $('#step2Location').show(); });
$('#backToPlans').click(()=>{ $('#step4Images').hide(); $('#step3Plans').show(); });
$('#backToImages').click(()=>{ $('#step5Pricing').hide(); $('#step4Images').show(); });

// ✅ انتخاب پلن
$(document).on('change', 'input[name="plans"]', function(){
    let provider = $('#selectedProvider').val();
    let planId = $(this).val();
    $('#selected-package').text(planId);
    
    let planPrice = parseInt($(this).data('price')) || 0;
    $('#selectedPlanPrice').val(planPrice);
    
    if(provider === 'hetzner') {
        loadHetznerImages();
    } else if(provider === 'vultr') {
        loadVultrImages();
    } else if(provider === 'arvan') {
        loadArvanImages($('input[name="location_radio"]:checked').val());
    } else if(provider === 'oneprovider') {
        loadOneProviderImages(planId);
    }
});

// ✅ انتخاب سیستم‌عامل → مستقیم برو به قیمت
$(document).on('change', 'input[name="images"]', function(){
    let osNameText = $(this).next('label').find('.os-name').text().trim();
    if(!osNameText) osNameText = $(this).next('label').text().trim();
    $('#selected-image').text(osNameText);
    
    // ✅ به‌روزرسانی قیمت و رفتن به مرحله 5
    updatePricing();
    $('#step4Images').hide();
    $('#step5Pricing').show();
});

// ✅ ساخت سرور
$(document).on('click', '#createVM', function(){
    let btn = $(this);
    let defaultText = btn.find('.default-text');
    let loadingText = btn.find('.loading-text');
    btn.prop('disabled', true);
    defaultText.addClass('d-none');
    loadingText.removeClass('d-none');

    let provider = $('#selectedProvider').val();
    let region = $('input[name="location_radio"]:checked').val();
    let plan = $('input[name="plans"]:checked').val();
    let image = $('input[name="images"]:checked').val();
    let payload = {};
    let url = '';

    if(provider === 'arvan') {
        let selectedPlan = arvanPlans.find(p => p.id === plan);
        let diskSize = selectedPlan ? selectedPlan.disk : null;
        if(!region || !plan || !image || !diskSize) {
            showToast('همه گزینه‌ها را انتخاب کنید!');
            btn.prop('disabled', false);
            loadingText.addClass('d-none');
            defaultText.removeClass('d-none');
            return;
        }
        payload = {
            provider: provider,
            region: region,
            plan: plan,
            image: image,
            disk_size: diskSize
        };
        url = '/cloud/arvan/vms/' + projectId;
    } else if(provider === 'vultr') {
        if(!region || !plan || !image) {
            showToast('همه گزینه‌ها را انتخاب کنید!');
            btn.prop('disabled', false);
            loadingText.addClass('d-none');
            defaultText.removeClass('d-none');
            return;
        }
        payload = {
            provider: provider,
            region: region,
            plan: plan,
            os_id: image,
            label: 'vultr-' + Math.random().toString(36).substring(2,8)
        };
        url = '/cloud/vultr/vms/' + projectId;
    } else if(provider === 'hetzner') {
        if(!region || !plan || !image) {
            showToast('همه گزینه‌ها را انتخاب کنید!');
            btn.prop('disabled', false);
            loadingText.addClass('d-none');
            defaultText.removeClass('d-none');
            return;
        }
        payload = {
            name: 'hetzner-' + Math.random().toString(36).substring(2,8),
            location: region,
            server_type: plan,
            image: image
        };
        url = '/cloud/hetzner/vms/' + projectId;
    } else if(provider === 'oneprovider') {
        if(!region || !plan || !image) {
            showToast('همه گزینه‌ها را انتخاب کنید!');
            btn.prop('disabled', false);
            loadingText.addClass('d-none');
            defaultText.removeClass('d-none');
            return;
        }
        payload = {
            location_id: String(region),
            instance_size: String(plan),
            template: String(image),
            hostname: 'oneprovider-' + Math.random().toString(36).substring(2,8)
        };
        url = '/cloud/oneprovider/vms/' + projectId;
    } else {
        showToast('خطا: provider نامعتبر است!');
        btn.prop('disabled', false);
        loadingText.addClass('d-none');
        defaultText.removeClass('d-none');
        return;
    }

    $.ajax({
        url: url,
        type: 'POST',
        data: JSON.stringify(payload),
        contentType: 'application/json',
        headers: {'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>'},
        success: function(res){
            showToast(res.message || 'درخواست ساخت سرور با موفقیت ارسال شد!', res.status === 'success' ? 'success' : 'danger');
            if(res.status === 'success'){
                setTimeout(function(){
                    window.location.href = '/cloud/projects/' + projectId + '/servers';
                }, 1200);
            }
        },
        error: function(jqXHR){
            let rawMsg = null;
            try{
                if(jqXHR.responseJSON && jqXHR.responseJSON.message) rawMsg = jqXHR.responseJSON.message;
                else {
                    let parsed = JSON.parse(jqXHR.responseText || '{}');
                    rawMsg = parsed.message || jqXHR.responseText;
                }
            } catch(e){ rawMsg = jqXHR.responseText || jqXHR.statusText; }
            rawMsg = String(rawMsg || 'خطا در ساخت سرور!');
            let decoded = decodeUnicodeEscapes(rawMsg);
            showToast(decoded, 'danger');
            console.error(jqXHR);
        },
        complete: function(){
            btn.prop('disabled', false);
            loadingText.addClass('d-none');
            defaultText.removeClass('d-none');
        }
    });
});

});
</script>

<!-- Toast -->
<div class="position-fixed top-0 end-0 p-3" style="z-index: 1100;">
    <div id="vmToast" class="toast align-items-center border-0" role="alert">
        <div class="d-flex">
            <div class="toast-body" id="vmToastBody">پیام</div>
            <button type="button" class="btn-close me-2 m-auto" data-bs-dismiss="toast"></button>
        </div>
    </div>
</div>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('layouts.simple.master', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /home/cloud/public_html/laravel-project/resources/views/servers/create.blade.php ENDPATH**/ ?>