<?php
require_once __DIR__ . '/../includes/bootstrap.php';
$config = load_config();
$loggedIn = is_admin();
?><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Developer Admin</title>
  <link rel="stylesheet" href="../assets/app.css" />
  <style>
    .admin-wrap{max-width:1000px;margin:0 auto;padding:20px}
    .login-box{max-width:420px;margin:60px auto}
    .stack{display:grid;gap:12px}
    .frame-admin{display:grid;grid-template-columns:1fr 1fr;gap:16px}
    .frame-card{padding:14px;border:1px solid rgba(255,255,255,.08);border-radius:16px;background:rgba(255,255,255,.03)}
    .frame-card img{width:100%;max-width:220px;border-radius:12px;display:block;margin-bottom:10px}
    @media(max-width:900px){.frame-admin{grid-template-columns:1fr}}
  </style>
</head>
<body>
<div class="admin-wrap">
  <div class="topbar">
    <div>
      <h1>Developer Admin</h1>
      <p>Manage photo frames and site settings for all users.</p>
    </div>
    <a class="admin-link" href="../index.php">Back to Site</a>
  </div>

  <?php if (!$loggedIn): ?>
  <div class="panel login-box">
    <div class="panel-header">
      <h2>Login</h2>
      <p>Default password is cityboyadmin. Change it after first setup in data/config.json.</p>
    </div>
    <div class="panel-body stack">
      <input type="password" id="adminPassword" placeholder="Enter password" />
      <button class="btn" id="loginBtn">Login</button>
      <div class="status" id="loginStatus"></div>
    </div>
  </div>
  <?php else: ?>
  <div class="panel">
    <div class="panel-header">
      <h2>Global Settings</h2>
      <p>These settings appear on the public frontend.</p>
    </div>
    <div class="panel-body stack">
      <label>Site Title</label>
      <input type="text" id="siteTitleInput" value="<?= e($config['siteTitle'] ?? '') ?>" />
      <label>Footer Text</label>
      <input type="text" id="footerTextInput" value="<?= e($config['footerText'] ?? '') ?>" />
      <button class="btn success" id="saveSettingsBtn">Save Settings</button>
      <div class="status" id="settingsStatus"></div>
    </div>
  </div>

  <div style="height:18px"></div>

  <div class="panel">
    <div class="panel-header">
      <h2>Frame Templates</h2>
      <p>Upload transparent PNG frames here. These remain saved for all public users.</p>
    </div>
    <div class="panel-body frame-admin">
      <?php foreach (($config['frames'] ?? []) as $frame): ?>
      <div class="frame-card">
        <img src="../frames/<?= e($frame['file']) ?>?v=<?= time() ?>" alt="<?= e($frame['name']) ?>">
        <div class="stack">
          <label>Frame Name</label>
          <input type="text" class="frame-name" data-id="<?= (int)$frame['id'] ?>" value="<?= e($frame['name']) ?>">
          <label>Replace PNG Overlay</label>
          <input type="file" class="frame-file" data-id="<?= (int)$frame['id'] ?>" accept="image/png">
          <button class="btn secondary upload-frame-btn" data-id="<?= (int)$frame['id'] ?>">Upload Frame <?= (int)$frame['id'] ?></button>
          <div class="status frame-status" id="frame-status-<?= (int)$frame['id'] ?>"></div>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
    <div class="panel-body">
      <button class="btn" id="saveFrameNamesBtn">Save Frame Names</button>
      <a class="btn secondary" style="text-decoration:none" href="../api/logout.php">Logout</a>
      <div class="status" id="frameNamesStatus"></div>
    </div>
  </div>
  <?php endif; ?>
</div>

<script>
window.ADMIN_STATE = {
  loggedIn: <?= $loggedIn ? 'true' : 'false' ?>,
  frames: <?= json_encode($config['frames'] ?? [], JSON_UNESCAPED_SLASHES) ?>
};
</script>
<script>
(async function() {
  const qs = s => document.querySelector(s);
  const qsa = s => Array.from(document.querySelectorAll(s));
  if (!window.ADMIN_STATE.loggedIn) {
    const btn = qs('#loginBtn');
    if (btn) {
      btn.onclick = async () => {
        const fd = new FormData();
        fd.append('password', qs('#adminPassword').value);
        const res = await fetch('../api/login.php', { method: 'POST', body: fd });
        const data = await res.json();
        const s = qs('#loginStatus');
        s.textContent = data.message;
        s.className = 'status ' + (data.ok ? 'good' : 'bad');
        if (data.ok) location.reload();
      };
    }
    return;
  }
  qs('#saveSettingsBtn').onclick = async () => {
    const fd = new FormData();
    fd.append('siteTitle', qs('#siteTitleInput').value);
    fd.append('footerText', qs('#footerTextInput').value);
    fd.append('frames', JSON.stringify(window.ADMIN_STATE.frames));
    const res = await fetch('../api/save-config.php', { method: 'POST', body: fd });
    const data = await res.json();
    const s = qs('#settingsStatus');
    s.textContent = data.message;
    s.className = 'status ' + (data.ok ? 'good' : 'bad');
  };
  qs('#saveFrameNamesBtn').onclick = async () => {
    qsa('.frame-name').forEach(input => {
      const id = Number(input.dataset.id);
      const f = window.ADMIN_STATE.frames.find(x => Number(x.id) === id);
      if (f) f.name = input.value.trim() || f.name;
    });
    const fd = new FormData();
    fd.append('siteTitle', qs('#siteTitleInput').value);
    fd.append('footerText', qs('#footerTextInput').value);
    fd.append('frames', JSON.stringify(window.ADMIN_STATE.frames));
    const res = await fetch('../api/save-config.php', { method: 'POST', body: fd });
    const data = await res.json();
    const s = qs('#frameNamesStatus');
    s.textContent = data.message;
    s.className = 'status ' + (data.ok ? 'good' : 'bad');
  };
  qsa('.upload-frame-btn').forEach(btn => {
    btn.onclick = async () => {
      const id = btn.dataset.id;
      const input = qs(`.frame-file[data-id="${id}"]`);
      const status = qs(`#frame-status-${id}`);
      if (!input.files[0]) {
        status.textContent = 'Choose a PNG first.';
        status.className = 'status bad';
        return;
      }
      const fd = new FormData();
      fd.append('frame_id', id);
      fd.append('frame_file', input.files[0]);
      const res = await fetch('../api/upload-frame.php', { method: 'POST', body: fd });
      const data = await res.json();
      status.textContent = data.message;
      status.className = 'status ' + (data.ok ? 'good' : 'bad');
      if (data.ok) setTimeout(() => location.reload(), 800);
    };
  });
})();
</script>
</body>
</html>
