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

$settings = cms_settings();
$defaults = cms_booking_form_defaults();
$bookingForm = cms_booking_form_settings($settings);
$notice = '';
$fieldTitles = [
    'name' => 'Имя',
    'phone' => 'Телефон',
    'contact_nick' => 'Telegram / WhatsApp',
    'house' => 'Домик',
    'checkin' => 'Заезд',
    'checkout' => 'Выезд',
    'calendar' => 'Календарь',
    'adults' => 'Взрослые',
    'children' => 'Дети / возраст',
    'pet' => 'Питомец',
    'comment' => 'Комментарий',
];

if (request_method() === 'POST') {
    if (!verify_csrf($_POST['csrf_token'] ?? null)) {
        $notice = '<div class="notice notice--error">Ошибка безопасности.</div>';
    } else {
        $postedFields = $_POST['fields'] ?? [];
        $newConfig = [
            'eyebrow' => post_text('eyebrow', $bookingForm['eyebrow'] ?? ''),
            'title' => post_text('title', $bookingForm['title'] ?? ''),
            'house_description' => post_text('house_description', $bookingForm['house_description'] ?? ''),
            'summary_nights_label' => post_text('summary_nights_label', $bookingForm['summary_nights_label'] ?? ''),
            'summary_total_label' => post_text('summary_total_label', $bookingForm['summary_total_label'] ?? ''),
            'summary_total_empty' => post_text('summary_total_empty', $bookingForm['summary_total_empty'] ?? ''),
            'summary_hint' => post_text('summary_hint', $bookingForm['summary_hint'] ?? ''),
            'lead_text' => post_text('lead_text', $bookingForm['lead_text'] ?? ''),
            'caption' => post_text('caption', $bookingForm['caption'] ?? ''),
            'calendar_label' => post_text('calendar_label', $bookingForm['calendar_label'] ?? ''),
            'submit_label' => post_text('submit_label', $bookingForm['submit_label'] ?? ''),
            'consent_prefix' => post_text('consent_prefix', $bookingForm['consent_prefix'] ?? ''),
            'privacy_link_label' => post_text('privacy_link_label', $bookingForm['privacy_link_label'] ?? ''),
            'privacy_link_url' => post_text('privacy_link_url', $bookingForm['privacy_link_url'] ?? '/politica.php'),
            'consent_middle' => post_text('consent_middle', $bookingForm['consent_middle'] ?? ''),
            'rules_link_label' => post_text('rules_link_label', $bookingForm['rules_link_label'] ?? ''),
            'rules_link_url' => post_text('rules_link_url', $bookingForm['rules_link_url'] ?? '/rools.php'),
            'consent_suffix' => post_text('consent_suffix', $bookingForm['consent_suffix'] ?? ''),
            'fields' => [],
            'field_order' => [],
        ];

        $sortMap = [];
        foreach ($defaults['fields'] as $key => $fieldDefaults) {
            $source = is_array($postedFields[$key] ?? null) ? $postedFields[$key] : [];
            $current = $bookingForm['fields'][$key] ?? $fieldDefaults;
            $field = [
                'label' => trim((string) ($source['label'] ?? ($current['label'] ?? $fieldDefaults['label']))),
                'placeholder' => trim((string) ($source['placeholder'] ?? ($current['placeholder'] ?? $fieldDefaults['placeholder'] ?? ''))),
                'type' => (string) ($fieldDefaults['type'] ?? 'text'),
                'width' => (string) ($source['width'] ?? ($current['width'] ?? $fieldDefaults['width'] ?? 'half')),
                'enabled' => !empty($fieldDefaults['locked_enabled']) ? true : !empty($source['enabled']),
                'required' => !empty($fieldDefaults['locked_required']) ? true : !empty($source['required']),
            ];
            if (!in_array($field['width'], ['half', 'full'], true)) {
                $field['width'] = (string) ($fieldDefaults['width'] ?? 'half');
            }
            if (!empty($fieldDefaults['locked_width'])) {
                $field['width'] = (string) ($fieldDefaults['width'] ?? 'full');
            }
            if (isset($fieldDefaults['min'])) {
                $field['min'] = (int) ($fieldDefaults['min']);
            }
            if (isset($fieldDefaults['max'])) {
                $field['max'] = (int) ($fieldDefaults['max']);
            }
            if (isset($fieldDefaults['value'])) {
                $field['value'] = (string) ($fieldDefaults['value']);
            }
            if (isset($fieldDefaults['rows'])) {
                $field['rows'] = (int) ($fieldDefaults['rows']);
            }
            if (isset($fieldDefaults['options'])) {
                $optionsText = trim((string) ($source['options_text'] ?? ''));
                $options = [];
                foreach (preg_split('/
|
|
/', $optionsText) ?: [] as $line) {
                    $line = trim((string) $line);
                    if ($line === '') {
                        continue;
                    }
                    if (strpos($line, '|') !== false) {
                        [$value, $label] = array_map('trim', explode('|', $line, 2));
                    } else {
                        $value = $line;
                        $label = $line;
                    }
                    if ($value === '' && $label === '') {
                        continue;
                    }
                    $options[] = [
                        'value' => $value !== '' ? $value : $label,
                        'label' => $label !== '' ? $label : $value,
                    ];
                }
                $field['options'] = $options !== [] ? $options : $fieldDefaults['options'];
            }
            if (!empty($fieldDefaults['locked_enabled'])) {
                $field['locked_enabled'] = true;
            }
            if (!empty($fieldDefaults['locked_required'])) {
                $field['locked_required'] = true;
            }
            if (!empty($fieldDefaults['locked_width'])) {
                $field['locked_width'] = true;
            }
            if ($key === 'calendar') {
                $field['label'] = $newConfig['calendar_label'];
            }
            $newConfig['fields'][$key] = $field;
            $sortMap[] = [
                'key' => $key,
                'position' => max(1, (int) ($source['position'] ?? 999)),
            ];
        }

        usort($sortMap, static function (array $a, array $b): int {
            if ($a['position'] === $b['position']) {
                return strcmp($a['key'], $b['key']);
            }
            return $a['position'] <=> $b['position'];
        });
        $newConfig['field_order'] = array_column($sortMap, 'key');

        $settings['booking_form'] = $newConfig;
        cms_save_settings($settings);
        $settings = cms_settings();
        $bookingForm = cms_booking_form_settings($settings);
        $notice = '<div class="notice">Форма бронирования сохранена.</div>';
    }
}

$orderedFieldKeys = $bookingForm['field_order'] ?? array_keys($bookingForm['fields']);
ob_start();
echo $notice;
?>
<form class="grid" method="post">
  <input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>">

  <section class="panel grid">
    <div class="admin-page-head admin-page-head--compact">
      <div>
        <div class="badge">Бронирование</div>
        <h2 style="margin:10px 0 6px">Тексты и подписи окна бронирования</h2>
      </div>
    </div>
    <div class="grid grid-2">
      <label><span>Маленькая подпись слева</span><input name="eyebrow" value="<?= e($bookingForm['eyebrow'] ?? '') ?>"></label>
      <label><span>Главный заголовок</span><input name="title" value="<?= e($bookingForm['title'] ?? '') ?>"></label>
    </div>
    <div class="grid grid-2">
      <label><span>Текст под заголовком слева</span><textarea name="house_description"><?= e($bookingForm['house_description'] ?? '') ?></textarea></label>
      <label><span>Главный текст справа</span><textarea name="lead_text"><?= e($bookingForm['lead_text'] ?? '') ?></textarea></label>
    </div>
    <label><span>Подпись под главным текстом справа</span><input name="caption" value="<?= e($bookingForm['caption'] ?? '') ?>"></label>
    <div class="grid grid-3">
      <label><span>Подпись «Ночей»</span><input name="summary_nights_label" value="<?= e($bookingForm['summary_nights_label'] ?? '') ?>"></label>
      <label><span>Подпись «Стоимость»</span><input name="summary_total_label" value="<?= e($bookingForm['summary_total_label'] ?? '') ?>"></label>
      <label><span>Текст до выбора дат</span><input name="summary_total_empty" value="<?= e($bookingForm['summary_total_empty'] ?? '') ?>"></label>
    </div>
    <label><span>Подсказка в блоке итогов</span><textarea name="summary_hint"><?= e($bookingForm['summary_hint'] ?? '') ?></textarea></label>
    <div class="grid grid-2">
      <label><span>Подпись календаря</span><input name="calendar_label" value="<?= e($bookingForm['calendar_label'] ?? '') ?>"></label>
      <label><span>Текст кнопки отправки</span><input name="submit_label" value="<?= e($bookingForm['submit_label'] ?? '') ?>"></label>
    </div>
  </section>

  <section class="panel grid">
    <div class="admin-page-head admin-page-head--compact">
      <div>
        <div class="badge">Согласие</div>
        <h2 style="margin:10px 0 6px">Строка согласия под формой</h2>
      </div>
    </div>
    <div class="notice" style="margin:0">Собирается из трёх текстовых частей и двух ссылок. Так безопаснее, чем редактировать HTML вручную.</div>
    <label><span>Текст до ссылки на политику</span><input name="consent_prefix" value="<?= e($bookingForm['consent_prefix'] ?? '') ?>"></label>
    <div class="grid grid-2">
      <label><span>Текст ссылки на политику</span><input name="privacy_link_label" value="<?= e($bookingForm['privacy_link_label'] ?? '') ?>"></label>
      <label><span>URL ссылки на политику</span><input name="privacy_link_url" value="<?= e($bookingForm['privacy_link_url'] ?? '') ?>"></label>
    </div>
    <label><span>Текст между ссылками</span><input name="consent_middle" value="<?= e($bookingForm['consent_middle'] ?? '') ?>"></label>
    <div class="grid grid-2">
      <label><span>Текст ссылки на правила</span><input name="rules_link_label" value="<?= e($bookingForm['rules_link_label'] ?? '') ?>"></label>
      <label><span>URL ссылки на правила</span><input name="rules_link_url" value="<?= e($bookingForm['rules_link_url'] ?? '') ?>"></label>
    </div>
    <label><span>Текст после ссылки на правила</span><input name="consent_suffix" value="<?= e($bookingForm['consent_suffix'] ?? '') ?>"></label>
  </section>

  <section class="panel grid">
    <div class="admin-page-head admin-page-head--compact">
      <div>
        <div class="badge">Поля</div>
        <h2 style="margin:10px 0 6px">Настройка полей формы</h2>
        <p class="muted" style="margin:0">Можно менять подписи, плейсхолдеры, ширину, порядок и скрывать необязательные поля. Системные поля бронирования закреплены, чтобы форма не ломалась.</p>
      </div>
    </div>
    <div class="booking-admin-preview">
      <?php foreach ($orderedFieldKeys as $position => $fieldKey): $field = $bookingForm['fields'][$fieldKey] ?? null; if (!$field) continue; if ($fieldKey === 'calendar') { $field['label'] = $bookingForm['calendar_label'] ?? ($field['label'] ?? 'Календарь'); } ?>
        <span class="booking-admin-preview__item <?= empty($field['enabled']) ? 'is-muted' : '' ?>"><?= e(($position + 1) . '. ' . ($field['label'] ?? ($fieldTitles[$fieldKey] ?? $fieldKey))) ?></span>
      <?php endforeach; ?>
    </div>
    <div class="grid grid-2 booking-admin-fields">
      <?php foreach ($orderedFieldKeys as $position => $fieldKey): ?>
        <?php $field = $bookingForm['fields'][$fieldKey] ?? []; $defaultsField = $defaults['fields'][$fieldKey] ?? []; ?>
        <div class="booking-admin-field">
          <div class="booking-admin-field__head">
            <div>
              <strong><?= e($fieldTitles[$fieldKey] ?? $fieldKey) ?></strong>
              <div class="booking-admin-field__meta">Ключ: <code><?= e($fieldKey) ?></code><?php if (($field['type'] ?? '') === 'calendar'): ?> · управляет выбором дат<?php endif; ?></div>
            </div>
            <label><span>Позиция</span><input class="booking-admin-order" type="number" min="1" step="1" name="fields[<?= e($fieldKey) ?>][position]" value="<?= e((string)($position + 1)) ?>"></label>
          </div>
          <div class="grid grid-2">
            <label><span>Подпись поля</span><input name="fields[<?= e($fieldKey) ?>][label]" value="<?= e($fieldKey === 'calendar' ? ($bookingForm['calendar_label'] ?? ($field['label'] ?? '')) : ($field['label'] ?? '')) ?>" <?= $fieldKey === 'calendar' ? 'disabled' : '' ?>></label>
            <label><span>Плейсхолдер</span><input name="fields[<?= e($fieldKey) ?>][placeholder]" value="<?= e($field['placeholder'] ?? '') ?>" <?= ($field['type'] ?? '') === 'calendar' ? 'disabled' : '' ?>></label>
          </div>
          <div class="grid grid-3">
            <label><span>Ширина</span>
              <select name="fields[<?= e($fieldKey) ?>][width]" <?= !empty($defaultsField['locked_width']) ? 'disabled' : '' ?>>
                <option value="half" <?= ($field['width'] ?? 'half') === 'half' ? 'selected' : '' ?>>половина строки</option>
                <option value="full" <?= ($field['width'] ?? '') === 'full' ? 'selected' : '' ?>>во всю строку</option>
              </select>
            </label>
            <label class="pill <?= !empty($defaultsField['locked_enabled']) ? 'pill--active' : '' ?>"><input type="checkbox" name="fields[<?= e($fieldKey) ?>][enabled]" value="1" <?= !empty($field['enabled']) ? 'checked' : '' ?> <?= !empty($defaultsField['locked_enabled']) ? 'disabled' : '' ?>> показывать поле</label>
            <label class="pill <?= !empty($defaultsField['locked_required']) ? 'pill--active' : '' ?>"><input type="checkbox" name="fields[<?= e($fieldKey) ?>][required]" value="1" <?= !empty($field['required']) ? 'checked' : '' ?> <?= !empty($defaultsField['locked_required']) ? 'disabled' : '' ?>> обязательное</label>
          </div>
          <?php if ($fieldKey === 'calendar'): ?>
            <div class="muted" style="font-size:13px">Подпись календаря меняется выше, в блоке с общими текстами окна бронирования.</div>
          <?php elseif (!empty($defaultsField['locked_enabled']) || !empty($defaultsField['locked_required']) || !empty($defaultsField['locked_width'])): ?>
            <div class="muted" style="font-size:13px">Это системное поле: часть параметров зафиксирована для стабильной работы формы.</div>
          <?php endif; ?>
          <?php if (($field['type'] ?? '') === 'select'): ?>
            <?php $optionsText = []; foreach ((array)($field['options'] ?? []) as $opt) { $optionsText[] = trim((string)($opt['value'] ?? '')) . '|' . trim((string)($opt['label'] ?? '')); } ?>
            <label><span>Опции (каждая с новой строки, формат: значение|подпись)</span><textarea name="fields[<?= e($fieldKey) ?>][options_text]" style="min-height:110px"><?= e(implode("
", $optionsText)) ?></textarea></label>
          <?php endif; ?>
        </div>
      <?php endforeach; ?>
    </div>
  </section>

  <button class="button" type="submit">Сохранить настройки формы</button>
</form>
<?php
admin_layout('Форма бронирования', ob_get_clean(), 'booking_form');
