<?php

namespace App\Http\Controllers\Admin;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Models\Menu;
use App\Models\MenuItem;
use App\Models\Page;

class MenuController extends Controller
{
    /**
     * Show menu overview with all menus and their items.
     * GET /admin/menus
     */
    public function index(Request $request, array $params = []): void
    {
        $menus = Menu::all('id', 'ASC');

        $itemsByMenu = [];
        foreach ($menus as $menu) {
            $itemsByMenu[$menu['id']] = MenuItem::getByMenuId($menu['id']);
        }

        // All pages for the "link to page" selector
        $pages = Page::all('sort_order', 'ASC');

        $this->renderAdmin('menus/index', [
            'pageTitle'   => 'Menu Management',
            'menus'       => $menus,
            'itemsByMenu' => $itemsByMenu,
            'pages'       => $pages,
            'auth'        => $this->auth(),
            'csrf'        => $this->csrf(),
        ]);
    }

    /**
     * Add a new item to a menu.
     * POST /admin/menus/items/store
     */
    public function storeItem(Request $request, array $params = []): void
    {
        $this->validateCsrf();

        $menuId = (int) $request->input('menu_id', 0);
        $label  = trim($request->input('label', ''));
        $url    = trim($request->input('url', ''));

        if (!$menuId || $label === '' || $url === '') {
            set_flash('error', __('messages.all_required'));
            Response::redirect('/admin/menus');
            return;
        }

        $menu = Menu::find($menuId);
        if (!$menu) {
            set_flash('error', __('messages.not_found', ['item' => 'Menu']));
            Response::redirect('/admin/menus');
            return;
        }

        $pageId = $request->input('page_id', '');
        MenuItem::create([
            'menu_id'    => $menuId,
            'parent_id'  => null,
            'label'      => $label,
            'url'        => $url,
            'page_id'    => $pageId !== '' ? (int) $pageId : null,
            'target'     => in_array($request->input('target', '_self'), ['_self', '_blank']) ? $request->input('target') : '_self',
            'sort_order' => MenuItem::nextSortOrder($menuId),
            'is_visible' => (int) $request->input('is_visible', 1),
        ]);

        set_flash('success', __('messages.menu_item_added'));
        Response::redirect('/admin/menus#menu-' . $menuId);
    }

    /**
     * Update an existing menu item.
     * POST /admin/menus/items/update/{id}
     */
    public function updateItem(Request $request, array $params = []): void
    {
        $this->validateCsrf();

        $id   = (int) ($params['id'] ?? 0);
        $item = MenuItem::find($id);

        if (!$item) {
            set_flash('error', 'Menu item not found.');
            Response::redirect('/admin/menus');
            return;
        }

        $label = trim($request->input('label', ''));
        $url   = trim($request->input('url', ''));

        if ($label === '' || $url === '') {
            set_flash('error', __('messages.all_required'));
            Response::redirect('/admin/menus#menu-' . $item['menu_id']);
            return;
        }

        $pageId = $request->input('page_id', '');
        MenuItem::updateById($id, [
            'label'      => $label,
            'url'        => $url,
            'page_id'    => $pageId !== '' ? (int) $pageId : null,
            'target'     => in_array($request->input('target', '_self'), ['_self', '_blank']) ? $request->input('target') : '_self',
            'sort_order' => (int) $request->input('sort_order', $item['sort_order']),
            'is_visible' => (int) $request->input('is_visible', 1),
        ]);

        set_flash('success', 'Menu item updated.');
        Response::redirect('/admin/menus#menu-' . $item['menu_id']);
    }

    /**
     * Delete a menu item.
     * POST /admin/menus/items/delete/{id}
     */
    public function deleteItem(Request $request, array $params = []): void
    {
        $this->validateCsrf();

        $id   = (int) ($params['id'] ?? 0);
        $item = MenuItem::find($id);

        if ($item) {
            MenuItem::deleteById($id);
            set_flash('success', 'Menu item deleted.');
            Response::redirect('/admin/menus#menu-' . $item['menu_id']);
            return;
        }

        set_flash('error', 'Menu item not found.');
        Response::redirect('/admin/menus');
    }

    /**
     * Reorder items via JSON POST (used by drag & drop JS).
     * POST /admin/menus/items/reorder
     * Expects: csrf_token + order = JSON-encoded array of item IDs in new sequence.
     */
    public function reorder(Request $request, array $params = []): void
    {
        $this->validateCsrf();

        $order = json_decode($request->input('order', '[]'), true);
        if (!is_array($order)) {
            http_response_code(400);
            echo json_encode(['success' => false, 'error' => 'Invalid order data.']);
            return;
        }

        foreach ($order as $sortOrder => $itemId) {
            MenuItem::updateById((int) $itemId, ['sort_order' => (int) $sortOrder]);
        }

        echo json_encode(['success' => true]);
    }

    /**
     * Legacy stub redirect – kept for route compatibility.
     * POST /admin/menus/save
     */
    public function save(Request $request, array $params = []): void
    {
        Response::redirect('/admin/menus');
    }
}
