<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Csrf;
use App\Repositories\Container;

class AdminScheduleController
{
    public function edit(array $params): void
    {
        $artist = Container::artists()->find($params['id'] ?? '');
        if (!$artist) { http_response_code(404); require MAT_ROOT . '/src/Views/errors/404.php'; return; }
        $weekly = Container::schedules()->weeklyForArtist($artist['id']);
        $exceptions = Container::schedules()->exceptionsForArtistInRange(
            $artist['id'],
            date('Y-m-d'),
            date('Y-m-d', strtotime('+6 months'))
        );
        render('admin', 'admin.schedule', compact('artist', 'weekly', 'exceptions'), $artist['display_name'] ?? '');
    }

    public function update(array $params): void
    {
        Csrf::requireValid();
        $artist = Container::artists()->find($params['id'] ?? '');
        if (!$artist) redirect('/admin/artists');

        $rows = [];
        for ($wd = 0; $wd < 7; $wd++) {
            if (empty($_POST['enabled'][$wd])) continue;
            $start = $_POST['start'][$wd] ?? null;
            $end   = $_POST['end'][$wd]   ?? null;
            if ($start && $end && $start < $end) {
                $rows[] = ['weekday' => $wd, 'start_time' => $start, 'end_time' => $end];
            }
        }
        Container::schedules()->replaceWeekly($artist['id'], $rows);

        if (!empty($_POST['exception_date'])) {
            Container::schedules()->addException([
                'artist_id' => $artist['id'],
                'date' => $_POST['exception_date'],
                'start_time' => $_POST['exception_start'] ?: null,
                'end_time' => $_POST['exception_end'] ?: null,
                'is_day_off' => !empty($_POST['is_day_off']),
                'reason' => trim((string)($_POST['exception_reason'] ?? '')),
            ]);
        }

        $_SESSION['_flash']['success'] = t('admin.schedule.saved');
        redirect('/admin/artists/' . $artist['id'] . '/schedule');
    }
}
