<?php
session_start();
require __DIR__ . '/includes/admin_lib.php';
include __DIR__ . '/includes/admin_header.php';


$action = $_GET['action'] ?? '';
if ($action === 'import') {
  if (!$CAN_EDIT) die("<h1>Access Denied</h1><p>You do not have permission to import the schedule.</p>");
  $txtFile = __DIR__ . '/../data/schedule.txt';
  $days = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];
  if (file_exists($txtFile) && filesize($txtFile) > 0) {
    $out = [];
    foreach ($days as $d) $out[$d] = [];
    foreach (file($txtFile, FILE_IGNORE_NEW_LINES) as $line) {
      $line = trim($line);
      if ($line === '' || str_starts_with($line,'#')) continue;
      $parts = array_map('trim', explode('|', $line));
      if (count($parts) < 3) continue;
      $day = $parts[0];
      $time = $parts[1];
      if (!in_array($day, $days, true)) continue;
      if (!preg_match('/^\d{2}:\d{2}$/', $time)) continue;
      $title=''; $dj='';
      if (count($parts) >= 4) { $title=$parts[2]; $dj=$parts[3]; } else { $dj=$parts[2]; }
      $out[$day][] = ['time'=>$time,'title'=>$title,'dj'=>$dj];
    }
    smurf_write_json($scheduleFile, $out);
    header("Location: /admin/schedule.php?imported=1");
    exit;
  } else {
    header("Location: /admin/schedule.php?imported=0");
    exit;
  }
}

$scheduleFile = __DIR__ . '/../data/schedule.json';
$schedule = smurf_read_json($scheduleFile, new stdClass());

$raw = file_exists($scheduleFile) ? file_get_contents($scheduleFile) : "{}\n";
$error = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (!$CAN_EDIT) die("<h1>Access Denied</h1><p>You do not have permission to edit the schedule.</p>");
  $raw = trim($_POST['json'] ?? '');
  $parsed = json_decode($raw, true);

  if (is_null($parsed)) {
    $error = "Invalid JSON. Please fix and try again.";
  } else {
    smurf_write_json($scheduleFile, $parsed);
    $saved = true;
    $raw = file_get_contents($scheduleFile);
  }
}
?>
<section class="content-card">
  <h1 class="admin-title">📅 Schedule Editor</h1>
  <p style="margin-top:6px;">
    <a class="admin-btn" href="/admin/schedule.php?action=import">⬇️ Import schedule.txt</a>
  </p>
  <?php if (isset($_GET['imported'])): ?>
    <?php if ($_GET['imported'] == '1'): ?>
      <div class="msg success">Imported schedule.txt into schedule.json.</div>
    <?php else: ?>
      <div class="msg error">No schedule.txt found to import.</div>
    <?php endif; ?>
  <?php endif; ?>
  <p style="opacity:.8;">Front-end reads: <code>/data/schedule.json</code> (used by <code>/schedule.php</code>)</p>

  <?php if ($error): ?>
    <div class="msg error"><?= smurf_h($error) ?></div>
  <?php elseif (!empty($saved)): ?>
    <div class="msg success">Saved.</div>
  <?php endif; ?>

  <div class="content-card" style="text-align:left;">
    <p style="margin-top:0;opacity:.9;">
      Format: <code>{"Monday":{"0":"Show name","1":"..."},"Tuesday":{...}}</code><br>
      Hours are <strong>0–23</strong> (UK time). Missing hours just show blank.
    </p>
  </div>

  <form method="POST" class="form">
    <textarea name="json" class="input-field" rows="18" <?= $CAN_EDIT ? '' : 'disabled' ?>><?= smurf_h($raw) ?></textarea>

    <?php if ($CAN_EDIT): ?>
      <button class="admin-btn primary" type="submit" style="margin-top:12px;">Save Schedule</button>
    <?php else: ?>
      <p style="opacity:.7;margin-top:10px;">View-only mode — editing disabled.</p>
    <?php endif; ?>
  </form>
</section>

<?php include __DIR__ . '/includes/admin_footer.php'; ?>
