<?php

namespace App\Controllers\Admin;

use App\Models\MenuModel;

class MenuController extends AdminController
{
    public function index(): void
    {
        $menuModel = new MenuModel();

        $this->adminView('menu/index', [
            'menus' => $menuModel->getAllFlat(),
        ]);
    }

    public function create(): void
    {
        $menuModel = new MenuModel();

        $this->adminView('menu/form', [
            'menu'          => null,
            'parentOptions' => $menuModel->getParentOptions(),
        ]);
    }

    public function store(): void
    {
        $this->verifyCsrf();

        $data = $this->validatedInput();

        (new MenuModel())->insert($data);

        $this->setFlash('success', 'Menu berhasil ditambahkan.');
        $this->redirect('admin/menu');
    }

    public function edit(string $id): void
    {
        $menuModel = new MenuModel();
        $menu = $menuModel->find((int) $id);

        if (!$menu) {
            $this->setFlash('error', 'Menu tidak ditemukan.');
            $this->redirect('admin/menu');
            return;
        }

        $this->adminView('menu/form', [
            'menu'          => $menu,
            'parentOptions' => array_filter($menuModel->getParentOptions(), fn ($p) => (int) $p['id'] !== (int) $id),
        ]);
    }

    public function update(string $id): void
    {
        $this->verifyCsrf();

        $data = $this->validatedInput();

        // Mencegah menu memilih dirinya sendiri sebagai parent
        if (!empty($data['parent_id']) && (int) $data['parent_id'] === (int) $id) {
            $data['parent_id'] = null;
        }

        (new MenuModel())->update((int) $id, $data);

        $this->setFlash('success', 'Menu berhasil diperbarui.');
        $this->redirect('admin/menu');
    }

    public function destroy(string $id): void
    {
        $this->verifyCsrf();

        (new MenuModel())->delete((int) $id);

        $this->setFlash('success', 'Menu berhasil dihapus (beserta submenunya).');
        $this->redirect('admin/menu');
    }

    /**
     * Ambil & bersihkan input form menu.
     */
    private function validatedInput(): array
    {
        return [
            'label'        => trim($_POST['label'] ?? ''),
            'url'          => trim($_POST['url'] ?? '#'),
            'tipe'         => in_array($_POST['tipe'] ?? '', ['halaman', 'berita', 'eksternal', 'custom'], true) ? $_POST['tipe'] : 'custom',
            'parent_id'    => !empty($_POST['parent_id']) ? (int) $_POST['parent_id'] : null,
            'urutan'       => (int) ($_POST['urutan'] ?? 0),
            'target_blank' => isset($_POST['target_blank']) ? 1 : 0,
            'is_active'    => isset($_POST['is_active']) ? 1 : 0,
        ];
    }
}
