<?php
declare(strict_types=1);
require_once __DIR__ . '/bootstrap.php';
admin_require_login();

$houses = cms_collection('houses')['items'] ?? [];
$availability = cms_availability();
$notice = '';

if (request_method() === 'POST') {
    if (!verify_csrf($_POST['csrf_token'] ?? null)) {
        $notice = '<div class="notice notice--error">Ошибка безопасности.</div>';
    } else {
        $payload = json_decode((string)($_POST['availability_payload'] ?? '{}'), true);
        if (!is_array($payload)) {
            $notice = '<div class="notice notice--error">Не удалось сохранить календарь.</div>';
        } else {
            $clean = ['global' => [], 'houses' => []];
            foreach (($payload['global'] ?? []) as $date) {
                if (preg_match('/^\d{4}-\d{2}-\d{2}$/', (string)$date)) {
                    $clean['global'][] = (string)$date;
                }
            }
            foreach (($payload['houses'] ?? []) as $slug => $dates) {
                $slug = slugify((string)$slug);
                foreach ((array)$dates as $date) {
                    if (preg_match('/^\d{4}-\d{2}-\d{2}$/', (string)$date)) {
                        $clean['houses'][$slug][] = (string)$date;
                    }
                }
                if (isset($clean['houses'][$slug])) {
                    $clean['houses'][$slug] = array_values(array_unique($clean['houses'][$slug]));
                    sort($clean['houses'][$slug]);
                }
            }
            $clean['global'] = array_values(array_unique($clean['global']));
            sort($clean['global']);
            cms_save_availability($clean);
            $availability = $clean;
            $notice = '<div class="notice">Календарь сохранён.</div>';
        }
    }
}

$houseMap = [];
foreach ($houses as $house) {
    $title = (string)($house['title'] ?? 'Домик');
    $houseMap[slugify($title)] = $title;
}

ob_start();
echo $notice;
?>
<div class="panel">
  <p class="muted">Минималистичный календарь: один месяц на экране, стрелками можно перейти вперёд или назад. Клик по дню открывает или закрывает дату. Глобальные даты блокируют все домики сразу.</p>
  <form method="post" id="availability-form">
    <input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>">
    <input type="hidden" name="availability_payload" id="availability_payload">
    <div class="module-actions" style="margin-bottom:16px">
      <button class="button button--ghost is-filter" type="button" data-calendar-target="global">Все домики</button>
      <?php foreach ($houseMap as $slug => $title): ?>
        <button class="button button--ghost is-filter" type="button" data-calendar-target="<?= e($slug) ?>"><?= e($title) ?></button>
      <?php endforeach; ?>
    </div>
    <div id="admin-availability" data-calendar-admin></div>
    <script id="admin-availability-data" type="application/json"><?= json_encode($availability, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?></script>
    <script id="admin-houses-data" type="application/json"><?= json_encode($houseMap, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?></script>
    <div class="module-actions" style="margin-top:18px">
      <button class="button" type="submit">Сохранить календарь</button>
    </div>
  </form>
</div>
<?php
admin_layout('Календарь доступности', ob_get_clean(), 'availability');
