<html lang="tr">
<head>
  <meta charset="UTF-8">
  <title>Konsol</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
    <!--  <link rel="stylesheet" href="css/wmks-all.css?v=<?php echo rand(); ?>"> -->
  <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
  <script src="https://sspanel.serversistemleri.com/js/wmks.min.js?v=<?php echo rand(); ?>"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" integrity="sha512-Evv84Mr4kqVGRNSgIGL/F/aIDqQb7xQ2vcrdIwxfjThSH8CSR7PBEakCr51Ck+w+/U6swU2Im1vVX0SVk9ABhg==" crossorigin="anonymous" referrerpolicy="no-referrer" />

  <style>
.ctrl-pane .back,
.ctrl-pane .front,
.ctrl-pane .key-group{
  display: flex !important;
  flex-wrap: wrap !important;
  justify-content: center !important;
  gap: 10px !important;
  padding: 1rem !important;
  max-width: 100% !important;
  box-sizing: border-box !important;
}

.baseKey {
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  background-color: #1f2937 !important; /* gray-800 */
  color: #ffffff !important;
  font-weight: 600 !important;
  border-radius: 0.5rem !important;
  width: 64px !important;
  height: 64px !important;
  box-shadow: 0 2px 8px rgba(0,0,0,0.4) !important;
  text-align: center !important;
  user-select: none !important;
  cursor: pointer !important;
  transition: all 0.2s ease-in-out !important;
  font-size: 14px !important;
  line-height: 1.2 !important;
}

.baseKey:hover {
  background-color: #374151 !important; /* gray-700 */
  transform: scale(1.05) !important;
}

.baseKey img.touch-sprite {
  width: 24px !important;
  height: 24px !important;
  filter: invert(1) !important;
  pointer-events: none !important;
}

#fnMasterKey {
  width: auto !important;
  padding: 0 1rem !important;
}

@media (max-width: 768px) {
  .baseKey {
    width: 56px !important;
    height: 56px !important;
    font-size: 12px !important;
  }
}
.baseKey.ab-modifier-key-down {
  background-color: #2563eb !important; /* blue-600 */
  box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.4) !important;
  transform: scale(0.95) !important;
}
  </style>
  <style>


    html, body {
      margin: 0;
      padding: 0;
      height: 100%;
      overflow: hidden;
      background: #000;
    }

    #wmksContainer canvas {
      cursor: none !important;
    }

    #wmksContainer {
      position: absolute;
      top: 4rem; /* üst bar yüksekliği */
      bottom: 0;
      left: 0;
      right: 0;
      z-index: 10;
      background-color: #000;
    }
  </style>
</head>
<body class="bg-black text-white">

  <!-- Üst Bar -->
  <div id="header" class="fixed top-0 left-0 w-full z-50 bg-gray-900 border-b border-gray-800 h-16 flex items-center justify-between px-6 shadow-md">
    <!-- Müşteri Bilgileri -->
    <div class="flex flex-col">
      <span class="text-sm font-semibold text-white">👤 Müşteri: <span class="text-green-400"><?php echo $adsoyad; ?></span></span>
      <span class="text-xs text-gray-400">⏳ Süre: <minuten id="remaining-time"><?php echo $minuten; ?></minuten> dakika kaldı</span>
    </div>
    <style>
      /* Mobil cihazlar icin 3 nokta menusu */
      .mobile-overlay-toggle {
        position: fixed;
        bottom: 20px;
        right: 20px;
        background-color: #1f2937;
        color: white;
        border-radius: 9999px;
        width: 48px;
        height: 48px;
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 9999;
        box-shadow: 0 0 10px rgba(0,0,0,0.5);
      }

      .mobile-overlay-toggle svg {
        width: 24px;
        height: 24px;
      }

      .mobile-overlay {
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background-color: rgba(31, 41, 55, 0.95);
        color: white;
        padding: 20px;
        border-radius: 1rem;
        z-index: 9998;
        width: 90vw;
        height: 80vh;
        overflow-y: auto;
        display: none;
      }
      div#ctrlPaneWidget{
        display: block !important;
      }
      .mobile-overlay.active {
        display: block;
      }

      @media (min-width: 768px) {
        .mobile-overlay-toggle {
          display: none;
        }
      }

      .fnKeyPadMobile{
        width: 350px !important;
        height: 350px !important;
      }
      button.ui-button.ui-corner-all.ui-widget.ui-button-icon-only.ui-dialog-titlebar-close {
          display: none !important;
      }
    </style>

    <!-- 3 Nokta Buton -->
    <button id="toggleOverlay" class="mobile-overlay-toggle">
      <svg fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
        <path d="M6 10a2 2 0 114 0 2 2 0 01-4 0zm6 0a2 2 0 114 0 2 2 0 01-4 0z"></path>
      </svg>
    </button>

    <!-- Mobil Overlay -->
    <div id="mobileOverlay" class="mobile-overlay">
      <!-- ctrlPaneWidget ve fnKeyPad icine konacak -->
      <div id="ctrlPaneWidgetMobile"></div>
      <div id="fnKeyPadMobile"></div>
    </div>

    <script>
      const toggleBtn = document.getElementById("toggleOverlay");
      const overlay = document.getElementById("mobileOverlay");

      toggleBtn.addEventListener("click", () => {
        overlay.classList.toggle("active");
      });

      // Orijinal kontrolleri taşı (ilk yüklemede)
      window.addEventListener("load", () => {
        const ctrlPane = document.getElementById("ctrlPaneWidget");
        const fnKey = document.getElementById("fnKeyPad");
        const ctrlMobile = document.getElementById("ctrlPaneWidgetMobile");
        const fnMobile = document.getElementById("fnKeyPadMobile");

        if (ctrlPane && ctrlMobile) ctrlMobile.appendChild(ctrlPane);
        if (fnKey && fnMobile) fnMobile.appendChild(fnKey);
      });
    </script>
    <!-- Başlık -->
    <div class="absolute left-1/2 transform -translate-x-1/2 text-center">
      <h1 class="hidden text-lg font-bold text-white">🖥️ Web Konsol</h1>
    </div>

    <style media="screen">
      .swal2-title{
        font-size: 19px !important;
      }
      div#swal2-html-container {
        font-size: 15px !important;
      }
      #mobileMenu button{
        text-align: center !important;
      }
      #mobileMenu button i{
        margin-bottom:5px !important;
      }
    </style>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <!-- Butonlar -->
    <div class="relative">
  <!-- Masaüstü için -->
  <div class="hidden md:flex space-x-2">
    <button onclick="wmks.sendCAD()" class="bg-blue-600 hover:bg-blue-700 px-4 py-2 text-sm rounded shadow text-white">
      Ctrl + Alt + Del
    </button>
    <button onclick="toggleFullscreen()" class="bg-gray-700 hover:bg-gray-600 px-4 py-2 text-sm rounded shadow text-white">
      Tam Ekran
    </button>
    <button data-action="start" class="power-action btn-start bg-gray-700 hover:bg-gray-600 px-4 py-2 text-sm rounded shadow text-white disabled:opacity-50 disabled:cursor-not-allowed">
      <i class="fa-solid fa-plug-circle-plus"></i> Gücü Aç
    </button>
    <button data-action="stop" class="power-action btn-stop bg-gray-700 hover:bg-gray-600 px-4 py-2 text-sm rounded shadow text-white disabled:opacity-50 disabled:cursor-not-allowed">
      <i class="fa-solid fa-plug-circle-minus"></i> Gücü Kapat
    </button>
    <button data-action="reset" class="power-action btn-reset bg-gray-700 hover:bg-gray-600 px-4 py-2 text-sm rounded shadow text-white disabled:opacity-50 disabled:cursor-not-allowed">
      <i class="fa-solid fa-power-off"></i> Yeniden Başlat
    </button>
    <button id="vm-status" class="bg-gray-700 hover:bg-gray-600 px-4 py-2 text-sm rounded shadow text-white disabled:opacity-50 disabled:cursor-not-allowed">
      Güç Durumu
    </button>
  </div>

  <!-- Mobil için hamburger -->
  <div class="md:hidden">
    <button id="menuToggle" onclick="toggleMenu()" class="p-2 rounded bg-gray-700 hover:bg-gray-600">
      <svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24"
           xmlns="http://www.w3.org/2000/svg">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
              d="M4 6h16M4 12h16M4 18h16"></path>
      </svg>
    </button>

    <!-- Açılır menü -->
    <div style="text-align:center !important;" id="mobileMenu" class="absolute right-0 mt-2 bg-gray-800 border border-gray-700 rounded shadow-md p-2 space-y-2 hidden z-50">
      <button onclick="wmks.sendCAD(); closeMenu()" class="block w-full bg-blue-600 hover:bg-blue-700 px-4 py-2 text-sm rounded text-left text-white">
        Ctrl + Alt + Del
      </button>
    
      <button data-action="start" onclick="closeMenu()" class="power-action btn-start block w-full bg-gray-700 hover:bg-gray-600 px-4 py-2 text-sm rounded text-left text-white disabled:opacity-50 disabled:cursor-not-allowed">
        <i class="fa-solid fa-plug-circle-plus"></i> Gücü Aç
      </button>
      <button data-action="stop" onclick="closeMenu()" class="power-action btn-stop block w-full bg-gray-700 hover:bg-gray-600 px-4 py-2 text-sm rounded text-left text-white disabled:opacity-50 disabled:cursor-not-allowed">
        <i class="fa-solid fa-plug-circle-minus"></i> Gücü Kapat
      </button>
      <button data-action="reset" onclick="closeMenu()" class="power-action btn-reset block w-full bg-gray-700 hover:bg-gray-600 px-4 py-2 text-sm rounded text-left text-white disabled:opacity-50 disabled:cursor-not-allowed">
        <i class="fa-solid fa-power-off"></i> Yeniden Başlat
      </button>
      <button id="vm-status-mobile" class="block w-full bg-gray-700 hover:bg-gray-600 px-4 py-2 text-sm rounded text-left text-white disabled:opacity-50 disabled:cursor-not-allowed">
        Güç Durumu
      </button>
    </div>
  </div>
</div>
  </div>

  <!-- WebMKS Konsol -->
  <div id="wmksContainer"></div>

  <script>
      function updateVmStatus() {
          fetch("{{ route('ajax.vmStatus') }}", {
              method: "POST",
              headers: {
                  "Content-Type": "application/json",
                  "X-CSRF-TOKEN": "{{ csrf_token() }}"
              },
              body: JSON.stringify({
                  domain: "<?php echo $vm_name; ?>"
              })
          })
          .then(res => res.json())
          .then(data => {
              const el = document.getElementById("vm-status");
              const el2 = document.getElementById("vm-status-mobile");
              const btnStart = document.querySelector('.btn-start');
              const btnStop  = document.querySelector('.btn-stop');
              const btnReset = document.querySelector('.btn-reset');
              if (data.status === "success") {
                  // Metin güncelle
                  if (data.power === "POWERED_ON") {
                      el.innerHTML = '<i class="fa-solid fa-power-off" style="color:green;"></i> Sunucu Açık';
                      el2.innerHTML = '<i class="fa-solid fa-power-off" style="color:green;"></i> Sunucu Açık';
                      btnStart.disabled = true;
                      btnStop.disabled  = false;
                      btnReset.disabled = false;
                  } else if (data.power === "POWERED_OFF") {
                      el.innerHTML = '<i class="fa-solid fa-power-off" style="color:red;"></i> Sunucu Kapalı';
                      el2.innerHTML = '<i class="fa-solid fa-power-off" style="color:red;"></i> Sunucu Kapalı';
                      btnStart.disabled = false;
                      btnStop.disabled  = true;
                      btnReset.disabled = true;
                  } else {
                      el.textContent = "⚠️ Bilinmeyen durum";
                      [btnStart, btnStop, btnReset].forEach(btn => btn.disabled = true);
                  }
              } else {
                  el.textContent = "⚠️ Durum alınamadı";
                  [btnStart, btnStop, btnReset].forEach(btn => btn.disabled = true);
              }

              // Buton stillerini güncelle
              [btnStart, btnStop, btnReset].forEach(btn => {
                  if (btn.disabled) {
                      btn.classList.add('opacity-50', 'cursor-not-allowed');
                  } else {
                      btn.classList.remove('opacity-50', 'cursor-not-allowed');
                  }
              });
          })
          .catch(() => {
              document.getElementById("vm-status").textContent = "⚠️ Hata oluştu";
          });
      }
      updateVmStatus();
      setInterval(updateVmStatus, 5000);

    document.querySelectorAll('.power-action').forEach(button => {
      button.addEventListener('click', function () {
        const action = this.getAttribute('data-action');
        const domain = '<?php echo $vm_name; ?>';

        const actionTexts = {
          start: {
            title: 'Açmak istiyor musunuz?',
            text: "Cihazınız açık duruma gelecektir.",
            confirm: 'Evet, Aç!',
            cancel: 'Vazgeç'
          },
          stop: {
            title: 'Kapatmak istiyor musunuz?',
            text: 'Cihazınız kapalı duruma gelecektir. Cihaz tekrar açılmadan konsol erişimi yapamayacaksınız.',
            confirm: 'Evet, Kapat!',
            cancel: 'İptal Et'
          },
          reset: {
            title: 'Yeniden Başlatmak istiyor musunuz?',
            text: 'Cihaz yeniden başlatıldığında bazı yazılımlarınızda sorun oluşabilir.',
            confirm: 'Evet, Yeniden Başlat!',
            cancel: 'Hayır'
          }
        };

        const { title, text, confirm, cancel } = actionTexts[action];

        Swal.fire({
          title: title,
          text: text,
          icon: 'warning',
          theme: 'dark',
          showCancelButton: true,
          confirmButtonText: confirm,
          cancelButtonText: cancel,
          reverseButtons: true
        }).then((result) => {
          if (result.isConfirmed) {
            fetch('{{ route("console.process") }}', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
              },
              body: JSON.stringify({ domain, action })
            })
            .then(res => res.json())
            .then(data => {
              Swal.fire({
                title: 'İşlem Tamam',
                text: data.message || 'İşlem başarıyla gerçekleşti.',
                icon: 'success',
                timer: 2000,
                showConfirmButton: false
              }).then((result) => {
                if (data.message === 'Cihaz başarıyla kapatıldı.') {
                  location.reload(); // 🔄 Sayfayı yenile
                }
              });
            })
            .catch(() => {
              Swal.fire('Hata!', 'Bir sorun oluştu.', 'error');
            });
          }
        });
      });
    });

    const menuToggle = document.getElementById("menuToggle");
    const mobileMenu = document.getElementById("mobileMenu");

    menuToggle?.addEventListener("click", () => {
      mobileMenu?.classList.toggle("hidden");
    });

    function closeMenu() {
      mobileMenu?.classList.add("hidden");
    }

    document.addEventListener("click", function (e) {
      if (!menuToggle.contains(e.target) && !mobileMenu.contains(e.target)) {
        closeMenu();
      }
    });

    const wmks = WMKS.createWMKS("wmksContainer", {
      fitToParent: true,
      showMouse: true,
      enableRelativeMouse: true
    });

    wmks.connect("<?= htmlspecialchars($ticket_url) ?>");

    function toggleFullscreen() {
      const elem = document.documentElement;
      if (!document.fullscreenElement) {
        elem.requestFullscreen().catch(err => console.error(err));
      } else {
        document.exitFullscreen();
      }
    }

    window.addEventListener("resize", () => {
      const wmksContainer = document.getElementById("wmksContainer");
      wmksContainer.style.top = document.getElementById("header").offsetHeight + "px";
    });

    function resizeWMKSCanvasFix() {
      const canvas = document.querySelector('#wmksContainer canvas');
      const container = document.getElementById('wmksContainer');

      if (!canvas || !container) return;

      const containerWidth = container.clientWidth;
      const containerHeight = container.clientHeight;

      const canvasWidth = canvas.width;
      const canvasHeight = canvas.height;

      const scaleX = containerWidth / canvasWidth;
      const scaleY = containerHeight / canvasHeight;
      const scale = Math.min(scaleX, scaleY);

      const offsetX = (containerWidth - canvasWidth * scale) / 2;
      const offsetY = (containerHeight - canvasHeight * scale) / 2;

      canvas.style.transform = `scale(${scale})`;
      canvas.style.transformOrigin = "top left";
      canvas.style.left = `${offsetX}px`;
      canvas.style.top = `${offsetY}px`;
    }

    window.addEventListener("resize", resizeWMKSCanvasFix);
    document.addEventListener("fullscreenchange", resizeWMKSCanvasFix);
    window.addEventListener("load", () => {
      setTimeout(resizeWMKSCanvasFix, 300);
    });
  </script>
  <script>
      document.addEventListener('DOMContentLoaded', function () {
          let remainingMinutes = {{ $minuten }};
          const infoText = document.querySelector('#remaining-time');

          function updateTimer() {
              if (remainingMinutes <= -1) {
                  location.reload(); // Sayfayı otomatik yenile
              } else {
                  infoText.textContent = remainingMinutes + " dakika";
                  remainingMinutes--;
              }
          }

          // İlk yazdırma
          updateTimer();

          // Her 1 dakikada bir güncelle
          setInterval(updateTimer, 60000); // 60000ms = 1 dakika
      });
  </script>
</body>
</html>
