<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\NavigationItem;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class NavigationController extends Controller
{
    // Public: active top-level items with active children
    public function index(): JsonResponse
    {
        $items = Cache::remember('navigation', 300, function () {
            return NavigationItem::with(['children' => fn($q) => $q->where('is_active', true)->orderBy('sort_order')])
                ->whereNull('parent_id')
                ->where('is_active', true)
                ->orderBy('sort_order')
                ->get();
        });
        return response()->json(['data' => $items]);
    }

    // Admin: all items with children
    public function adminIndex(): JsonResponse
    {
        $items = NavigationItem::with(['children' => fn($q) => $q->orderBy('sort_order')])
            ->whereNull('parent_id')
            ->orderBy('sort_order')
            ->get();
        return response()->json(['data' => $items]);
    }

    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'parent_id'       => 'nullable|exists:navigation_items,id',
            'label'           => 'required|string|max:100',
            'url'             => 'required|string|max:500',
            'open_in_new_tab' => 'boolean',
            'is_active'       => 'boolean',
            'sort_order'      => 'integer',
        ]);
        $item = NavigationItem::create($data);
        Cache::forget('navigation');
        return response()->json(['data' => $item], 201);
    }

    public function update(Request $request, int $id): JsonResponse
    {
        $item = NavigationItem::findOrFail($id);
        $data = $request->validate([
            'parent_id'       => 'nullable|exists:navigation_items,id',
            'label'           => 'sometimes|string|max:100',
            'url'             => 'sometimes|string|max:500',
            'open_in_new_tab' => 'boolean',
            'is_active'       => 'boolean',
            'sort_order'      => 'integer',
        ]);
        $item->update($data);
        Cache::forget('navigation');
        return response()->json(['data' => $item]);
    }

    public function destroy(int $id): JsonResponse
    {
        $item = NavigationItem::findOrFail($id);
        // Delete children first
        $item->children()->delete();
        $item->delete();
        Cache::forget('navigation');
        return response()->json(['message' => 'Deleted.']);
    }

    // Reorder: accept [{id, sort_order}, ...]
    public function reorder(Request $request): JsonResponse
    {
        $items = $request->validate(['items' => 'required|array', 'items.*.id' => 'required|integer', 'items.*.sort_order' => 'required|integer']);
        foreach ($items['items'] as $row) {
            NavigationItem::where('id', $row['id'])->update(['sort_order' => $row['sort_order']]);
        }
        Cache::forget('navigation');
        return response()->json(['message' => 'Reordered.']);
    }
}
