<?php
session_start();


// Optional: restrict access
$role = $_SESSION['role'] ?? 'guest';
if (!in_array($role, ['admin', 'master'])) {
  header('Location: /login/index.php');
  exit;
}

include '../header.php';
include '../menu.php';

$scheduleFile = '../data/schedule.txt';
$schedule = [];

if (file_exists($scheduleFile)) {
  $lines = file($scheduleFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
  foreach ($lines as $line) {
    $parts = explode('|', trim($line));
    if (count($parts) === 3) {
      [$day, $hour, $dj] = $parts;
      $hour = trim($hour); // e.g., "08:00"
      $schedule[$day][$hour] = $dj;
    }
  }
}

$days = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];
$hours = [];
for ($h = 0; $h < 24; $h++) {
  $hours[] = str_pad($h, 2, '0', STR_PAD_LEFT) . ':00';
}

function formatHour($hour24) {
  $parts = explode(':', $hour24);
  $hour = (int)$parts[0];
  $suffix = $hour >= 12 ? 'PM' : 'AM';
  $hour12 = $hour % 12;
  if ($hour12 === 0) $hour12 = 12;
  return $hour12 . ':00 ' . $suffix;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['dj'])) {
  $newSchedule = ["Timezone|EST"];
  foreach ($_POST['dj'] as $day => $slots) {
    foreach ($slots as $hour => $dj) {
      $dj = trim($dj);
      if ($dj !== '') {
        $newSchedule[] = "$day|$hour|$dj";
      }
    }
  }
  file_put_contents($scheduleFile, implode("\n", $newSchedule));
  header('Location: Schedule_update.php');
  exit;
}
?>

<main class="main-container">
  <section class="content-box">
    <h2 class="text-warning">🛠️ Edit DJ Schedule</h2>
    <p class="text-muted mb-3">Update DJ names below. All times are Eastern Standard (12-hour format).</p>

    <form method="POST">
      <?php foreach ($days as $day): ?>
        <div class="content-box mb-4">
          <h3 class="text-warning"><?= $day ?></h3>
          <div class="schedule-edit-table">
            <table>
              <thead>
                <tr>
                  <th>Time</th>
                  <th>DJ Name</th>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($hours as $hour): ?>
                  <?php
                    $currentDJ = $schedule[$day][$hour] ?? '';
                    $timeLabel = formatHour($hour);
                  ?>
                  <tr>
                    <td class="time-divider"><?= $timeLabel ?></td>
                    <td>
                      <input type="text" name="dj[<?= $day ?>][<?= $hour ?>]" value="<?= htmlspecialchars($currentDJ) ?>" class="form-control">
                    </td>
                  </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        </div>
      <?php endforeach; ?>
      <button type="submit" class="btn btn-warning mt-3">💾 Save Schedule</button>
    </form>
  </section>
</main>

<?php include '../footer.php'; ?>
