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

$pageSlug = $_GET['page'] ?? 'home';
$page = cms_page($pageSlug);
$page['slug'] = $pageSlug;
$page['modules'] = $page['modules'] ?? [];
$notice = '';

if (request_method() === 'POST') {
    if (!verify_csrf($_POST['csrf_token'] ?? null)) {
        $notice = '<div class="notice notice--error">Ошибка безопасности.</div>';
    } else {
        $action = post_text('action');
        if ($action === 'reorder') {
            $ordered = array_filter(array_map('trim', explode(',', post_text('module_order'))));
            $page['modules'] = array_values($ordered);
            cms_save_page($pageSlug, $page);
            $notice = '<div class="notice">Порядок блоков сохранён.</div>';
        } elseif ($action === 'add') {
            $type = post_text('type');
            $moduleId = new_module_id($type);
            $module = [
                'id' => $moduleId,
                'type' => $type,
                'name' => post_text('name', 'Новый блок'),
                'title' => post_text('name', 'Новый блок'),
                'anchor' => slugify(post_text('name', $type)),
            ];
            cms_save_module($moduleId, $module);
            $page['modules'][] = $moduleId;
            cms_save_page($pageSlug, $page);
            redirect('/admin/module.php?id=' . urlencode($moduleId) . '&page=' . urlencode($pageSlug));
        } elseif ($action === 'remove') {
            $moduleId = post_text('module_id');
            $page['modules'] = array_values(array_filter($page['modules'], static fn($id) => $id !== $moduleId));
            cms_save_page($pageSlug, $page);
            $notice = '<div class="notice">Блок снят со страницы.</div>';
        }
    }
}

$modules = page_modules($page);
ob_start();
echo $notice;
?>
<div class="builder">
  <div class="grid">
    <form class="panel grid" method="post">
      <input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>">
      <input type="hidden" name="action" value="add">
      <label><span>Тип блока</span>
        <select name="type">
          <?php foreach (module_type_options() as $value => $label): ?><option value="<?= e($value) ?>"><?= e($label) ?></option><?php endforeach; ?>
        </select>
      </label>
      <label><span>Название блока</span><input name="name" value="Новый блок"></label>
      <button class="button" type="submit">Добавить блок</button>
    </form>

    <form class="panel grid" method="post">
      <input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>">
      <input type="hidden" name="action" value="reorder">
      <input type="hidden" name="module_order" value="<?= e(implode(',', $page['modules'])) ?>" id="module-order">
      <div class="collection-toolbar"><h2 style="margin:0">Порядок блоков</h2><button class="button button--small" type="submit">Сохранить порядок</button></div>
      <div class="module-list" data-sortable data-output="#module-order">
        <?php foreach ($modules as $module): ?>
          <div class="module-item" data-sort-item data-id="<?= e($module['id'] ?? '') ?>">
            <div class="badge"><?= e($module['type'] ?? '') ?></div>
            <h3><?= e($module['name'] ?? $module['title'] ?? 'Без названия') ?></h3>
            <div class="module-actions">
              <a class="button button--small" href="/admin/module.php?id=<?= e($module['id'] ?? '') ?>&page=<?= e($pageSlug) ?>">Редактировать</a>
              <form method="post" onsubmit="return confirm('Убрать блок со страницы?');">
                <input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>">
                <input type="hidden" name="action" value="remove">
                <input type="hidden" name="module_id" value="<?= e($module['id'] ?? '') ?>">
                <button class="button button--small button--danger" type="submit">Убрать</button>
              </form>
            </div>
          </div>
        <?php endforeach; ?>
      </div>
    </form>
  </div>
  <div class="panel">
    <div class="collection-toolbar"><h2 style="margin:0">Live Preview</h2><a class="button button--small button--ghost" target="_blank" rel="noopener" href="<?= e($pageSlug === 'home' ? '/' : ($pageSlug === 'policy' ? '/politica.php' : '/rools.php')) ?>">Открыть отдельно</a></div>
    <iframe class="preview-frame" src="<?= e($pageSlug === 'home' ? '/' : ($pageSlug === 'policy' ? '/politica.php' : '/rools.php')) ?>"></iframe>
  </div>
</div>
<?php
admin_layout('Конструктор: ' . e($page['name'] ?? $pageSlug), ob_get_clean(), 'builder');
