<?php
/**
 * HTMX fragment: expand/collapse/editor for a single form help block.
 *
 * GET  ?key=xxx          → render collapsed chip: 3/4 left (name + MD preview), 1/4 right (edit + toggle dot)
 * GET  ?key=xxx&edit=1   → render inline OverType editor + name field
 * POST                    → save content + name, return collapsed view
 * POST _action=toggle     → toggle enabled, return collapsed view
 */
require_once __DIR__ . '/../../bootstrap.php';
require_once __DIR__ . '/../../src/AdminAuth.php';
AdminAuth::requireLogin();
require_once __DIR__ . '/../../src/Database.php';

if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

$key = $_GET['key'] ?? '';

if (!in_array($key, Database::FORM_HELP_KEYS, true)) {
    http_response_code(400);
    echo 'Clé invalide.';
    exit;
}

// ── POST ─────────────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['_action'] ?? 'save';
    $db = new Database();

    // Toggle doesn't need CSRF — low-risk action behind admin auth
    if ($action === 'toggle') {
        $db->toggleFormHelpBlock($key);
        renderCollapsed($db, $key);
        exit;
    }

    // Save requires CSRF
    if (!isset($_POST['csrf_token'], $_SESSION['csrf_token'])
        || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        http_response_code(403);
        echo 'Token invalide.';
        exit;
    }

    // save
    $content = $_POST['content'] ?? '';
    $name    = trim($_POST['name'] ?? '');
    try {
        $db->setFormHelpBlock($key, $content);
        if ($name !== '') {
            $db->setFormHelpBlockName($key, $name);
        }
        require_once __DIR__ . '/../../src/AdminLogger.php';
        AdminLogger::make()->logFormStructureEdit($key);
    } catch (Exception $e) {
        error_log('form-help-inline save error: ' . $e->getMessage());
        http_response_code(500);
        echo 'Erreur lors de la sauvegarde.';
        exit;
    }

    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    renderCollapsed($db, $key);
    exit;
}

// ── GET ──────────────────────────────────────────────────────────────────────
$db = new Database();
$editMode = ($_GET['edit'] ?? '') === '1';

if ($editMode) {
    renderEditor($db, $key);
} else {
    renderCollapsed($db, $key);
}

// ═══════════════════════════════════════════════════════════════════════════════
// RENDER HELPERS
// ═══════════════════════════════════════════════════════════════════════════════

function renderCollapsed(Database $db, string $key): void
{
    $blocks = $db->getAllFormHelpBlocks();
    $b      = $blocks[$key] ?? ['content' => '', 'name' => '', 'enabled' => 0];
    $name   = $b['name'] ?: $key;
    $content = $b['content'] ?? '';
    $enabled = (int)($b['enabled'] ?? 1);
    $hasContent = trim($content) !== '';

    $mdHtml = '';
    if ($hasContent) {
        require_once APP_ROOT . '/src/Parsedown.php';
        $pd = new Parsedown();
        $pd->setSafeMode(true);
        $mdHtml = $pd->text($content);
    }
    ?>
    <div class="fhb-inline <?= $enabled ? '' : 'fhb-inline--disabled' ?>" data-key="<?= htmlspecialchars($key) ?>">

        <!-- Left side: name + content (content hidden when disabled) -->
        <div class="fhb-inline-body">
            <div class="fhb-inline-name"><?= htmlspecialchars($name) ?></div>
            <?php if ($enabled && $hasContent): ?>
            <div class="fhb-md-preview"><?= $mdHtml ?></div>
            <?php elseif ($enabled): ?>
            <div class="fhb-inline-empty">— vide —</div>
            <?php endif; ?>
        </div>

        <!-- Right side: dot above edit button (edit hidden when disabled) -->
        <div class="fhb-inline-actions">
            <form hx-post="/admin/form-help-inline-fragment.php?key=<?= urlencode($key) ?>"
                  hx-target="closest .fhb-inline"
                  hx-swap="outerHTML"
                  class="fhb-toggle-form">
                <input type="hidden" name="_action" value="toggle">
                <button type="submit"
                        class="fhb-dot <?= $enabled ? 'fhb-dot--on' : 'fhb-dot--off' ?>"
                        title="<?= $enabled ? 'Désactiver ce bloc' : 'Activer ce bloc' ?>"
                        aria-label="<?= $enabled ? 'Désactiver ce bloc' : 'Activer ce bloc' ?>"></button>
            </form>

            <?php if ($enabled): ?>
            <button type="button" class="btn btn--primary btn--sm"
                    hx-get="/admin/form-help-inline-fragment.php?key=<?= urlencode($key) ?>&edit=1"
                    hx-target="closest .fhb-inline"
                    hx-swap="outerHTML">Éditer</button>
            <?php endif; ?>
        </div>

    </div>
    <?php
}

function renderEditor(Database $db, string $key): void
{
    $blocks = $db->getAllFormHelpBlocks();
    $b      = $blocks[$key] ?? ['content' => '', 'name' => ''];
    $name   = $b['name'] ?: $key;
    $content = $b['content'] ?? '';
    ?>
    <div class="fhb-inline fhb-inline--editing" data-key="<?= htmlspecialchars($key) ?>">
        <form hx-post="/admin/form-help-inline-fragment.php?key=<?= urlencode($key) ?>"
              hx-swap="outerHTML"
              hx-target="closest .fhb-inline"
              class="fhb-inline-form">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">

            <div class="fhb-edit-name-row">
                <label for="fhb-name-<?= htmlspecialchars($key) ?>" class="fhb-edit-label">Nom du bloc :</label>
                <input type="text" id="fhb-name-<?= htmlspecialchars($key) ?>" name="name"
                       value="<?= htmlspecialchars($name) ?>"
                       class="fhb-name-input"
                       placeholder="Nom du bloc d'aide">
            </div>

            <label for="fhb-ed-<?= htmlspecialchars($key) ?>" class="fhb-edit-label">Contenu (Markdown) :</label>
            <input type="hidden" id="fhb-content-<?= htmlspecialchars($key) ?>" name="content"
                   value="<?= htmlspecialchars($content) ?>">
            <div id="fhb-editor-<?= htmlspecialchars($key) ?>" class="fhb-overtype-editor"></div>

            <div class="fhb-edit-buttons">
                <button type="submit" class="btn btn--primary btn--sm">Enregistrer</button>
                <button type="button" class="btn btn--secondary btn--sm"
                        hx-get="/admin/form-help-inline-fragment.php?key=<?= urlencode($key) ?>"
                        hx-target="closest .fhb-inline"
                        hx-swap="outerHTML">Annuler</button>
            </div>
        </form>
        <script>
        (function(){
            var hidden = document.getElementById('fhb-content-<?= htmlspecialchars($key) ?>');
            var ed = document.getElementById('fhb-editor-<?= htmlspecialchars($key) ?>');
            if (hidden && ed && typeof OverType !== 'undefined') {
                var OT = OverType.default || OverType;
                new OT(ed, {
                    value: hidden.value,
                    minHeight: '400px',
                    spellcheck: false,
                    onChange: function(v) { hidden.value = v; }
                });
            } else {
                ed.innerHTML = '<textarea name="content" style="width:100%;min-height:400px;font-family:monospace">'
                    + hidden.value.replace(/</g,'&lt;').replace(/>/g,'&gt;') + '</textarea>';
                var ta = ed.querySelector('textarea');
                ta.addEventListener('input', function() {
                    hidden.value = this.value;
                });
            }
        })();
        </script>
    </div>
    <?php
}
