<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreItemRequest;
use App\Models\Category;
use App\Models\Item;
use App\Models\ItemStock;
use App\Models\Location;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class ItemController extends Controller
{
    public function index(Request $request): View
    {
        $items = Item::query()
            ->with(['location', 'category', 'stock'])
            ->when($request->string('search')->value(), fn ($query, $search) => $query->where('name', 'like', "%{$search}%"))
            ->when($request->integer('location_id'), fn ($query, $locationId) => $query->where('location_id', $locationId))
            ->when($request->string('tracking_mode')->value(), fn ($query, $trackingMode) => $query->where('tracking_mode', $trackingMode))
            ->latest()
            ->paginate(15)
            ->withQueryString();

        return view('items.index', [
            'items' => $items,
            'locations' => Location::query()->orderBy('name')->get(),
        ]);
    }

    public function create(): View
    {
        return view('items.form', [
            'item' => new Item([
                'tracking_mode' => 'stock',
                'unit_of_measure' => 'unit',
                'is_active' => true,
            ]),
            'locations' => Location::query()->orderBy('name')->get(),
            'categories' => Category::query()->where('scope', 'inventory')->orderBy('name')->get(),
            'action' => route('items.store'),
            'method' => 'POST',
        ]);
    }

    public function store(StoreItemRequest $request): RedirectResponse
    {
        $item = new Item();
        $this->persist($item, $request->validated());

        return redirect()->route('items.index')->with('status', 'Barang inventaris berhasil ditambahkan.');
    }

    public function edit(Item $item): View
    {
        return view('items.form', [
            'item' => $item->load('category'),
            'locations' => Location::query()->orderBy('name')->get(),
            'categories' => Category::query()->where('scope', 'inventory')->orderBy('name')->get(),
            'action' => route('items.update', $item),
            'method' => 'PUT',
        ]);
    }

    public function update(StoreItemRequest $request, Item $item): RedirectResponse
    {
        $this->persist($item, $request->validated());

        return redirect()->route('items.index')->with('status', 'Barang inventaris berhasil diperbarui.');
    }

    public function show(Item $item): View
    {
        return view('items.show', [
            'item' => $item->load(['location', 'category', 'stock']),
            'logs' => $item->maintenanceLogs()->with('submitter')->latest('performed_at')->get(),
        ]);
    }

    public function destroy(Item $item): RedirectResponse
    {
        $item->delete();

        return redirect()->route('items.index')->with('status', 'Barang inventaris berhasil dihapus.');
    }

    protected function persist(Item $item, array $validated): void
    {
        $sum = $validated['good_count'] + $validated['minor_damage_count'] + $validated['major_damage_count'] + $validated['lost_count'];
        $total = max($validated['total_quantity'], $sum);
        $categoryId = null;

        if ($validated['category_name'] ?? null) {
            $category = Category::query()->firstOrCreate(
                ['slug' => Str::slug($validated['category_name'])],
                [
                    'name' => $validated['category_name'],
                    'scope' => 'inventory',
                ]
            );

            $categoryId = $category->id;
        }

        $item->fill([
            'location_id' => $validated['location_id'],
            'category_id' => $categoryId,
            'name' => $validated['name'],
            'slug' => Str::slug($validated['name']),
            'tracking_mode' => $validated['tracking_mode'],
            'unit_of_measure' => $validated['unit_of_measure'],
            'total_quantity' => $total,
            'good_count' => $validated['good_count'],
            'minor_damage_count' => $validated['minor_damage_count'],
            'major_damage_count' => $validated['major_damage_count'],
            'lost_count' => $validated['lost_count'],
            'notes' => $validated['notes'] ?? null,
            'last_checked_at' => $validated['last_checked_at'] ?? null,
            'is_active' => (bool) ($validated['is_active'] ?? true),
            'qr_token' => $item->qr_token ?: (string) Str::uuid(),
        ]);
        $item->save();

        $stock = $item->stock;
        ItemStock::query()->updateOrCreate(
            ['item_id' => $item->id],
            [
                'available_quantity' => $validated['tracking_mode'] === 'stock' ? $validated['good_count'] : ($stock?->available_quantity ?? 0),
                'borrowed_quantity' => $stock?->borrowed_quantity ?? 0,
                'maintenance_quantity' => $validated['minor_damage_count'] + $validated['major_damage_count'] + $validated['lost_count'],
            ]
        );
    }
}
