<?php
// TEXA canvas-PRO Backend
$configFile = __DIR__ . '/servers.json';

// Handle AJAX Save Request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['action']) && $_GET['action'] === 'save') {
    $inputJSON = file_get_contents('php://input');
    $data = json_decode($inputJSON, true);
    
    if ($data !== null) {
        // Save to file
        file_put_contents($configFile, json_encode($data, JSON_PRETTY_PRINT));
        echo json_encode(['status' => 'success']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Invalid JSON']);
    }
    exit;
}

// Load current config
$serverConfig = '{"servers":[],"activeId":null}';
if (file_exists($configFile)) {
    $serverConfig = file_get_contents($configFile);
}
?>
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>TEXA canvas-PRO</title>
    <script>
      // Fix for "Uncaught TypeError: Cannot set property fetch of #<Window> which has only a getter"
      // This happens when libraries try to polyfill fetch by direct assignment.
      (function() {
        if (typeof window !== 'undefined') {
          window.global = window;
          var _originalFetch = window.fetch;
          try {
            Object.defineProperty(window, 'fetch', {
              get: function() { return _originalFetch; },
              set: function(v) { 
                console.warn('Prevented attempt to overwrite window.fetch');
                // We ignore the assignment to prevent the TypeError
              },
              configurable: true,
              enumerable: true
            });
          } catch (e) {
            // If it's already non-configurable, we can't do much here
            // but usually this script runs early enough.
          }
        }
      })();
    </script>
    <style>
      body {
        margin: 0;
        font-family: system-ui,-apple-system,BlinkMacSystemFont,sans-serif;
        background: #020617;
        color: #e5e7eb;
      }
      .page {
        height: 100vh;
        height: 100dvh;
        display: flex;
        flex-direction: column;
        overflow: hidden;
      }
      .page-header {
        padding: 12px 20px;
        border-bottom: 1px solid rgba(148,163,184,0.3);
        display: flex;
        align-items: center;
        justify-content: space-between;
        background: radial-gradient(circle at top left,#22c55e1a,#020617);
      }
      .page-title {
        font-size: 18px;
        font-weight: 600;
      }
      .page-subtitle {
        font-size: 11px;
        opacity: 0.6;
      }
      .header-actions {
        display: flex;
        align-items: center;
        gap: 8px;
      }
      .toggle-sidebar-btn {
        border-radius: 999px;
        border: 1px solid rgba(148,163,184,0.7);
        background: rgba(15,23,42,0.9);
        color: #e5e7eb;
        padding: 6px 10px;
        font-size: 11px;
        cursor: pointer;
      }
      .toggle-sidebar-btn:hover {
        border-color: #22c55e;
        color: #bbf7d0;
      }
      .page-main {
        flex: 1;
        display: flex;
        gap: 16px;
        padding: 16px 20px 20px;
        box-sizing: border-box;
      }
      .panel {
        border-radius: 12px;
        border: 1px solid rgba(15,118,110,0.5);
        background: rgba(15,23,42,0.85);
        box-shadow: 0 20px 40px rgba(15,23,42,0.9);
      }
      .viewer-panel {
        flex: 1;
        display: flex;
        flex-direction: column;
        overflow: hidden;
      }
      .servers-panel {
        width: 260px;
        padding: 12px;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
      }
      .servers-header {
        font-size: 12px;
        font-weight: 600;
        margin-bottom: 8px;
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      .servers-list {
        display: flex;
        flex-direction: column;
        gap: 6px;
        max-height: 260px;
        overflow-y: auto;
        padding-right: 4px;
      }
      .server-button {
        width: 100%;
        text-align: left;
        border-radius: 10px;
        border: 1px solid rgba(148,163,184,0.5);
        background: rgba(15,23,42,0.9);
        color: #e5e7eb;
        padding: 8px 10px;
        font-size: 12px;
        cursor: pointer;
        display: flex;
        flex-direction: column;
        gap: 2px;
      }
      .server-button span {
        display: block;
        max-width: 100%;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      .server-button-label {
        font-weight: 600;
      }
      .server-button-url {
        font-size: 10px;
        opacity: 0.6;
      }
      .server-button.active {
        border-color: #22c55e;
        background: rgba(34,197,94,0.08);
      }
      .servers-empty {
        font-size: 11px;
        opacity: 0.7;
      }
      .admin-link {
        font-size: 11px;
        color: #a7f3d0;
        text-decoration: none;
      }
      .admin-link:hover {
        text-decoration: underline;
      }
      .frame-wrapper {
        flex: 1;
        border-radius: 10px;
        overflow: hidden;
        margin: 12px;
        margin-top: 8px;
        border: 1px solid rgba(15,118,110,0.6);
        background: #020617;
        display: flex;
        flex-direction: column;
      }
      .frame-info {
        font-size: 11px;
        opacity: 0.7;
        padding: 8px 12px 4px;
        flex-shrink: 0;
      }
      .frame-info span {
        display: block;
        max-width: 100%;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      .frame-element {
        width: 100%;
        height: 100%;
        flex: 1;
        border: none;
        background: #020617;
      }
      .admin-page {
        padding: 16px 20px 20px;
        box-sizing: border-box;
        display: none;
      }
      .admin-header {
        font-size: 18px;
        font-weight: 600;
        margin-bottom: 8px;
      }
      .admin-subtitle {
        font-size: 12px;
        opacity: 0.7;
        margin-bottom: 12px;
      }
      .admin-table {
        width: 100%;
        max-width: 900px;
        border-collapse: collapse;
        font-size: 12px;
      }
      .admin-table th,
      .admin-table td {
        border-bottom: 1px solid rgba(51,65,85,0.8);
        padding: 6px 8px;
        text-align: left;
      }
      .admin-table th {
        font-weight: 600;
        font-size: 11px;
        text-transform: uppercase;
        letter-spacing: 0.08em;
        opacity: 0.8;
      }
      .admin-input {
        width: 100%;
        box-sizing: border-box;
        border-radius: 8px;
        border: 1px solid rgba(51,65,85,0.9);
        background: #020617;
        color: #e5e7eb;
        padding: 6px 8px;
        font-size: 12px;
      }
      .admin-actions {
        margin-top: 12px;
        display: flex;
        gap: 8px;
      }
      .btn {
        border-radius: 8px;
        padding: 6px 12px;
        font-size: 12px;
        border: 1px solid transparent;
        cursor: pointer;
      }
      .btn-primary {
        background: #22c55e;
        border-color: #22c55e;
        color: #020617;
        font-weight: 600;
      }
      .btn-secondary {
        background: transparent;
        border-color: rgba(148,163,184,0.7);
        color: #e5e7eb;
      }
      .btn-danger {
        background: transparent;
        border-color: rgba(248,113,113,0.8);
        color: #fecaca;
      }
      .badge {
        font-size: 10px;
        padding: 2px 6px;
        border-radius: 999px;
        border: 1px solid rgba(148,163,184,0.8);
        margin-left: 8px;
        opacity: 0.8;
      }
      #viewer-root.sidebar-hidden .servers-panel {
        display: none !important;
      }
      #viewer-root.sidebar-hidden .frame-wrapper {
        margin: 12px 12px 12px 12px;
      }
      @media (max-width: 900px) {
        .page-main {
          flex-direction: column;
          padding: 8px 8px 72px;
        }
        .servers-panel {
          width: 100%;
          order: 2;
          padding: 8px 10px;
          border-radius: 16px 16px 0 0;
          position: fixed;
          left: 0;
          right: 0;
          bottom: 0;
          margin: 0;
          border-left: none;
          border-right: none;
          z-index: 100;
        }
        .viewer-panel {
          order: 1;
        }
        .servers-list {
          flex-direction: row;
          max-height: none;
          overflow-x: auto;
        }
        .server-button {
          min-width: 140px;
          font-size: 11px;
          padding: 6px 8px;
        }
        .toggle-sidebar-btn {
          display: none;
        }
      }
      
      .show-sidebar-btn {
        position: absolute;
        top: 16px;
        left: 20px;
        background: rgba(15,23,42,0.85);
        border: 1px solid rgba(15,118,110,0.5);
        color: #e5e7eb;
        border-radius: 8px;
        padding: 8px;
        cursor: pointer;
        display: none;
        z-index: 1000;
        box-shadow: 0 4px 12px rgba(0,0,0,0.5);
      }
      
      #viewer-root.sidebar-hidden .show-sidebar-btn {
        display: flex;
      }
    </style>
  </head>
  <body>
    <div class="page" id="viewer-root">
      <main class="page-main" style="position: relative;">
        <button id="show-sidebar" class="show-sidebar-btn" title="Tampilkan menu server">
          <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round">
            <line x1="3" y1="12" x2="21" y2="12"></line>
            <line x1="3" y1="6" x2="21" y2="6"></line>
            <line x1="3" y1="18" x2="21" y2="18"></line>
          </svg>
        </button>
        <aside class="panel servers-panel">
          <div class="servers-header">
            <span>Daftar server</span>
            <button id="toggle-sidebar" class="toggle-sidebar-btn">Sembunyikan menu</button>
          </div>
          <div id="servers-list" class="servers-list" style="flex: 1;"></div>
        </aside>
        <section class="panel viewer-panel">
          <div class="frame-info">
            <span id="active-server-label">Belum ada server dipilih</span>
          </div>
          <div class="frame-wrapper">
            <iframe id="server-frame" class="frame-element" src=""></iframe>
          </div>
        </section>
      </main>
    </div>
    <div class="admin-page" id="admin-root">
      <div class="admin-header">
        Dashboard Admin Server
        <span class="badge">Mode admin</span>
      </div>
      <div class="admin-subtitle">
        Atur daftar URL server yang boleh di-iframe oleh TEXA canvas-PRO.
      </div>
      <table class="admin-table">
        <thead>
          <tr>
            <th style="width: 60px;">No</th>
            <th style="width: 180px;">Nama server</th>
            <th>URL</th>
            <th style="width: 80px;">Aksi</th>
          </tr>
        </thead>
        <tbody id="admin-server-rows"></tbody>
      </table>
      <div class="admin-actions">
        <button id="add-server" class="btn btn-secondary">Tambah URL server</button>
        <button id="save-config" class="btn btn-primary">Simpan konfigurasi</button>
        <button id="back-viewer" class="btn btn-secondary">Kembali ke viewer</button>
      </div>
    </div>
    <script>
      (function() {
        // We now load config from PHP variable injected below
        var serverConfigFromPHP = <?php echo $serverConfig; ?>;
        
        function loadConfig() {
          return serverConfigFromPHP;
        }
        
        function saveConfig(cfg) {
          // Send AJAX request to save to JSON file on server
          var xhr = new XMLHttpRequest();
          xhr.open("POST", "?action=save", true);
          xhr.setRequestHeader("Content-Type", "application/json");
          xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
              console.log("Config saved to server.");
            }
          };
          var data = JSON.stringify(cfg);
          xhr.send(data);
          
          // Also save locally as a fallback just in case
          try { localStorage.setItem("gmServersConfigV2", data); } catch (e) {}
        }
        
        function createId() {
          return Date.now().toString(36) + Math.random().toString(36).slice(2);
        }
        
        function normalizeConfig(cfg) {
          var next = { servers: [], activeId: cfg.activeId || null };
          var seen = {};
          if(cfg && cfg.servers) {
              cfg.servers.forEach(function(s, index) {
                if (!s) return;
                var id = s.id || createId();
                if (seen[id]) id = createId();
                seen[id] = true;
                var name = s.name || ("Server " + (index + 1));
                var url = s.url || "";
                next.servers.push({ id: id, name: name, url: url });
              });
          }
          if (next.servers.length && !next.activeId) {
            next.activeId = next.servers[0].id;
          }
          return next;
        }
        
        var params = new URLSearchParams(window.location.search);
        var isAdmin = params.get("admin") === "1";
        var viewerRoot = document.getElementById("viewer-root");
        var adminRoot = document.getElementById("admin-root");
        var toggleBtn = document.getElementById("toggle-sidebar");
        var showBtn = document.getElementById("show-sidebar");
        var isSidebarHidden = false;
        
        function applySidebarState() {
          if (!viewerRoot) return;
          if (isSidebarHidden) {
            viewerRoot.classList.add("sidebar-hidden");
          } else {
            viewerRoot.classList.remove("sidebar-hidden");
          }
        }
        
        if (toggleBtn) {
          toggleBtn.addEventListener("click", function() {
            isSidebarHidden = true;
            applySidebarState();
          });
        }
        if (showBtn) {
          showBtn.addEventListener("click", function() {
            isSidebarHidden = false;
            applySidebarState();
          });
        }
        
        var state = { config: normalizeConfig(loadConfig()) };
        
        function setModeAdmin(flag) {
          if (flag) {
            viewerRoot.style.display = "none";
            adminRoot.style.display = "block";
          } else {
            viewerRoot.style.display = "flex";
            adminRoot.style.display = "none";
          }
        }
        
        function renderViewer() {
          var listEl = document.getElementById("servers-list");
          var frame = document.getElementById("server-frame");
          var label = document.getElementById("active-server-label");
          listEl.innerHTML = "";
          if (!state.config.servers.length) {
            var empty = document.createElement("div");
            empty.className = "servers-empty";
            empty.textContent = "Belum ada server. Buka dashboard admin untuk menambah.";
            listEl.appendChild(empty);
            label.textContent = "Belum ada server dipilih";
            frame.src = "";
            return;
          }
          state.config.servers.forEach(function(s, index) {
            var btn = document.createElement("button");
            btn.className = "server-button";
            if (s.id === state.config.activeId) btn.classList.add("active");
            var labelSpan = document.createElement("span");
            labelSpan.className = "server-button-label";
            labelSpan.textContent = s.name || ("Server " + (index + 1));
            var urlSpan = document.createElement("span");
            urlSpan.className = "server-button-url";
            urlSpan.textContent = "TEXA secure link";
            btn.appendChild(labelSpan);
            btn.appendChild(urlSpan);
            btn.addEventListener("click", function() {
              setActiveServer(s.id);
            });
            listEl.appendChild(btn);
          });
          applyActiveToFrame();
        }
        
        function setActiveServer(id) {
          state.config.activeId = id;
          // Save just active ID locally so it doesn't mess up global servers list
          saveConfig(state.config);
          renderViewer();
        }
        
        function applyActiveToFrame() {
          var frame = document.getElementById("server-frame");
          var label = document.getElementById("active-server-label");
          var active = state.config.servers.find(function(s) {
            return s.id === state.config.activeId;
          });
          if (!active) {
            label.textContent = "Belum ada server dipilih";
            frame.src = "";
            return;
          }
          label.textContent = active.name + " \u00b7 TEXA canvas-PRO";
          if (frame.src !== active.url) {
            frame.src = active.url;
          }
        }
        
        function renderAdmin() {
          var tbody = document.getElementById("admin-server-rows");
          tbody.innerHTML = "";
          if (!state.config.servers.length) {
            state.config.servers.push({ id: createId(), name: "Server 1", url: "" });
          }
          state.config.servers.forEach(function(s, index) {
            var tr = document.createElement("tr");
            var tdIndex = document.createElement("td");
            tdIndex.textContent = String(index + 1);
            var tdName = document.createElement("td");
            var nameInput = document.createElement("input");
            nameInput.type = "text";
            nameInput.className = "admin-input";
            nameInput.value = s.name || ("Server " + (index + 1));
            tdName.appendChild(nameInput);
            var tdUrl = document.createElement("td");
            var urlInput = document.createElement("input");
            urlInput.type = "text";
            urlInput.className = "admin-input";
            urlInput.value = s.url || "";
            tdUrl.appendChild(urlInput);
            var tdActions = document.createElement("td");
            var delBtn = document.createElement("button");
            delBtn.textContent = "Hapus";
            delBtn.className = "btn btn-danger";
            delBtn.addEventListener("click", function() {
              state.config.servers = state.config.servers.filter(function(x) {
                return x.id !== s.id;
              });
              if (state.config.activeId === s.id) {
                state.config.activeId = state.config.servers.length ? state.config.servers[0].id : null;
              }
              renderAdmin();
            });
            tdActions.appendChild(delBtn);
            tr.appendChild(tdIndex);
            tr.appendChild(tdName);
            tr.appendChild(tdUrl);
            tr.appendChild(tdActions);
            tbody.appendChild(tr);
            s._nameInput = nameInput;
            s._urlInput = urlInput;
          });
        }
        
        function wireAdminButtons() {
          var addBtn = document.getElementById("add-server");
          var saveBtn = document.getElementById("save-config");
          var backBtn = document.getElementById("back-viewer");
          addBtn.addEventListener("click", function() {
            var nextIndex = state.config.servers.length + 1;
            state.config.servers.push({ id: createId(), name: "Server " + nextIndex, url: "" });
            renderAdmin();
          });
          saveBtn.addEventListener("click", function() {
            state.config.servers.forEach(function(s) {
              if (s._nameInput) s.name = s._nameInput.value.trim() || s.name;
              if (s._urlInput) s.url = s._urlInput.value.trim();
              delete s._nameInput;
              delete s._urlInput;
            });
            state.config = normalizeConfig(state.config);
            saveConfig(state.config);
            alert("Konfigurasi server tersimpan di server database (JSON)!");
          });
          backBtn.addEventListener("click", function() {
            window.location.href = window.location.pathname;
          });
        }
        
        if (isAdmin) {
          setModeAdmin(true);
          renderAdmin();
          wireAdminButtons();
        } else {
          setModeAdmin(false);
          renderViewer();
        }
      })();
    </script>
  </body>
</html>