<?php require_once __DIR__ . '/includes/admin_bootstrap.php';
ugfx_require_permission('schedule');
$schedule = ugfx_read_json($ugfx['storage']['schedule'], []);
$message = '';
$days = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];

function ugfx_admin_schedule_label(int $hour): string {
    return sprintf('%02d:00', $hour);
}

function ugfx_admin_schedule_is_auto(string $show): bool {
    return stripos($show, 'autodj') !== false || stripos($show, 'automix') !== false || strcasecmp(trim($show), 'FX Vibe Radio Flow') === 0 || trim($show) === '';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $newSchedule = [];
    foreach ($days as $day) {
        $posted = $_POST['day_'.$day] ?? [];
        if (!is_array($posted)) {
            $posted = preg_split('/
|
|
/', (string) $posted);
        }
        $lines = array_map(static fn($v) => trim((string) $v), $posted);
        $lines = array_pad(array_slice($lines, 0, 24), 24, 'FX Vibe Radio Flow');
        $lines = array_map(static fn($v) => $v !== '' ? $v : 'FX Vibe Radio Flow', $lines);
        $newSchedule[$day] = array_values($lines);
    }
    ugfx_write_json($ugfx['storage']['schedule'], $newSchedule);
    $schedule = $newSchedule;
    $message = 'Schedule updated for all days.';
}

$today = ugfx_day_name();
$currentHour = (int) date('G');
$currentShow = $schedule[$today][$currentHour] ?? 'FX Vibe Radio Flow';
$nextHour = ($currentHour + 1) % 24;
$nextShow = $schedule[$today][$nextHour] ?? 'FX Vibe Radio Flow';
$adminTitle='Schedule'; include __DIR__ . '/includes/admin_header.php'; ?>
<?php if ($message): ?><div class="ugfx-admin-alert"><?= htmlspecialchars($message) ?></div><?php endif; ?>

<div class="ugfx-card ugfx-schedule-hero-card p-4 mb-4">
  <div class="ugfx-micro-label">SCHEDULE CONTROL</div>
  <h3 class="mb-2">Editable weekly schedule</h3>
  <p class="mb-0 ugfx-admin-copy">Edit each hour with the same live and next-show context as the public schedule. Blank slots are automatically filled with <strong>FX Vibe Radio Flow</strong>.</p>
</div>

<div class="ugfx-schedule-mini-bar mb-3">
  <div class="ugfx-card ugfx-schedule-mini-card">
    <div class="ugfx-schedule-mini-label"><i class="bi bi-broadcast-pin"></i> Live right now</div>
    <strong><?= htmlspecialchars((string)$currentShow) ?></strong>
    <small><?= htmlspecialchars((string)$today) ?> · <?= date('g:i A') ?></small>
  </div>
  <div class="ugfx-card ugfx-schedule-mini-card">
    <div class="ugfx-schedule-mini-label"><i class="bi bi-clock-history"></i> Up next</div>
    <strong><?= htmlspecialchars((string)$nextShow) ?></strong>
    <small>Starts <?= date('g:i A', strtotime(sprintf('%02d:00', $nextHour))) ?></small>
  </div>
</div>

<form method="post" class="ugfx-admin-form">
  <div class="ugfx-card ugfx-schedule-shell-premium p-3 p-lg-4">
    <div class="ugfx-schedule-tabs-premium" role="tablist" aria-label="Schedule days">
      <?php foreach ($days as $index => $day): ?>
        <?php $isActive = $index === 0; ?>
        <button class="ugfx-schedule-day-btn <?= $isActive ? 'is-active' : '' ?>" type="button" data-admin-schedule-day="<?= htmlspecialchars($day) ?>" aria-pressed="<?= $isActive ? 'true' : 'false' ?>">
          <?= htmlspecialchars($day) ?>
        </button>
      <?php endforeach; ?>
    </div>

    <?php foreach ($days as $index => $day): ?>
      <?php $isActive = $index === 0; ?>
      <div class="ugfx-schedule-day-panel <?= $isActive ? 'is-active' : '' ?>" data-admin-schedule-panel="<?= htmlspecialchars($day) ?>">
        <div class="ugfx-schedule-day-head">
          <h2><?= htmlspecialchars($day) ?></h2>
          <span class="ugfx-chip">24 editable hours</span>
        </div>

        <div class="ugfx-schedule-grid-premium ugfx-admin-schedule-premium-grid">
          <?php foreach ([['label' => 'Morning / Day', 'start' => 0, 'end' => 11], ['label' => 'Evening / Night', 'start' => 12, 'end' => 23]] as $period): ?>
            <div class="ugfx-card ugfx-schedule-period-card">
              <div class="ugfx-schedule-period-head">
                <h3><?= htmlspecialchars($period['label']) ?></h3>
              </div>
              <div class="ugfx-schedule-period-list">
                <?php for ($hour = $period['start']; $hour <= $period['end']; $hour++): ?>
                  <?php $value = (string)($schedule[$day][$hour] ?? 'FX Vibe Radio Flow'); ?>
                  <?php $isAuto = ugfx_admin_schedule_is_auto($value); ?>
                  <label class="ugfx-schedule-row <?= $isAuto ? 'is-auto' : 'is-dj' ?> ugfx-admin-schedule-row">
                    <span class="ugfx-schedule-time-pill"><?= htmlspecialchars(date('g:00 A', strtotime(sprintf('%02d:00', $hour)))) ?></span>
                    <span class="ugfx-schedule-show-pill ugfx-admin-schedule-input-wrap">
                      <input type="text" class="form-control ugfx-admin-schedule-input" name="day_<?= htmlspecialchars($day) ?>[]" value="<?= htmlspecialchars($value) ?>" placeholder="FX Vibe Radio Flow">
                      <?php if ($day === $today && $hour === $currentHour): ?><span class="ugfx-live-pill">LIVE</span><?php endif; ?>
                    </span>
                  </label>
                <?php endfor; ?>
              </div>
            </div>
          <?php endforeach; ?>
        </div>
      </div>
    <?php endforeach; ?>
  </div>

  <div class="d-flex gap-2 flex-wrap mt-3">
    <button class="btn ugfx-btn-primary" type="submit">Save weekly schedule</button>
  </div>
</form>

<script>
document.addEventListener('DOMContentLoaded', function () {
  const tabs = Array.from(document.querySelectorAll('[data-admin-schedule-day]'));
  const panels = Array.from(document.querySelectorAll('[data-admin-schedule-panel]'));
  if (!tabs.length || !panels.length) return;

  function activate(day) {
    tabs.forEach((tab) => {
      const active = tab.getAttribute('data-admin-schedule-day') === day;
      tab.classList.toggle('is-active', active);
      tab.setAttribute('aria-pressed', active ? 'true' : 'false');
    });
    panels.forEach((panel) => {
      panel.classList.toggle('is-active', panel.getAttribute('data-admin-schedule-panel') === day);
    });
  }

  tabs.forEach((tab) => tab.addEventListener('click', () => activate(tab.getAttribute('data-admin-schedule-day'))));
});
</script>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>