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


$scheduleFile = __DIR__ . '/../data/schedule.json';
$txtFile      = __DIR__ . '/../data/schedule.txt';
$days         = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];

function smurf_schedule_normalize($data) {
  global $days;
  $out = [];
  foreach ($days as $d) $out[$d] = [];

  if (!is_array($data)) return $out;

  // Detect list-of-objects format
  $looksLikeList = false;
  foreach ($days as $d) {
    if (!isset($data[$d])) continue;
    if (isset($data[$d][0]) && is_array($data[$d][0]) && isset($data[$d][0]['time'])) { $looksLikeList = true; break; }
  }

  if ($looksLikeList) {
    foreach ($days as $d) {
      $list = (isset($data[$d]) && is_array($data[$d])) ? $data[$d] : [];
      foreach ($list as $row) {
        if (!is_array($row)) continue;
        $time = trim((string)($row['time'] ?? ''));
        if (!preg_match('/^\d{2}:\d{2}$/', $time)) continue;
        $hour = (int)substr($time,0,2);

        $title = trim((string)($row['title'] ?? ''));
        $dj    = trim((string)($row['dj'] ?? ''));
        $val   = ($title !== '' ? $title : $dj);
        if ($title !== '' && $dj !== '' && $title !== $dj) $val = $title . ' — ' . $dj;
        if ($val !== '') $out[$d][$hour] = $val;
      }
      ksort($out[$d]);
    }
    return $out;
  }

  // Hour=>string format (expected)
  foreach ($days as $d) {
    $map = (isset($data[$d]) && is_array($data[$d])) ? $data[$d] : [];
    foreach ($map as $h => $val) {
      if (!is_numeric($h)) continue;
      $hh = (int)$h;
      if ($hh < 0 || $hh > 23) continue;
      $val = trim((string)$val);
      if ($val === '') continue;
      $out[$d][$hh] = $val;
    }
    ksort($out[$d]);
  }

  return $out;
}

function smurf_schedule_read($file) {
  $raw = (file_exists($file) ? file_get_contents($file) : '');
  $j = json_decode($raw, true);
  return smurf_schedule_normalize($j);
}

function smurf_schedule_write($file, $data) {
  @file_put_contents($file, json_encode($data, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT), LOCK_EX);
}

// Import action: schedule.txt -> schedule.json (hour=>string)
$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>");

  $out = [];
  foreach ($days as $d) $out[$d] = [];

  if (file_exists($txtFile) && filesize($txtFile) > 0) {
    foreach (file($txtFile, FILE_IGNORE_NEW_LINES) as $line) {
      $line = trim($line);
      if ($line === '' || (isset($line[0]) && $line[0] === '#')) continue;

      // Day|HH:MM|DJ
      // Day|HH:MM|Show Title|DJ
      $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;

      $hour = (int)substr($time, 0, 2);

      $title = '';
      $dj = '';
      if (count($parts) >= 4) { $title = $parts[2]; $dj = $parts[3]; }
      else { $dj = $parts[2]; }

      $val = ($title !== '' ? $title : $dj);
      if ($title !== '' && $dj !== '' && $title !== $dj) $val = $title . ' — ' . $dj;

      if ($val !== '') $out[$day][$hour] = $val;
    }

    foreach ($days as $d) ksort($out[$d]);
    smurf_schedule_write($scheduleFile, $out);
    header("Location: /admin/schedule.php?imported=1");
    exit;
  }

  header("Location: /admin/schedule.php?imported=0");
  exit;
}

$schedule = smurf_schedule_read($scheduleFile);
$error = '';
$saved = !empty($_GET['saved']);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (!$CAN_EDIT) die("<h1>Access Denied</h1><p>You do not have permission to edit the schedule.</p>");

  $posted = $_POST['sched'] ?? [];
  $out = [];
  foreach ($days as $d) $out[$d] = [];

  if (is_array($posted)) {
    foreach ($days as $d) {
      $rows = $posted[$d] ?? [];
      if (!is_array($rows)) $rows = [];
      foreach ($rows as $h => $val) {
        if (!is_numeric($h)) continue;
        $hh = (int)$h;
        if ($hh < 0 || $hh > 23) continue;
        $val = trim((string)$val);
        if ($val === '') continue;
        $out[$d][$hh] = $val;
      }
      ksort($out[$d]);
    }
  }

  smurf_schedule_write($scheduleFile, $out);
  smurf_redirect_self(['saved'=>1], ['imported']);
}

function fmt_hour_12($h){ return date('g:00 A', strtotime(sprintf('%02d:00', $h))); }
include __DIR__ . '/includes/admin_header.php';
?>

<style>
  .sched-day{
    margin-top:16px;
  }
  .sched-day h2{
    margin:0;
  }
  .sched-split{
    display:grid;
    grid-template-columns: 1fr;
    gap:14px;
    margin-top:12px;
  }
  @media (min-width: 980px){
    .sched-split{ grid-template-columns: 1fr 1fr; }
  }
  .sched-half{
    padding:12px;
    border-radius:14px;
    background: rgba(0,0,0,0.22);
    border:1px solid rgba(255,220,160,.20);
  }
  .sched-half h3{
    margin:0 0 10px 0;
    display:flex;
    align-items:center;
    gap:8px;
    font-size: 1.05rem;
  }
  .sched-row{
    display:grid;
    grid-template-columns: 86px 1fr;
    gap:12px;
    align-items:center;
    padding:10px;
    border-radius:14px;
    background: rgba(0,0,0,0.30);
    border:1px solid rgba(255,220,160,.18);
    margin-bottom:10px;
  }
  .sched-time{
    font-weight:800;
    color: var(--accent);
    text-align:center;
    line-height:1.1;
  }
  .sched-input{
    width:100%;
    padding:12px 14px;
    border-radius:12px;
    border:1px solid rgba(255,220,160,.22);
    background: rgba(0,0,0,0.35);
    color: #fff;
  }
  .sched-input::placeholder{ opacity:.7; }
  .admin-help{
    opacity:.9;
    margin-top:8px;
  }
</style>

<section class="content-card">
  <h1 class="admin-title">📅 Schedule Editor</h1>

  <p style="margin-top:6px;display:flex;gap:10px;flex-wrap:wrap;">
    <a class="admin-btn" href="/admin/schedule.php?action=import">⬇️ Import schedule.txt</a>
    <a class="admin-btn" href="/schedule.php" target="_blank" rel="noopener">👀 View Schedule Page</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; ?>

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

  <div class="content-card" style="text-align:left;">
    <p style="margin:0;opacity:.9;">
      <strong>Tip:</strong> Enter text as <code>Show Name — DJ Name</code> (example: <code>Jukebox Mayhem — DJ BLAZE</code>).<br>
      If you only enter a DJ name, it will still show fine.
    </p>
  </div>

  <form method="POST" class="form">

    <?php foreach ($days as $day): ?>
      <div class="content-card sched-day">
        <h2><?= smurf_h($day) ?></h2>

        <div class="sched-split">
          <div class="sched-half">
            <h3>🌅 Morning</h3>
            <?php for ($h=0; $h<=11; $h++): ?>
              <div class="sched-row">
                <div class="sched-time"><?= smurf_h(fmt_hour_12($h)) ?></div>
                <input
                  class="sched-input"
                  type="text"
                  name="sched[<?= smurf_h($day) ?>][<?= $h ?>]"
                  value="<?= smurf_h($schedule[$day][$h] ?? '') ?>"
                  placeholder="Show — DJ"
                  <?= $CAN_EDIT ? '' : 'disabled' ?>
                />
              </div>
            <?php endfor; ?>
          </div>

          <div class="sched-half">
            <h3>🌙 Evening</h3>
            <?php for ($h=12; $h<=23; $h++): ?>
              <div class="sched-row">
                <div class="sched-time"><?= smurf_h(fmt_hour_12($h)) ?></div>
                <input
                  class="sched-input"
                  type="text"
                  name="sched[<?= smurf_h($day) ?>][<?= $h ?>]"
                  value="<?= smurf_h($schedule[$day][$h] ?? '') ?>"
                  placeholder="Show — DJ"
                  <?= $CAN_EDIT ? '' : 'disabled' ?>
                />
              </div>
            <?php endfor; ?>
          </div>
        </div>
      </div>
    <?php endforeach; ?>

    <?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'; ?>
