<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/bootstrap.php';
require_once __DIR__ . '/../includes/admin_layout.php';

require_admin();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string) ($_POST['action'] ?? '');

    if ($action === 'save_link') {
        $id = trim((string) ($_POST['id'] ?? ''));
        $label = trim((string) ($_POST['label'] ?? ''));
        $url = trim((string) ($_POST['url'] ?? ''));

        if ($label === '' || $url === '') {
            flash('error', 'Link adı ve URL zorunlu.');
            redirect(url('admin/menu.php' . ($id !== '' ? '?edit=' . rawurlencode($id) : '')));
        }

        $items = menu_items();
        $found = false;
        foreach ($items as &$it) {
            if ($id !== '' && (string) ($it['id'] ?? '') === $id) {
                $it['label'] = $label;
                $it['url'] = $url;
                $found = true;
                break;
            }
        }
        unset($it);

        if (!$found) {
            $maxSort = 0;
            foreach ($items as $it) {
                $maxSort = max($maxSort, (int) ($it['sort'] ?? 0));
            }
            $items[] = [
                'id' => new_id('m_'),
                'label' => $label,
                'url' => $url,
                'sort' => $maxSort + 10,
            ];
        }

        store_write('menu', array_values($items));
        flash('success', $found ? 'Link güncellendi.' : 'Link eklendi.');
        redirect(url('admin/menu.php'));
    }

    if ($action === 'delete_item') {
        $id = trim((string) ($_POST['id'] ?? ''));
        $items = array_values(array_filter(
            menu_items(),
            static fn(array $it): bool => (string) ($it['id'] ?? '') !== $id
        ));
        store_write('menu', $items);
        flash('success', 'Link silindi.');
        redirect(url('admin/menu.php'));
    }

    if ($action === 'move') {
        $id = trim((string) ($_POST['id'] ?? ''));
        $dir = (string) ($_POST['dir'] ?? '');
        $items = menu_items();
        $idx = null;
        foreach ($items as $i => $it) {
            if ((string) ($it['id'] ?? '') === $id) {
                $idx = $i;
                break;
            }
        }
        if ($idx !== null) {
            $swap = $dir === 'up' ? $idx - 1 : $idx + 1;
            if (isset($items[$swap])) {
                $a = $items[$idx];
                $items[$idx] = $items[$swap];
                $items[$swap] = $a;
                foreach ($items as $i => &$it) {
                    $it['sort'] = ($i + 1) * 10;
                }
                unset($it);
                store_write('menu', array_values($items));
            }
        }
        redirect(url('admin/menu.php'));
    }

    flash('error', 'Geçersiz işlem.');
    redirect(url('admin/menu.php'));
}

$items = menu_items();
$editId = trim((string) ($_GET['edit'] ?? ''));
$editItem = $editId !== '' ? menu_find($editId) : null;

admin_layout_start('Menü', 'menu');
?>

<section class="admin-panel">
    <h2>Menü linkleri</h2>
    <p class="hint">Mobil ☰ menüsünde görünür. Sadece <strong>link adı</strong> + <strong>yönlenecek URL</strong>.</p>

    <?php if (!$items): ?>
        <p class="hint">Henüz link yok.</p>
    <?php else: ?>
        <div class="admin-table-wrap">
            <table class="admin-table">
                <thead>
                    <tr>
                        <th>Link adı</th>
                        <th>URL</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($items as $it): ?>
                        <tr>
                            <td><strong><?= e((string) ($it['label'] ?? '')) ?></strong></td>
                            <td>
                                <a href="<?= e(menu_href((string) ($it['url'] ?? ''))) ?>" target="_blank" rel="noopener">
                                    <?= e((string) ($it['url'] ?? '')) ?>
                                </a>
                            </td>
                            <td class="admin-actions">
                                <a class="admin-btn sm" href="<?= e(url('admin/menu.php?edit=' . rawurlencode((string) ($it['id'] ?? '')))) ?>">Düzenle</a>
                                <form method="post" style="display:inline">
                                    <input type="hidden" name="action" value="move">
                                    <input type="hidden" name="id" value="<?= e((string) ($it['id'] ?? '')) ?>">
                                    <input type="hidden" name="dir" value="up">
                                    <button class="admin-btn ghost sm" type="submit">↑</button>
                                </form>
                                <form method="post" style="display:inline">
                                    <input type="hidden" name="action" value="move">
                                    <input type="hidden" name="id" value="<?= e((string) ($it['id'] ?? '')) ?>">
                                    <input type="hidden" name="dir" value="down">
                                    <button class="admin-btn ghost sm" type="submit">↓</button>
                                </form>
                                <form method="post" style="display:inline" onsubmit="return confirm('Silinsin mi?');">
                                    <input type="hidden" name="action" value="delete_item">
                                    <input type="hidden" name="id" value="<?= e((string) ($it['id'] ?? '')) ?>">
                                    <button class="admin-btn danger sm" type="submit">Sil</button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</section>

<section class="admin-panel">
    <h2><?= $editItem ? 'Linki düzenle' : 'Yeni link ekle' ?></h2>
    <?php if ($editItem): ?>
        <p class="hint"><a href="<?= e(url('admin/menu.php')) ?>">Yeni link ekle</a></p>
    <?php endif; ?>

    <form method="post" class="admin-form">
        <input type="hidden" name="action" value="save_link">
        <?php if ($editItem): ?>
            <input type="hidden" name="id" value="<?= e((string) ($editItem['id'] ?? '')) ?>">
        <?php endif; ?>

        <label>Link adı
            <input type="text" name="label" required
                   value="<?= e((string) ($editItem['label'] ?? '')) ?>"
                   placeholder="Nasıl Çalışır?">
        </label>

        <label>Yönlendirilecek URL
            <input type="text" name="url" required
                   value="<?= e((string) ($editItem['url'] ?? '')) ?>"
                   placeholder="https://… veya magaza.php">
        </label>

        <p class="hint">
            Dış site: <code>https://instagram.com/hesap</code><br>
            Site içi: <code>magaza.php</code> · <code>index.php</code>
        </p>

        <button class="admin-btn" type="submit"><?= $editItem ? 'Kaydet' : 'Menüye Ekle' ?></button>
    </form>
</section>

<?php admin_layout_end(); ?>
