<?php
session_start();
include __DIR__ . '/auth.php'; // sets $CAN_EDIT

include __DIR__ . '/includes/header.php';
include __DIR__ . '/includes/sidebar.php';

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

/* Load schedule */
if (file_exists($scheduleFile)) {
    $lines = file($scheduleFile, FILE_IGNORE_NEW_LINES);
    foreach ($lines as $line) {
        [$day, $hour, $dj] = explode('|', trim($line));
        $schedule[$day][$hour] = $dj;
    }
}

/* Days in order */
$daysOrder = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];

/* Convert 24h to 12h format */
function formatHour($hour24) {
    $hour = (int)substr($hour24, 0, 2);
    $suffix = $hour >= 12 ? 'PM' : 'AM';
    $hour12 = $hour % 12;
    if ($hour12 === 0) $hour12 = 12;
    return $hour12 . ':00 ' . $suffix;
}

$errorMessage = '';
$successMessage = '';

/* Handle save (EDIT PERMISSION REQUIRED) */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (!$CAN_EDIT) {
        die("<h1>Access Denied</h1><p>You cannot edit the schedule.</p>");
    }

    $newSchedule = [];

    foreach ($_POST['dj'] as $day => $slots) {
        foreach ($slots as $hour => $djName) {
            $djName = trim($djName);

            if ($djName === '') {
                $errorMessage = "All time slots must have a DJ name. Missing at $day $hour.";
                break 2;
            }

            $newSchedule[] = "$day|$hour|$djName";
        }
    }

    if (!$errorMessage) {
        file_put_contents($scheduleFile, implode("\n", $newSchedule));
        $successMessage = "Schedule updated successfully!";

        // Reload
        $schedule = [];
        foreach ($newSchedule as $line) {
            [$day, $hour, $dj] = explode('|', $line);
            $schedule[$day][$hour] = $dj;
        }
    }
}

/* Current EST time for LIVE highlight */
$nowEST = new DateTime("now", new DateTimeZone("America/New_York"));
$currentHourEST = $nowEST->format("H") . ":00";
$currentDayEST = $nowEST->format("l");
?>

<div class="main-wrap">
    <div class="content-panel">

        <div class="schedule-banner">
            <h1 class="schedule-banner-text">📅 Edit Weekly DJ Schedule</h1>
            <p class="schedule-subtext">All times are Eastern Standard Time — emojis welcome 🎧🎶📻</p>
        </div>

        <?php if ($errorMessage): ?>
            <div class="msg error center-text"><?= htmlspecialchars($errorMessage) ?></div>
        <?php elseif ($successMessage): ?>
            <div class="msg success center-text"><?= htmlspecialchars($successMessage) ?></div>
        <?php endif; ?>

        <div class="vinyl-divider center-divider"></div>

        <form method="POST">

            <?php foreach ($daysOrder as $day): ?>
                <?php if (!isset($schedule[$day])) continue; ?>
                <?php $slots = $schedule[$day]; ?>

                <div class="neon-card schedule-day">

                    <h2 class="schedule-day-title"><?= htmlspecialchars($day) ?></h2>

                    <div class="schedule-columns-2">

                        <!-- MORNING -->
                        <div class="schedule-column">
                            <h3 class="schedule-period">🌅 Morning</h3>
                            <ul class="schedule-list">
                                <?php foreach ($slots as $hour => $dj): ?>
                                    <?php $h = (int)substr($hour, 0, 2); ?>
                                    <?php if ($h >= 6 && $h < 18): ?>
                                        <?php $isLive = ($hour === $currentHourEST && $day === $currentDayEST); ?>

                                        <li class="<?= $isLive ? 'live-now' : '' ?>">
                                            <span class="schedule-time"><?= formatHour($hour) ?></span>

                                            <input
                                                type="text"
                                                name="dj[<?= $day ?>][<?= $hour ?>]"
                                                class="input-field"
                                                value="<?= htmlspecialchars($dj) ?>"
                                                <?= $CAN_EDIT ? '' : 'readonly' ?>
                                                required
                                                style="display:inline-block; max-width:260px; margin-left:10px;"
                                            >

                                            <?php if ($isLive): ?>
                                                <span class="live-now-badge">LIVE NOW</span>
                                            <?php endif; ?>
                                        </li>

                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </ul>
                        </div>

                        <!-- EVENING -->
                        <div class="schedule-column">
                            <h3 class="schedule-period">🌙 Evening</h3>
                            <ul class="schedule-list">
                                <?php foreach ($slots as $hour => $dj): ?>
                                    <?php $h = (int)substr($hour, 0, 2); ?>
                                    <?php if ($h >= 18 || $h < 6): ?>
                                        <?php $isLive = ($hour === $currentHourEST && $day === $currentDayEST); ?>

                                        <li class="<?= $isLive ? 'live-now' : '' ?>">
                                            <span class="schedule-time"><?= formatHour($hour) ?></span>

                                            <input
                                                type="text"
                                                name="dj[<?= $day ?>][<?= $hour ?>]"
                                                class="input-field"
                                                value="<?= htmlspecialchars($dj) ?>"
                                                <?= $CAN_EDIT ? '' : 'readonly' ?>
                                                required
                                                style="display:inline-block; max-width:260px; margin-left:10px;"
                                            >

                                            <?php if ($isLive): ?>
                                                <span class="live-now-badge">LIVE NOW</span>
                                            <?php endif; ?>
                                        </li>

                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </ul>
                        </div>

                    </div>
                </div>

                <div class="vinyl-divider center-divider"></div>

            <?php endforeach; ?>

            <?php if ($CAN_EDIT): ?>
                <div class="content-box center-text">
                    <button type="submit" class="button radio-static">💾 Save Schedule</button>
                </div>
            <?php else: ?>
                <div class="content-box center-text" style="opacity:0.6;">
                    <p>You can view the schedule, but you cannot edit it.</p>
                </div>
            <?php endif; ?>

        </form>

    </div>
</div>

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