<?php

namespace Modules\LandingPage\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Modules\LandingPage\Entities\Menu;
use Modules\LandingPage\Entities\MenuItem;
use Modules\LandingPage\Entities\LpPage;

class MenuItemController extends Controller
{
    /**
     * Store a newly created menu item in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Modules\LandingPage\Entities\Menu  $menu
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(Request $request, Menu $menu)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'type' => 'required|in:page,url,route',
            'lp_page_id' => 'nullable|required_if:type,page|exists:lp_pages,id',
            'url' => 'nullable|required_if:type,url|url|max:2048',
            'route_name' => 'nullable|required_if:type,route|string|max:255',
            'route_parameters' => 'nullable|json',
            'target' => 'nullable|in:_self,_blank',
            'icon_class' => 'nullable|string|max:255',
            'css_class' => 'nullable|string|max:255',
            'parent_id' => 'nullable|exists:lp_menu_items,id,menu_id,' . $menu->id,
            'is_active' => 'nullable|boolean',
        ]);

        $order = $menu->items()->where('parent_id', $request->input('parent_id'))->max('sort_order') + 1;

        $menuItemData = [
            'menu_id' => $menu->id,
            'title' => $request->input('title'),
            'type' => $request->input('type'),
            'target' => $request->input('target', '_self'),
            'icon_class' => $request->input('icon_class'),
            'css_class' => $request->input('css_class'),
            'parent_id' => $request->input('parent_id'),
            'is_active' => $request->has('is_active'), // Set based on checkbox presence
            'sort_order' => $order,
        ];

        // Clear fields not relevant to the selected type
        $menuItemData['lp_page_id'] = null;
        $menuItemData['url'] = null;
        $menuItemData['route_name'] = null;
        $menuItemData['parameters'] = null;

        switch ($menuItemData['type']) {
            case 'page':
                $menuItemData['lp_page_id'] = $request->input('lp_page_id');
                break;
            case 'url':
                $menuItemData['url'] = $request->input('url');
                break;
            case 'route':
                $menuItemData['route_name'] = $request->input('route_name');
                $menuItemData['parameters'] = $request->filled('route_parameters') ? json_decode($request->input('route_parameters'), true) : null;
                break;
        }

        MenuItem::create($menuItemData);

        return redirect()->route('admin.landingpage.menus.edit', $menu->id)
                         ->with('success', 'Menu item added successfully.');
    }


    /**
     * Update the specified menu item in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Modules\LandingPage\Entities\Menu  $menu
     * @param  \Modules\LandingPage\Entities\MenuItem  $item // Route model binding for item
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request, Menu $menu, MenuItem $item)
    {
        // Ensure the item belongs to the menu
        if ($item->menu_id !== $menu->id) {
            abort(404);
        }

        $request->validate([
            'title' => 'required|string|max:255',
            'type' => 'required|in:page,url,route',
            'lp_page_id' => 'nullable|required_if:type,page|exists:lp_pages,id',
            'url' => 'nullable|required_if:type,url|url|max:2048',
            'route_name' => 'nullable|required_if:type,route|string|max:255',
            'route_parameters' => 'nullable|json',
            'target' => 'nullable|in:_self,_blank',
            'icon_class' => 'nullable|string|max:255',
            'css_class' => 'nullable|string|max:255',
            // Parent ID update is complex with reordering, handle separately or simplify for now
            'is_active' => 'nullable|boolean',
        ]);

        $itemData = $request->only(['title', 'type', 'target', 'icon_class', 'css_class']);
        $itemData['is_active'] = $request->has('is_active'); // Set based on checkbox presence

        // Reset link-specific fields before setting the correct one based on type
        $itemData['lp_page_id'] = null; // Reset link types
        $itemData['url'] = null;
        $itemData['route_name'] = null;
        $itemData['parameters'] = null;

        switch ($itemData['type']) {
            case 'page': $itemData['lp_page_id'] = $request->input('lp_page_id'); break;
            case 'url': $itemData['url'] = $request->input('url'); break;
            case 'route':
                $itemData['route_name'] = $request->input('route_name');
                $itemData['parameters'] = $request->filled('route_parameters') ? json_decode($request->input('route_parameters'), true) : null;
                break;
        }

        $item->update($itemData);

        return redirect()->route('admin.landingpage.menus.edit', $menu->id)
                         ->with('success', 'Menu item updated successfully.');
    }

    /**
     * Remove the specified menu item from storage.
     *
     * @param  \Modules\LandingPage\Entities\Menu  $menu
     * @param  \Modules\LandingPage\Entities\MenuItem  $item
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy(Menu $menu, MenuItem $item)
    {
        if ($item->menu_id !== $menu->id) {
            abort(404);
        }
        $item->delete(); // Children will be cascade deleted by DB constraint if parent_id is set up correctly
        return redirect()->route('admin.landingpage.menus.edit', $menu->id)
                         ->with('success', 'Menu item deleted successfully.');
    }

    // We might add an 'edit' method later if we use a separate page/modal for editing items.
    // For now, editing might be inline or via a simple form on the menu edit page.

    /**
     * Update the order and parentage of menu items.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Modules\LandingPage\Entities\Menu  $menu
     * @return \Illuminate\Http\JsonResponse
     */
    public function reorder(Request $request, Menu $menu)
    {
        $request->validate([
            'items' => 'required|array',
            'items.*.id' => 'required|integer|exists:lp_menu_items,id,menu_id,' . $menu->id, // Ensure item belongs to this menu
            'items.*.sort_order' => 'required|integer|min:0',
            'items.*.parent_id' => 'nullable|integer|exists:lp_menu_items,id,menu_id,' . $menu->id, // Ensure parent (if any) also belongs to this menu
        ]);

        \DB::transaction(function () use ($request) {
            foreach ($request->input('items') as $itemData) {
                MenuItem::where('id', $itemData['id'])
                        ->update(['sort_order' => $itemData['sort_order'], 'parent_id' => $itemData['parent_id']]);
            }
        });

        return response()->json(['message' => 'Menu items reordered successfully.']);
    }
}