<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\InventoryBalance;
use App\Services\LocationService;
use Illuminate\Http\Request;
use Illuminate\View\View;

class InventoryBalanceController extends Controller
{
    public function __construct(protected LocationService $locationService)
    {
        $this->middleware('auth');
    }

    public function index(Request $request): View
    {
        $user = $request->user();
        $locations = $this->locationService->accessibleLocations($user);

        $requested = $request->input('location_id');
        if ($requested) {
            $locationId = $this->locationService->resolveAuthorizedLocationId($user, $requested);
        } else {
            $locationId = $this->locationService->resolveAuthorizedLocationId($user, null)
                ?: $locations->first()?->id;
        }

        $balances = InventoryBalance::query()
            ->with(['product', 'location'])
            ->when($locationId, fn ($q) => $q->where('location_id', $locationId))
            ->when(!$locationId, fn ($q) => $q->whereIn('location_id', $locations->pluck('id')->all() ?: [0]))
            ->when($request->filled('q'), function ($q) use ($request) {
                $q->whereHas('product', function ($p) use ($request) {
                    $p->where('name', 'like', '%' . $request->q . '%')
                        ->orWhere('sku', 'like', '%' . $request->q . '%')
                        ->orWhere('barcode', 'like', '%' . $request->q . '%');
                });
            })
            ->when($request->stock === 'available', fn ($q) => $q->whereRaw('(on_hand - reserved - damaged) > 0'))
            ->when($request->stock === 'zero', fn ($q) => $q->whereRaw('(on_hand - reserved - damaged) <= 0'))
            ->when($request->stock === 'reserved', fn ($q) => $q->where('reserved', '>', 0))
            ->orderByDesc('on_hand')
            ->paginate(50)
            ->withQueryString();

        return view('admin.inventory.balances', compact('balances', 'locations', 'locationId'));
    }
}
