<?php
// dev.php - Tings Dashboard File Creator (Fixed Version)

$folder = __DIR__;

function writeFile($filename, $content) {
    global $folder;
    $path = $folder . DIRECTORY_SEPARATOR . $filename;
    if (file_put_contents($path, $content) !== false) {
        echo "<p style='color:#0f0'>✅ Created/Updated: <strong>$filename</strong></p>";
    } else {
        echo "<p style='color:#f66'>❌ Failed to write: $filename</p>";
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // ==================== index.html ====================
    $indexHTML = <<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Tings Dashboard</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gridstack@12.6.0/dist/gridstack.min.css">
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <header>
    <h1>Tings</h1>
    <button id="edit-btn">Edit Mode: OFF</button>
    <button id="add-section-btn">+ Section</button>
    <button id="export-btn">Export Config</button>
    <button id="import-btn">Import Config</button>
    <input type="file" id="import-file" accept=".json" style="display:none">
    <button id="reset-btn">Reset Dashboard</button>
  </header>

  <div id="grid" class="grid-stack"></div>

  <div id="overlay" class="overlay hidden">
    <div class="overlay-content">
      <button id="close-overlay">✕</button>
      <div id="overlay-body"></div>
    </div>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/gridstack@12.6.0/dist/gridstack.all.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
  <script src="script.js"></script>
</body>
</html>
HTML;

    // ==================== style.css ====================
    $styleCSS = <<<CSS
:root { --bg: #0a0a14; --section-bg: #1a1a2e; --accent: #00ffcc; }
body { margin:0; background:var(--bg); color:#eee; font-family:system-ui,sans-serif; overflow:hidden; height:100vh; }
header { padding:12px 20px; background:#111827; display:flex; gap:10px; flex-wrap:wrap; z-index:100; }
h1 { margin:0; color:var(--accent); }
.grid-stack { padding:20px; min-height:calc(100vh - 70px); background:var(--bg); }
.grid-stack-item-content { background:var(--section-bg); border:2px solid #445577; border-radius:10px; height:100%; display:flex; flex-direction:column; overflow:hidden; pointer-events:auto; }
.section-header { background:#16213e; padding:10px 14px; cursor:move; user-select:none; display:flex; justify-content:space-between; align-items:center; }
.tings-grid { display:grid; gap:14px; padding:16px; flex:1; overflow:auto; }
.ting { pointer-events:auto; padding:12px; border-radius:8px; background:rgba(255,255,255,0.07); text-align:center; cursor:pointer; transition:all .2s; }
.ting:hover { transform:scale(1.12); background:rgba(0,255,204,0.2); }
.overlay { position:fixed; inset:0; background:rgba(0,0,0,0.95); z-index:3000; display:none; align-items:center; justify-content:center; }
.overlay:not(.hidden) { display:flex; }
.overlay-content { width:92%; max-width:1150px; background:#111827; border-radius:12px; padding:15px; position:relative; }
#close-overlay { position:absolute; top:12px; right:20px; font-size:32px; background:none; border:none; color:white; cursor:pointer; }
CSS;

    // ==================== script.js (Improved with better button handling) ====================
    $scriptJS = <<<JS
let grid = null;
let isEditMode = false;
let config = {};

const defaultConfig = {
  sections: [{
    id: "main",
    title: "Main",
    color: "#00ffcc",
    bgImage: "",
    customCSS: "",
    x: 0, y: 0, w: 6, h: 4,
    tings: [{ name: "The Hub", url: "https://idontbyte.com", icon: "🌐", tint: "", target: "_blank" }]
  }]
};

function loadConfig() {
  const saved = localStorage.getItem('tingsConfig');
  config = saved ? JSON.parse(saved) : JSON.parse(JSON.stringify(defaultConfig));
}

function saveConfig() {
  localStorage.setItem('tingsConfig', JSON.stringify(config));
}

function initGrid() {
  if (grid) grid.destroy(true);
  const gridEl = document.getElementById('grid');
  if (!gridEl) return;
  gridEl.innerHTML = '';

  config.sections.forEach(sec => {
    const bg = sec.bgImage ? `background-image:url('\${sec.bgImage}');background-size:cover;` : '';
    gridEl.innerHTML += `
      <div class="grid-stack-item" data-gs-id="\${sec.id}" data-gs-x="\${sec.x}" data-gs-y="\${sec.y}" data-gs-w="\${sec.w}" data-gs-h="\${sec.h}">
        <div class="grid-stack-item-content" style="\${bg} \${sec.customCSS||''}">
          <div class="section-header" style="color:\${sec.color}">
            <span>\${sec.title}</span>
            \${isEditMode ? `<button class="edit-section-btn" data-id="\${sec.id}">⚙️</button>` : ''}
          </div>
          <div class="tings-grid" id="tings-\${sec.id}"></div>
        </div>
      </div>`;
  });

  grid = GridStack.init({
    cellHeight: 100,
    margin: 12,
    draggable: { handle: '.section-header' },
    resizable: isEditMode,
    disableDrag: !isEditMode,
    disableResize: !isEditMode,
    column: 12,
    animate: true
  });

  config.sections.forEach(s => renderTings(s.id));
  setupSortable();
}

function renderTings(sectionId) {
  const container = document.getElementById(`tings-\${sectionId}`);
  if (!container) return;
  container.innerHTML = '';
  const section = config.sections.find(s => s.id === sectionId);
  if (!section) return;

  section.tings.forEach((ting) => {
    const div = document.createElement('div');
    div.className = 'ting';
    div.innerHTML = `<div style="font-size:2.8rem">\${ting.icon || '🔗'}</div><span>\${ting.name}</span>`;
    div.onclick = () => { if (!isEditMode) handleTingClick(ting); };
    container.appendChild(div);
  });

  if (isEditMode) {
    const add = document.createElement('div');
    add.className = 'ting';
    add.innerHTML = `<div style="font-size:2.8rem">+</div><span>Add Ting</span>`;
    add.onclick = () => addNewTing(sectionId);
    container.appendChild(add);
  }
}

function setupSortable() {
  document.querySelectorAll('.tings-grid').forEach(el => {
    new Sortable(el, {
      group: 'tings',
      animation: 150,
      onEnd: (evt) => {
        const from = evt.from.id.replace('tings-', '');
        const to = evt.to.id.replace('tings-', '');
        const secFrom = config.sections.find(s => s.id === from);
        const secTo = config.sections.find(s => s.id === to);
        if (!secFrom || !secTo) return;
        const [moved] = secFrom.tings.splice(evt.oldIndex, 1);
        secTo.tings.splice(evt.newIndex, 0, moved);
        saveConfig();
        renderTings(from);
        if (from !== to) renderTings(to);
      }
    });
  });
}

function handleTingClick(ting) {
  window.open(ting.url, ting.target || '_blank');
}

function addNewTing(sectionId) {
  const name = prompt("Ting Name:");
  if (!name) return;
  const url = prompt("URL:", "https://");
  if (!url) return;
  const section = config.sections.find(s => s.id === sectionId);
  if (section) {
    section.tings.push({name, url, icon: "🔗", tint: "", target: "_blank"});
    renderTings(sectionId);
    saveConfig();
  }
}

// Attach all button listeners safely
function attachListeners() {
  const editBtn = document.getElementById('edit-btn');
  if (editBtn) {
    editBtn.onclick = () => {
      isEditMode = !isEditMode;
      editBtn.textContent = `Edit Mode: \${isEditMode ? 'ON' : 'OFF'}`;
      console.log('Edit mode toggled to:', isEditMode);
      initGrid();
    };
  }

  const addSectionBtn = document.getElementById('add-section-btn');
  if (addSectionBtn) {
    addSectionBtn.onclick = () => {
      config.sections.push({id: 'sec-' + Date.now(), title: 'New Section', color: '#ff8800', bgImage: '', customCSS: '', x:0, y:999, w:5, h:3, tings:[]});
      initGrid();
      saveConfig();
      console.log('New section added');
    };
  }

  const exportBtn = document.getElementById('export-btn');
  if (exportBtn) {
    exportBtn.onclick = () => {
      const dataStr = JSON.stringify(config, null, 2);
      const blob = new Blob([dataStr], {type: "application/json"});
      const a = document.createElement("a");
      a.href = URL.createObjectURL(blob);
      a.download = "tings-config.json";
      a.click();
      console.log('Config exported');
    };
  }

  const importBtn = document.getElementById('import-btn');
  if (importBtn) {
    importBtn.onclick = () => document.getElementById('import-file').click();
  }

  const importFile = document.getElementById('import-file');
  if (importFile) {
    importFile.onchange = (e) => {
      const file = e.target.files[0];
      if (!file) return;
      const reader = new FileReader();
      reader.onload = ev => {
        try {
          config = JSON.parse(ev.target.result);
          saveConfig();
          initGrid();
          alert('Config imported successfully!');
        } catch(err) {
          alert('Invalid config file');
        }
      };
      reader.readAsText(file);
    };
  }

  const resetBtn = document.getElementById('reset-btn');
  if (resetBtn) {
    resetBtn.onclick = () => {
      if (confirm('Reset to default clean dashboard?')) {
        localStorage.removeItem('tingsConfig');
        location.reload();
      }
    };
  }

  const closeOverlay = document.getElementById('close-overlay');
  if (closeOverlay) {
    closeOverlay.onclick = () => document.getElementById('overlay').classList.add('hidden');
  }
}

window.addEventListener('load', () => {
  console.log('%cTings Dashboard loading...', 'color:#00ffcc');
  loadConfig();
  initGrid();
  attachListeners();
  console.log('%cTings Dashboard ready - Try clicking Edit Mode', 'color:#00ffcc');
});
JS;

    // ==================== fix.html ====================
    $fixHTML = <<<HTML
<!DOCTYPE html>
<html>
<head>
  <title>Tings Fix Tool</title>
  <style>
    body { background:#0a0a14; color:#0f0; font-family:sans-serif; text-align:center; padding:100px 20px; }
    button { padding:15px 40px; font-size:1.3rem; background:#00ffcc; color:#000; border:none; border-radius:8px; cursor:pointer; }
  </style>
</head>
<body>
  <h1>Tings Dashboard Fix Tool</h1>
  <p>If buttons still don't work, click below to reset:</p>
  <button onclick="localStorage.removeItem('tingsConfig'); alert('Reset done!'); window.location='index.html';">
    RESET DASHBOARD
  </button>
  <p style="margin-top:60px;">
    <a href="index.html" style="color:#0f0; font-size:1.2rem;">→ Open Tings Dashboard</a>
  </p>
</body>
</html>
HTML;

    writeFile('index.html', $indexHTML);
    writeFile('style.css', $styleCSS);
    writeFile('script.js', $scriptJS);
    writeFile('fix.html', $fixHTML);

    echo "<h2 style='color:#0f0'>All files updated!</h2>";
    echo "<p><a href='index.html' style='color:#0f0; font-size:1.3rem;'>→ Open Tings Dashboard</a></p>";
    echo "<p><a href='fix.html' style='color:#aaa;'>→ Open Fix Tool</a></p>";

    exit;
}
?>

<!DOCTYPE html>
<html>
<head>
  <title>Tings dev.php</title>
  <style>
    body { background:#0a0a14; color:#eee; font-family:sans-serif; padding:40px; text-align:center; }
    button { padding:18px 50px; font-size:1.4rem; background:#00ffcc; color:#000; border:none; border-radius:10px; cursor:pointer; }
  </style>
</head>
<body>
  <h1>Tings Dashboard Setup Tool</h1>
  <p>Click the button below to create/update all files with fixes.</p>
  <form method="post">
    <button type="submit">CREATE / UPDATE ALL FILES (Fixed Version)</button>
  </form>
</body>
</html>