<?php
/**
 * Header Menu Builder
 *
 * @var array $menu
 */

use Core\App\Models\Page;

$pagesModel = new Page();
$pages = $pagesModel->getAll();
?>

<div class="container-fluid py-4">

    <!-- PAGE HEADER -->
    <div class="mb-4 d-flex justify-content-between align-items-center">
        <div>
            <h3 class="mb-1">
                <i class="bi bi-list-ul me-2"></i>
                <?= __('header.menu_title', 'Header Menu') ?>
            </h3>
            <small class="text-muted">
                <?= __('sidebar.manage_site', 'Manage Site') ?>
                →
                <?= __('header.menu_title', 'Header Menu') ?>
            </small>
        </div>

        <!-- ADD BUTTON (FIXED) -->
        <button type="button" class="btn btn-success" id="addMenuItem">
            <i class="bi bi-plus-circle me-1"></i>
            <?= __('actions.add', 'Add link') ?>
        </button>
    </div>

    <?php if (!empty($_SESSION['success'])): ?>
        <div class="alert alert-success d-flex align-items-center">
            <i class="bi bi-check-circle me-2"></i>
            <?= htmlspecialchars((string)$_SESSION['success'], ENT_QUOTES, 'UTF-8') ?>
        </div>
        <?php unset($_SESSION['success']); ?>
    <?php endif; ?>

    <?php if (!empty($_SESSION['error'])): ?>
        <div class="alert alert-danger d-flex align-items-center">
            <i class="bi bi-exclamation-triangle me-2"></i>
            <?= htmlspecialchars((string)$_SESSION['error'], ENT_QUOTES, 'UTF-8') ?>
        </div>
        <?php unset($_SESSION['error']); ?>
    <?php endif; ?>

    <form method="post" action="/admin/appearance/header/save">
        <?= \Core\System\Csrf::field(); ?>

        <div class="card border-0 shadow-sm">
            <div class="card-body p-3">

                <table class="table mb-0">
                    <tbody id="menuSortable">

                    <?php foreach ($menu as $index => $item): ?>
                    <?php
                        $type = $item['type'] ?? 'custom';
                        $slug = ltrim($item['url'] ?? '', '/');
                    ?>
                    <tr class="menu-row">
                        <td class="p-0 pb-3">

                            <div class="card border shadow-sm">
                                <div class="card-body">

                                    <div class="row g-3 align-items-center">

                                        <!-- DRAG -->
                                        <div class="col-auto text-muted cursor-move">
                                            <i class="bi bi-grip-vertical fs-4"></i>
                                        </div>

                                        <!-- LABEL -->
                                        <div class="col-md-3">
                                            <label class="form-label small text-muted">
                                                <?= __('header.menu_label', 'Label') ?>
                                            </label>
                                            <input type="text"
                                                   name="menu[<?= $index ?>][label]"
                                                   value="<?= htmlspecialchars($item['label'], ENT_QUOTES, 'UTF-8') ?>"
                                                   class="form-control">
                                        </div>

                                        <!-- DESTINATION (COLORED) -->
                                        <div class="col-md-4">
                                            <label class="form-label small text-muted">
                                                <?= __('header.menu_destination', 'Destination') ?>
                                            </label>

                                            <div class="btn-group w-100">
                                                <input type="radio" class="btn-check destination-radio"
                                                       name="menu[<?= $index ?>][type]"
                                                       value="home"
                                                       id="home<?= $index ?>"
                                                       <?= $type === 'home' ? 'checked' : '' ?>>
                                                <label class="btn btn-outline-primary" for="home<?= $index ?>">
                                                    <i class="bi bi-house"></i>
                                                </label>

                                                <input type="radio" class="btn-check destination-radio"
                                                       name="menu[<?= $index ?>][type]"
                                                       value="page"
                                                       id="page<?= $index ?>"
                                                       <?= $type === 'page' ? 'checked' : '' ?>>
                                                <label class="btn btn-outline-success" for="page<?= $index ?>">
                                                    <i class="bi bi-file-earmark-text"></i>
                                                </label>

                                                <input type="radio" class="btn-check destination-radio"
                                                       name="menu[<?= $index ?>][type]"
                                                       value="custom"
                                                       id="custom<?= $index ?>"
                                                       <?= $type === 'custom' ? 'checked' : '' ?>>
                                                <label class="btn btn-outline-warning" for="custom<?= $index ?>">
                                                    <i class="bi bi-link-45deg"></i>
                                                </label>
                                            </div>
                                        </div>

                                        <!-- TARGET -->
                                        <div class="col-md-3">
                                            <label class="form-label small text-muted">
                                                <?= __('header.menu_target', 'Target') ?>
                                            </label>

                                            <select name="menu[<?= $index ?>][page_slug]"
                                                    class="form-select page-select <?= $type !== 'page' ? 'd-none' : '' ?>">
                                                <?php foreach ($pages as $page): ?>
                                                    <option value="<?= $page['slug'] ?>"
                                                        <?= $slug === $page['slug'] ? 'selected' : '' ?>>
                                                        <?= htmlspecialchars($page['title'], ENT_QUOTES, 'UTF-8') ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>

                                            <input type="text"
                                                   name="menu[<?= $index ?>][url]"
                                                   value="<?= htmlspecialchars($item['url'], ENT_QUOTES, 'UTF-8') ?>"
                                                   class="form-control custom-url <?= $type !== 'custom' ? 'd-none' : '' ?>">
                                        </div>

                                        <!-- ENABLE -->
                                        <div class="col-auto">
                                            <div class="form-check form-switch">
                                                <input class="form-check-input"
                                                       type="checkbox"
                                                       name="menu[<?= $index ?>][enabled]"
                                                       <?= !empty($item['enabled']) ? 'checked' : '' ?>>
                                            </div>
                                        </div>

                                        <!-- DELETE -->
                                        <div class="col-auto">
                                            <button type="button"
                                                    class="btn btn-sm btn-outline-danger btn-delete-row">
                                                <i class="bi bi-trash"></i>
                                            </button>
                                        </div>

                                    </div>

                                </div>
                            </div>

                        </td>
                    </tr>
                    <?php endforeach; ?>

                    </tbody>
                </table>

            </div>

            <div class="card-footer bg-white text-end">
                <button type="submit" class="btn btn-primary px-4">
                    <i class="bi bi-save me-1"></i>
                    <?= __('actions.save', 'Save') ?>
                </button>
            </div>

        </div>
    </form>
</div>

<style>
.menu-row { cursor: grab; }
.menu-row:active { cursor: grabbing; }
#menuSortable .card { transition: box-shadow .2s ease; }
#menuSortable .card:hover { box-shadow: 0 .5rem 1rem rgba(0,0,0,.08); }
</style>

<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>

<script>
document.addEventListener('DOMContentLoaded', function () {

    // Toggle destination
    document.addEventListener('change', function (e) {
        if (!e.target.classList.contains('destination-radio')) return;
        const row = e.target.closest('.menu-row');
        row.querySelector('.page-select')?.classList.add('d-none');
        row.querySelector('.custom-url')?.classList.add('d-none');
        if (e.target.value === 'page') row.querySelector('.page-select')?.classList.remove('d-none');
        if (e.target.value === 'custom') row.querySelector('.custom-url')?.classList.remove('d-none');
    });

    // Delete
    document.addEventListener('click', function (e) {
        if (e.target.closest('.btn-delete-row')) {
            e.target.closest('.menu-row').remove();
        }
    });

    // Sortable
    new Sortable(document.getElementById('menuSortable'), {
        animation: 150,
        handle: '.cursor-move',
        ghostClass: 'bg-light'
    });

    // ADD NEW ROW (FIXED & WORKING)
    document.getElementById('addMenuItem').addEventListener('click', function () {
        const tbody = document.getElementById('menuSortable');
        const index = Date.now();

        const row = document.createElement('tr');
        row.classList.add('menu-row');
        row.innerHTML = `
        <td class="p-0 pb-3">
            <div class="card border shadow-sm">
                <div class="card-body">
                    <div class="row g-3 align-items-center">

                        <div class="col-auto text-muted cursor-move">
                            <i class="bi bi-grip-vertical fs-4"></i>
                        </div>

                        <div class="col-md-3">
                            <label class="form-label small text-muted"><?= __('header.menu_label','Label') ?></label>
                            <input type="text" name="menu[\${index}][label]" class="form-control">
                        </div>

                        <div class="col-md-4">
                            <label class="form-label small text-muted"><?= __('header.menu_destination','Destination') ?></label>
                            <div class="btn-group w-100">
                                <input type="radio" class="btn-check destination-radio" name="menu[\${index}][type]" value="home" id="h\${index}">
                                <label class="btn btn-outline-primary" for="h\${index}"><i class="bi bi-house"></i></label>

                                <input type="radio" class="btn-check destination-radio" name="menu[\${index}][type]" value="page" id="p\${index}">
                                <label class="btn btn-outline-success" for="p\${index}"><i class="bi bi-file-earmark-text"></i></label>

                                <input type="radio" class="btn-check destination-radio" name="menu[\${index}][type]" value="custom" id="c\${index}" checked>
                                <label class="btn btn-outline-warning" for="c\${index}"><i class="bi bi-link-45deg"></i></label>
                            </div>
                        </div>

                        <div class="col-md-3">
                            <label class="form-label small text-muted"><?= __('header.menu_target','Target') ?></label>
                            <select name="menu[\${index}][page_slug]" class="form-select page-select d-none">
                                <?php foreach ($pages as $page): ?>
                                <option value="<?= $page['slug'] ?>"><?= htmlspecialchars($page['title'], ENT_QUOTES, 'UTF-8') ?></option>
                                <?php endforeach; ?>
                            </select>
                            <input type="text" name="menu[\${index}][url]" class="form-control custom-url">
                        </div>

                        <div class="col-auto">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" name="menu[\${index}][enabled]" checked>
                            </div>
                        </div>

                        <div class="col-auto">
                            <button type="button" class="btn btn-sm btn-outline-danger btn-delete-row">
                                <i class="bi bi-trash"></i>
                            </button>
                        </div>

                    </div>
                </div>
            </div>
        </td>`;
        tbody.appendChild(row);
    });

});
</script>
