

<?php $__env->startSection('title', 'مدیریت سرور - ' . $server->name); ?>

<?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">
<link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet" />
<style>
.sidebar-panel-main { display: none !important; }

/* ==================== Modern Server Management Styling ==================== */
body {
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
    font-family: 'Rubik', sans-serif;
}

.server-container {
    padding: 70px 0 30px;
}

/* Modern Tabs */
.modern-tabs {
    display: flex;
    gap: 6px;
    padding: 0;
    margin-bottom: 20px;
    list-style: none;
    flex-wrap: wrap;
    justify-content: flex-end;
}

.modern-tabs .nav-item {
    margin: 0;
}

.modern-tabs .nav-link {
    padding: 8px 18px;
    border-radius: 10px;
    border: 2px solid #e2e8f0;
    background: #fff;
    color: #4a5568;
    font-weight: 600;
    font-size: 13px;
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
    cursor: pointer;
}

.modern-tabs .nav-link::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 0;
    height: 100%;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    transition: width 0.3s ease;
    z-index: 0;
}

.modern-tabs .nav-link .tab-label {
    position: relative;
    z-index: 1;
}

.modern-tabs .nav-link:hover {
    border-color: #667eea;
    color: #667eea;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2);
}

.modern-tabs .nav-link.active {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-color: #667eea;
    color: #fff;
    box-shadow: 0 4px 16px rgba(102, 126, 234, 0.4);
}

.modern-tabs .nav-link.active::before {
    width: 100%;
}

/* Tab Content */
.tab-content-wrapper {
    background: #fff;
    border-radius: 16px;
    padding: 24px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.06);
}

/* Loading Spinner */
.tab-loading {
    text-align: center;
    padding: 40px 20px;
}

.spinner-modern {
    width: 40px;
    height: 40px;
    border: 3px solid #f3f4f6;
    border-top-color: #667eea;
    border-radius: 50%;
    animation: spin 0.8s linear infinite;
}

@keyframes spin {
    to { transform: rotate(360deg); }
}

/* Password Field */
.password-field {
    position: relative;
    font-family: 'Courier New', monospace;
    display: inline-block;
    padding: 4px 8px;
    background: #f7fafc;
    border-radius: 6px;
    font-size: 14px;
}

.password-field.blur {
    filter: blur(4px);
    user-select: none;
}

/* Card Radio */
.card-radio {
    position: relative;
}

.card-radio input {
    position: absolute;
    opacity: 0;
}

.card-radio label {
    display: block;
    padding: 12px 16px;
    border-radius: 10px;
    border: 2px solid #e2e8f0;
    background: #fff;
    cursor: pointer;
    transition: all 0.3s ease;
}

.card-radio input:checked + label {
    border-color: #667eea;
    background: linear-gradient(135deg, #f8f9ff 0%, #f0f0ff 100%);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2);
}

.card-radio label:hover {
    border-color: #667eea;
    transform: translateY(-2px);
}

.card-radio img {
    width: 24px;
    height: 24px;
    margin-left: 8px;
    vertical-align: middle;
}

/* Info Box */
.info-box-custom {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 12px;
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border-radius: 10px;
    border: 1px solid #e2e8f0;
}

.info-box-custom img {
    width: 32px;
    height: 32px;
    border-radius: 6px;
}

.info-box-custom .info-content {
    flex: 1;
}

.info-box-custom .info-label {
    font-size: 11px;
    color: #718096;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    margin-bottom: 2px;
}

.info-box-custom .info-value {
    font-size: 15px;
    font-weight: 700;
    color: #2d3748;
}

/* Buttons */
.btn-modern {
    padding: 8px 18px;
    border-radius: 10px;
    font-weight: 600;
    font-size: 13px;
    transition: all 0.3s ease;
    border: none;
    display: inline-flex;
    align-items: center;
    gap: 6px;
}

.btn-modern i {
    font-size: 16px;
}

.btn-modern.primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #fff;
}

.btn-modern.primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.btn-modern.success {
    background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
    color: #fff;
}

.btn-modern.success:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(17, 153, 142, 0.4);
}

.btn-modern.warning {
    background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    color: #fff;
}

.btn-modern.warning:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(240, 147, 251, 0.4);
}

.btn-modern.danger {
    background: linear-gradient(135deg, #eb3349 0%, #f45c43 100%);
    color: #fff;
}

.btn-modern.danger:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(235, 51, 73, 0.4);
}

.btn-modern.info {
    background: linear-gradient(135deg, #36d1dc 0%, #5b86e5 100%);
    color: #fff;
}

.btn-modern.info:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(54, 209, 220, 0.4);
}

.btn-soft-info {
    background: rgba(102, 126, 234, 0.1);
    color: #667eea;
    border: 1px solid rgba(102, 126, 234, 0.2);
    padding: 6px 14px;
    border-radius: 8px;
    font-weight: 600;
    font-size: 12px;
    transition: all 0.3s ease;
}

.btn-soft-info:hover {
    background: rgba(102, 126, 234, 0.2);
    transform: translateY(-1px);
}

.btn-soft-danger {
    background: rgba(235, 51, 73, 0.1);
    color: #eb3349;
    border: 1px solid rgba(235, 51, 73, 0.2);
    padding: 6px 14px;
    border-radius: 8px;
    font-weight: 600;
    font-size: 12px;
    transition: all 0.3s ease;
}

.btn-soft-danger:hover {
    background: rgba(235, 51, 73, 0.2);
    transform: translateY(-1px);
}

/* Border Dashed */
.border-dashed {
    border: 2px dashed #e2e8f0;
    border-radius: 10px;
}

/* Stack */
.hstack {
    display: flex;
    align-items: center;
    gap: 8px;
}

/* Profile Wrapper */
.profile-wrapper .avatar-sm {
    width: 56px;
    height: 56px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 700;
    border-radius: 12px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #fff;
    font-size: 22px;
}

/* CRM Widget */
.crm-widget .display-6 {
    font-size: 1.8rem;
    font-weight: 800;
}

/* Text Decoration */
.text-decoration-underline {
    text-decoration: underline;
    text-underline-offset: 3px;
}

/* Arvan OS Row */
.arvan-os-row {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
}

.arvan-os-item {
    min-width: 140px;
    text-align: center;
    padding: 12px;
    background: #f8f9fa;
    border-radius: 10px;
    border: 2px solid #e2e8f0;
    transition: all 0.3s ease;
}

.arvan-os-item:hover {
    border-color: #667eea;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2);
}

.arvan-os-item input[type="radio"]:checked + label {
    color: #667eea;
    font-weight: 700;
}

.arvan-os-select {
    margin-top: 8px;
    border-radius: 8px;
    border: 2px solid #e2e8f0;
    padding: 6px 10px;
    font-size: 12px;
    transition: all 0.3s ease;
}

.arvan-os-select:focus {
    border-color: #667eea;
    box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1);
}

/* Alert */
.alert {
    border-radius: 10px;
    border: none;
    padding: 12px 16px;
    font-size: 13px;
    font-weight: 600;
}

.alert-success {
    background: linear-gradient(135deg, #d4fc79 0%, #96e6a1 100%);
    color: #22543d;
}

.alert-danger {
    background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
    color: #742a2a;
}

.alert-warning {
    background: linear-gradient(135deg, #fff7cd 0%, #ffe5a0 100%);
    color: #744210;
}

.alert-info {
    background: linear-gradient(135deg, #e0f2fe 0%, #bae6fd 100%);
    color: #0c4a6e;
}

/* Responsive */
@media (max-width: 768px) {
    .modern-tabs {
        justify-content: center;
    }
    
    .modern-tabs .nav-link {
        font-size: 12px;
        padding: 6px 14px;
    }
    
    .tab-content-wrapper {
        padding: 16px;
    }
}

/* Animation */
@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(10px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.fade-in {
    animation: fadeIn 0.4s ease-out;
}
</style>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('main_content'); ?>
<div class="server-container">
    <div class="container-fluid">

        <?php echo $__env->make('servers.partials.header', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>

        
        <ul class="nav modern-tabs" id="server-tabs" role="tablist">
            <li class="nav-item" role="presentation">
                <button class="nav-link active" id="overview-tab-btn" 
                        data-bs-toggle="tab" data-bs-target="#overview-tab" 
                        type="button" role="tab">
                    <span class="tab-label">
                        <i class="ri-dashboard-line"></i>
                        نمای کلی
                    </span>
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="reinstall-tab-btn" 
                        data-tab-url="<?php echo e(route('servers.tabs.reinstall', $server)); ?>"
                        data-bs-toggle="tab" data-bs-target="#reinstall-tab" 
                        type="button" role="tab">
                    <span class="tab-label">
                        <i class="ri-refresh-line"></i>
                        نصب مجدد
                    </span>
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="abuse-tab-btn"
                        data-tab-url="<?php echo e(route('servers.tabs.abuse', $server)); ?>"
                        data-bs-toggle="tab" data-bs-target="#abuse-tab" 
                        type="button" role="tab">
                    <span class="tab-label">
                        <i class="ri-shield-check-line"></i>
                        ابیوز
                    </span>
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="bandwidth-tab-btn"
                        data-tab-url="<?php echo e(route('servers.tabs.bandwidth', $server)); ?>"
                        data-bs-toggle="tab" data-bs-target="#bandwidth-tab" 
                        type="button" role="tab">
                    <span class="tab-label">
                        <i class="ri-bar-chart-line"></i>
                        Bandwidth
                    </span>
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="network-tab-btn"
                        data-tab-url="<?php echo e(route('servers.tabs.network', $server)); ?>"
                        data-bs-toggle="tab" data-bs-target="#network-tab" 
                        type="button" role="tab">
                    <span class="tab-label">
                        <i class="ri-global-line"></i>
                        Network
                    </span>
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="activity-tab-btn"
                        data-tab-url="<?php echo e(route('servers.tabs.activity', $server)); ?>"
                        data-bs-toggle="tab" data-bs-target="#activity-tab" 
                        type="button" role="tab">
                    <span class="tab-label">
                        <i class="ri-history-line"></i>
                        اکتیویتی
                    </span>
                </button>
            </li>
                <li class="nav-item" role="presentation">
                <button class="nav-link" id="costs-tab-btn"
                        data-tab-url="<?php echo e(route('servers.tabs.costs', $server)); ?>"
                        data-bs-toggle="tab" data-bs-target="#costs-tab" 
                        type="button" role="tab">
                    <span class="tab-label">
                        <i class="ri-history-line"></i>
                        هزینه ها
                    </span>
                </button>
            </li>
        </ul>

        
        <div class="tab-content tab-content-wrapper fade-in" id="server-tab-content">
            
            <div class="tab-pane fade show active" id="overview-tab" role="tabpanel">
                <?php echo $__env->make('servers.partials.overview-tab', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
            </div>

            
            <div class="tab-pane fade" id="reinstall-tab" role="tabpanel">
                <div class="tab-loading">
                    <div class="spinner-modern"></div>
                    <p class="mt-3 text-muted">در حال بارگذاری...</p>
                </div>
            </div>

            <div class="tab-pane fade" id="abuse-tab" role="tabpanel">
                <div class="tab-loading">
                    <div class="spinner-modern"></div>
                    <p class="mt-3 text-muted">در حال بارگذاری...</p>
                </div>
            </div>

            <div class="tab-pane fade" id="bandwidth-tab" role="tabpanel">
                <div class="tab-loading">
                    <div class="spinner-modern"></div>
                    <p class="mt-3 text-muted">در حال بارگذاری...</p>
                </div>
            </div>

            <div class="tab-pane fade" id="network-tab" role="tabpanel">
                <div class="tab-loading">
                    <div class="spinner-modern"></div>
                    <p class="mt-3 text-muted">در حال بارگذاری...</p>
                </div>
            </div>

            <div class="tab-pane fade" id="activity-tab" role="tabpanel">
                <div class="tab-loading">
                    <div class="spinner-modern"></div>
                    <p class="mt-3 text-muted">در حال بارگذاری...</p>
                </div>
            </div>
               <div class="tab-pane fade" id="costs-tab" role="tabpanel">
                <div class="tab-loading">
                    <div class="spinner-modern"></div>
                    <p class="mt-3 text-muted">در حال بارگذاری...</p>
                </div>
            </div>
        </div>

    </div>
</div>


<?php echo $__env->make('servers.partials.modals', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('script'); ?>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
function togglePassword() {
  var el = document.getElementById('password-field');
  if(!el) return;
  var serverPassword = <?php echo json_encode($server->password ?? null, 15, 512) ?>;
  if(serverPassword) {
    if(el.classList.contains('blur')) {
      el.textContent = serverPassword;
      el.classList.remove('blur');
      setTimeout(()=>{
        el.textContent = '*'.repeat(serverPassword.length);
        el.classList.add('blur');
      }, 8000);
    } else {
      el.textContent = '*'.repeat(serverPassword.length);
      el.classList.add('blur');
    }
  } else {
    Swal.fire({
      icon: 'info',
      title: 'توجه',
      text: 'رمز اولیه از سمت provider موجود نیست یا قبلاً نمایش داده شده است.',
    });
  }
}

// ✅ AJAX Tab Loader
(function initTabLoader() {
  const loadedTabs = new Set();
  
  document.querySelectorAll('[data-tab-url]').forEach(btn => {
    btn.addEventListener('shown.bs.tab', function (e) {
      const url = this.getAttribute('data-tab-url');
      const targetId = this.getAttribute('data-bs-target');
      const targetEl = document.querySelector(targetId);
      
      if (loadedTabs.has(targetId)) {
        console.log('⚠️ Tab already loaded:', targetId);
        return;
      }
      
      console.log('🔵 Loading tab:', url);
      
      if (targetEl) {
        fetch(url)
          .then(res => res.text())
          .then(html => {
            targetEl.innerHTML = html;
            loadedTabs.add(targetId);
            
            console.log('✅ Tab HTML loaded:', targetId);
            
            const scripts = targetEl.querySelectorAll('script');
            console.log('📜 Found scripts:', scripts.length);
            
            scripts.forEach((oldScript) => {
              const newScript = document.createElement('script');
              
              Array.from(oldScript.attributes).forEach(attr => {
                newScript.setAttribute(attr.name, attr.value);
              });
              
              newScript.textContent = oldScript.textContent;
              oldScript.parentNode.replaceChild(newScript, oldScript);
              
              console.log('✅ Script executed');
            });
          })
          .catch(err => {
            console.error('❌ Error loading tab:', err);
            targetEl.innerHTML = '<div class="alert alert-danger"><i class="ri-error-warning-line me-2"></i>خطا در بارگذاری محتوا</div>';
          });
      }
    });
  });
  
  console.log('✅ Tab Loader Initialized');
})();

function copyToClipboard(text){
  if (navigator.clipboard) {
    navigator.clipboard.writeText(text);
    Swal.fire({
      toast: true,
      position: 'top-end',
      timer: 1500,
      icon: 'success',
      title: 'کپی شد!',
      showConfirmButton: false
    });
  } else {
    var tempInput = document.createElement("input");
    document.body.appendChild(tempInput);
    tempInput.value = text;
    tempInput.select();
    document.execCommand("copy");
    document.body.removeChild(tempInput);
    Swal.fire({
      toast: true,
      position: 'top-end',
      timer: 1500,
      icon: 'success',
      title: 'کپی شد!',
      showConfirmButton: false
    });
  }
}

function RebootServer() {
  Swal.fire({
    title: "ریبوت سرور",
    html: "آیا از ریبوت سرور مطمئن هستید؟",
    icon: "warning",
    showCancelButton: true,
    confirmButtonText: "بله، ریبوت کن",
    cancelButtonText: "لغو",
    confirmButtonColor: '#667eea',
    cancelButtonColor: '#6c757d'
  }).then((result) => {
    if(result.isConfirmed) {
      fetch(`/cloud/servers/<?php echo e($server->id); ?>/reboot`, {
        method: 'POST',
        headers: {'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>'}
      }).then(res=>res.json()).then(data=>{
        Swal.fire({
          title:'نتیجه',
          icon:data.status==='success'?'success':'error',
          text:data.message||''
        });
      });
    }
  });
}

function PowerServer(status) {
  Swal.fire({
    title: status ? "روشن کردن سرور" : "خاموش کردن سرور",
    html: status ? "آیا می‌خواهید سرور را روشن کنید؟" : "آیا مطمئن هستید که می‌خواهید سرور را خاموش کنید؟",
    icon: "warning",
    showCancelButton: true,
    confirmButtonText: status ? "روشن کن" : "خاموش کن",
    cancelButtonText: "لغو",
    confirmButtonColor: status ? '#11998e' : '#eb3349',
    cancelButtonColor: '#6c757d'
  }).then((result)=>{
    if(result.isConfirmed){
      fetch(`/cloud/servers/<?php echo e($server->id); ?>/power`, {
        method: 'POST',
        headers: {'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>','Content-Type':'application/json'},
        body: JSON.stringify({state:status})
      }).then(res=>res.json()).then(data=>{
        Swal.fire({
          title:'نتیجه',
          icon:data.status==='success'?'success':'error',
          text:data.message||''
        });
        if(data.status==='success'){
          let tries = 0;
          function poll(){
            fetch(`/cloud/servers/<?php echo e($server->id); ?>/status`)
              .then(res=>res.json())
              .then(stat=>{
                if(['active','running','on','off','stopped'].includes((stat.status||'').toLowerCase())){
                  location.reload();
                } else if(tries < 10){
                  tries++;
                  setTimeout(poll, 1000);
                }
              });
          }
          poll();
        }
      });
    }
  });
}

function ReinstallServer() {
  let provider = "<?php echo e($server->provider ?? ''); ?>";
  let imageId = null;

  if (provider === "arvan") {
    let radios = document.getElementsByName("os-family");
    radios = Array.from(radios);

    radios.forEach(function(radio, idx) {
      if(radio.checked) {
        let select = document.getElementById('os-version-' + idx);
        imageId = select && select.value ? select.value : null;
      }
    });
  } else {
    let selected = document.querySelector('input[name="image_id"]:checked, select[name="image_id"]');
    if(selected) imageId = selected.value;
  }

  if(!imageId) {
    Swal.fire({
      icon: 'warning',
      title: 'توجه',
      text: 'لطفاً ابتدا یک سیستم عامل و نسخه را انتخاب کنید'
    });
    return;
  }
  
  Swal.fire({
    title: "نصب مجدد سیستم عامل",
    html: 'آیا مطمئن هستید؟ تمام فایل‌ها پاک خواهد شد!',
    icon: "warning",
    showCancelButton: true,
    confirmButtonText: "بله، نصب مجدد",
    cancelButtonText: "لغو",
    confirmButtonColor: '#eb3349',
    cancelButtonColor: '#6c757d'
  }).then((result)=>{
    if(result.isConfirmed){
      fetch(`/cloud/servers/<?php echo e($server->id); ?>/reinstall`, {
        method: 'POST',
        headers: {'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>','Content-Type':'application/json'},
        body: JSON.stringify({ image_id: imageId })
      })
      .then(res => {
        if (res.headers.get('content-type').includes('application/json')) {
          return res.json();
        } else {
          throw new Error('پاسخ غیرمنتظره از سرور دریافت شد');
        }
      })
      .then(data=>{
        let resultBox = document.getElementById('reinstall-result');
        let msg = data.message || '';
        if(msg.indexOf("This action is disabled in this region") !== -1) {
          msg = 'امکان نصب مجدد سیستم عامل در این موقعیت وجود ندارد. می‌توانید سرور را حذف و سرور دیگری ایجاد نمایید.';
        }
        if(data.success) {
          resultBox.innerHTML = '<div class="alert alert-success"><i class="ri-checkbox-circle-line me-2"></i>نصب مجدد آغاز شد</div>';
        } else {
          resultBox.innerHTML = '<div class="alert alert-danger"><i class="ri-error-warning-line me-2"></i>خطا: '+ (msg || "خطایی رخ داد") +'</div>';
        }
      })
      .catch(err=>{
        document.getElementById('reinstall-result').innerHTML =
          '<div class="alert alert-danger"><i class="ri-error-warning-line me-2"></i>خطای ارتباط با سرور: '+err.message+'</div>';
      });
    }
  });
}

function DeleteServer() {
  Swal.fire({
    title: "حذف سرور",
    html: "آیا مطمئن هستید که می‌خواهید این سرور را حذف کنید؟",
    icon: "error",
    showCancelButton: true,
    confirmButtonText: "بله، حذف کن",
    cancelButtonText: "لغو",
    confirmButtonColor: '#eb3349',
    cancelButtonColor: '#6c757d'
  }).then((result)=>{
    if(result.isConfirmed){
      fetch(`/cloud/servers/<?php echo e($server->id); ?>/delete`, {
        method: 'POST',
        headers: {'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>'}
      }).then(res=>res.json()).then(data=>{
        Swal.fire({
          title:'نتیجه',
          icon:data.status==='success'?'success':'error',
          text:data.message||''
        });
        if(data.status==='success') setTimeout(()=>window.location='/cloud/projects/<?php echo e($server->project_id ?? ''); ?>/servers', 2000);
      });
    }
  });
}

function OpenConsole() {
  let provider = "<?php echo e($server->provider ?? ''); ?>";
  if(provider === "arvan") {
    fetch('/cloud/arvan/servers/<?php echo e($server->id); ?>/vnc', {
      method: "GET",
      headers: {'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>'}
    })
    .then(res => res.json())
    .then(data => {
      let url = null;
      if(data.success && data.data) {
        if(data.data.url) url = data.data.url;
        else if(data.data.data && data.data.data.url) url = data.data.data.url;
      }
      if(url) {
        document.getElementById('vnc-frame').src = url;
        let modal = new bootstrap.Modal(document.getElementById('vncModal'));
        modal.show();
      } else {
        Swal.fire({
          icon: 'error',
          title: 'خطا',
          text: data.message || 'دریافت اطلاعات کنسول ممکن نشد'
        });
      }
    })
    .catch(err=>{
      Swal.fire({
        icon: 'error',
        title: 'خطا',
        text: 'ارتباط با سرور برقرار نشد'
      });
    });
  } else {
    Swal.fire({
      icon: 'info',
      title: 'کنسول سرور',
      text: 'در حال توسعه...'
    });
  }
}

// Polling وضعیت سرور
(function pollOverviewStatus(serverId, osListRaw){
  let pollingInterval = 5000;
  let osList = [];
  try { osList = JSON.parse(osListRaw); } catch(e){}

  function statusInfo(status) {
    status = (status||'').toLowerCase();
    if(['active','running','on'].includes(status))  return {class:'text-success', text:'روشن', icon:'ri-checkbox-circle-fill'};
    if(['creating','pending','starting','initializing','installing'].includes(status)) return {class:'text-warning', text:'در حال ساخت', icon:'ri-time-fill'};
    if(['off','stopped','shutoff'].includes(status)) return {class:'text-secondary', text:'خاموش', icon:'ri-pause-circle-fill'};
    if(['suspended'].includes(status))              return {class:'text-danger', text:'مسدود', icon:'ri-error-warning-fill'};
    return {class:'text-muted', text:status, icon:'ri-question-fill'};
  }

  function getOsName(osId) {
    if(!osId) return '-';
    for(let i=0; i<osList.length; i++) {
      if(osList[i].id == osId) return osList[i].name || osId;
    }
    return osId;
  }

  function updateStatusUI(data) {
    let statusVal = (data.status||'').toLowerCase();
    let info = statusInfo(statusVal);
    let statusIcon = document.querySelector('#server-status i');
    if(statusIcon) statusIcon.className = 'ri ' + info.icon + ' ' + info.class;
    let statusTextEl = document.getElementById('status-text');
    if(statusTextEl) statusTextEl.innerText = info.text;
    if(typeof data.ram !== "undefined" && document.getElementById('server-ram'))
      document.getElementById('server-ram').textContent = data.ram ? (data.ram + ' MB') : '-';
    if(typeof data.vcpu !== "undefined" && document.getElementById('server-cpu'))
      document.getElementById('server-cpu').textContent = data.vcpu ? (data.vcpu + ' Core') : '-';
    if(typeof data.disk !== "undefined" && document.getElementById('server-disk'))
      document.getElementById('server-disk').textContent = data.disk ? (data.disk + ' GB') : '-';

    let osName = data.image_name || getOsName(data.image) || '-';
    if(document.getElementById('server-os')) document.getElementById('server-os').textContent = osName;
    if(document.getElementById('info-os-name')) document.getElementById('info-os-name').textContent = osName;
    if(typeof renderOsBox === "function") renderOsBox(osName);
  }
  
  function renderOsBox(osName) {
    const osIconMap = {
      'debian':   'debian.svg',
      'ubuntu':   'ubuntu.svg',
      'centos':   'centos.svg',
      'windows':  'windows.svg',
      'almalinux':'alma.svg',
      'rocky':    'rocky.svg',
      'arch':     'arch.svg',
      'fedora':   'fedora.svg',
      'opensuse': 'opensuse.svg'
    };
    let icon = 'os-unknown.svg';
    if (osName && typeof osName === 'string') {
      const name = osName.toLowerCase();
      for (const key in osIconMap) {
        if (~name.indexOf(key)) {
          icon = osIconMap[key];
          break;
        }
      }
    }
    if(document.getElementById('os-icon')) document.getElementById('os-icon').src = '/assets/os-icons/' + icon;
    if(document.getElementById('info-os-name')) document.getElementById('info-os-name').textContent = osName || '-';
  }

  function poll() {
    fetch(`/cloud/servers/${serverId}/status`)
      .then(res=>res.json())
      .then(data=>{
        if(data.status) updateStatusUI(data);
        setTimeout(poll, pollingInterval);
      });
  }
  poll();
})(
  <?php echo e($server->id); ?>,
  <?php echo json_encode($osList ?? [], 15, 512) ?>
);

// لیست ایمیج آروان
document.addEventListener("DOMContentLoaded", function() {
  document.getElementById('reinstall-tab-btn')?.addEventListener('click', function() {
    let provider = "<?php echo e($server->provider ?? ''); ?>";
    if(provider !== 'arvan') return;
    let region   = "<?php echo e($server->region ?? ''); ?>";
    let imageBox = document.getElementById('image-radio-list');
    if(!imageBox) return;
    
    imageBox.innerHTML = '<div class="text-center p-3"><div class="spinner-modern"></div></div>';
    fetch('/cloud/arvan/images?region=' + region + '&type=distributions')
      .then(res => res.json())
      .then(function(data) {
        let osFamilies = Array.isArray(data) ? data.filter(item => item.display !== false) : [];
        if (osFamilies.length === 0) {
          imageBox.innerHTML =
            '<div class="alert alert-danger"><i class="ri-error-warning-line me-2"></i>هیچ سیستم عاملی برای نصب مجدد یافت نشد.</div>';
          return;
        }
        let html = '<div class="arvan-os-row">';
        osFamilies.forEach(function(family, idx){
          let familyName = family.name || "نامشخص";
          let checked = idx === 0 ? 'checked' : '';
          let selectId = 'os-version-' + idx;
          html += `
            <div class="arvan-os-item">
              <div>
                <input type="radio" class="form-check-input" name="os-family" id="os-radio-${selectId}" value="${familyName}" ${checked}
                  onchange="showOsVersionDrop('${selectId}')">
                <label class="form-check-label" for="os-radio-${selectId}" style="cursor:pointer;font-weight:600;">
                  ${familyName}
                </label>
              </div>
              <div style="margin-top:7px;">
                <select class="form-select arvan-os-select" style="display:${checked?'inline-block':'none'};" name="image_id" id="${selectId}">
          `;
          (family.images||[]).forEach(function(img){
            html += `<option value="${img.id}">${img.name || 'بدون نسخه'}</option>`;
          });
          html += `</select></div></div>`;
        });
        html += '</div>';
        imageBox.innerHTML = html;

        window.showOsVersionDrop = function(selectId) {
          osFamilies.forEach(function(f, i){
            document.getElementById('os-version-' + i).style.display = 'none';
            document.getElementById('os-radio-os-version-' + i).checked = false;
          });
          document.getElementById(selectId).style.display = 'inline-block';
          document.getElementById('os-radio-' + selectId).checked = true;
        }
      })
      .catch(function() {
        imageBox.innerHTML =
          '<div class="alert alert-danger"><i class="ri-error-warning-line me-2"></i>خطا در دریافت لیست سیستم عامل‌ها از آروان!</div>';
      });
  });
});

// Polling for creating status
<?php if(($server->status ?? '') === 'creating'): ?>
(function pollServerStatus(serverId) {
  let pollingInterval = 3500, maxTries = 60, tries = 0;
  function checkStatus() {
    fetch(`/cloud/servers/${serverId}/status`)
      .then(res => res.json())
      .then(data => {
        let status = (data.status||'').toLowerCase();
        if (['active','running','on'].includes(status)) {
          location.reload();
        } else if (['creating','installing'].includes(status)) {
          tries++; if(tries < maxTries) setTimeout(checkStatus, pollingInterval);
        }
      });
  }
  checkStatus();
})(<?php echo e($server->id); ?>);
<?php endif; ?>
</script>
<?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/overview.blade.php ENDPATH**/ ?>