<?php

namespace App\Http\Controllers;

use App\Http\Requests\MasterMenuRequest;
use App\Models\MasterMenu;
use App\Models\MasterStand;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class MasterMenuController extends Controller
{
    public function index(Request $request): View
    {
        $query = MasterMenu::query()->with('stand')->withCount('packageComponents');
        $search = $request->query('q');

        if ($search) {
            $query->where('nama', 'like', '%' . $search . '%');
        }

        $menus = $query->orderByDesc('id')->paginate(10)->withQueryString();

        return view('master.menus.index', compact('menus', 'search'));
    }

    public function create(): View
    {
        $stands = MasterStand::orderBy('nama')->get();
        $componentMenus = MasterMenu::query()
            ->where('is_active', true)
            ->orderBy('nama')
            ->get(['id', 'nama', 'type_menu']);

        return view('master.menus.create', compact('stands', 'componentMenus'));
    }

    public function store(MasterMenuRequest $request): RedirectResponse
    {
        $data = $request->validated();

        if ($request->hasFile('image')) {
            $path = $request->file('image')->store('menus', 'public');
            $data['image'] = $path;

            $source = storage_path('app/public/' . $path);
            $targetDir = public_path('storage/' . dirname($path));
            if (!is_dir($targetDir)) {
                mkdir($targetDir, 0755, true);
            }
            @copy($source, public_path('storage/' . $path));
        }

        $packageItems = $this->normalizePackageItems($data['package_items'] ?? []);
        unset($data['package_items']);

        $menu = MasterMenu::create($data);

        if (! empty($data['is_package'])) {
            $menu->packageComponents()->sync($packageItems);
        }

        return redirect()->route('menus.index')->with('success', 'Menu berhasil ditambahkan.');
    }

    public function edit(MasterMenu $menu): View
    {
        $menu->load('packageComponents');

        $stands = MasterStand::orderBy('nama')->get();
        $componentMenus = MasterMenu::query()
            ->where('is_active', true)
            ->where('id', '!=', $menu->id)
            ->orderBy('nama')
            ->get(['id', 'nama', 'type_menu']);

        $selectedPackageItems = old('package_items');
        if ($selectedPackageItems === null) {
            $selectedPackageItems = $menu->packageComponents
                ->map(fn ($component) => [
                    'id_menu' => $component->id,
                    'qty' => (int) ($component->pivot->qty ?? 1),
                ])
                ->values()
                ->all();
        }

        return view('master.menus.edit', compact('menu', 'stands', 'componentMenus', 'selectedPackageItems'));
    }

    public function update(MasterMenuRequest $request, MasterMenu $menu): RedirectResponse
    {
        $data = $request->validated();

        if ($request->hasFile('image')) {
            if ($menu->image) {
                Storage::disk('public')->delete($menu->image);
                @unlink(public_path('storage/' . $menu->image));
            }
            $path = $request->file('image')->store('menus', 'public');
            $data['image'] = $path;

            $source = storage_path('app/public/' . $path);
            $targetDir = public_path('storage/' . dirname($path));
            if (!is_dir($targetDir)) {
                mkdir($targetDir, 0755, true);
            }
            @copy($source, public_path('storage/' . $path));
        } else {
            unset($data['image']);
        }

        $packageItems = $this->normalizePackageItems($data['package_items'] ?? []);
        unset($data['package_items']);

        $menu->update($data);

        if (! empty($data['is_package'])) {
            $menu->packageComponents()->sync($packageItems);
        } else {
            $menu->packageComponents()->detach();
        }

        return redirect()->route('menus.index')->with('success', 'Menu berhasil diperbarui.');
    }

    public function destroy(MasterMenu $menu): RedirectResponse
    {
        $menu->delete();

        return redirect()->route('menus.index')->with('success', 'Menu berhasil dihapus (soft delete).');
    }

    private function normalizePackageItems(array $rows): array
    {
        $sync = [];

        foreach ($rows as $row) {
            $componentId = (int) ($row['id_menu'] ?? 0);
            $qty = (int) ($row['qty'] ?? 0);
            if ($componentId <= 0 || $qty <= 0) {
                continue;
            }

            if (! isset($sync[$componentId])) {
                $sync[$componentId] = ['qty' => 0];
            }

            $sync[$componentId]['qty'] += $qty;
        }

        return $sync;
    }
}
