<?php

namespace App\Modules\Procurement\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Inventory\Models\Warehouse;
use App\Modules\Procurement\Models\PurchaseOrder;
use App\Support\Operational\PurchaseOrderOperationalPresenter;
use Illuminate\Http\Request;
use Illuminate\View\View;

class PurchaseOrderPageController extends Controller
{
    public function index(Request $request): View
    {
        $this->authorize('viewAny', PurchaseOrder::class);
        $status = $request->query('status');
        $q = PurchaseOrder::query()->withCount(['items', 'goodsReceipts']);
        if (is_string($status) && $status !== '') {
            $q->where('status', $status);
        }

        return view('pages.procurement.purchase-orders.index', [
            'purchaseOrders' => $q->orderByDesc('id')->paginate(25)->withQueryString(),
            'statusFilter' => is_string($status) ? $status : null,
        ]);
    }

    public function show(PurchaseOrder $purchaseOrder): View
    {
        $this->authorize('view', $purchaseOrder);
        $purchaseOrder->load([
            'items.inventoryItem.defaultUnit',
            'goodsReceipts' => static fn ($q) => $q->orderByDesc('id'),
        ]);

        $operational = app(PurchaseOrderOperationalPresenter::class)->detail($purchaseOrder);

        return view('pages.procurement.purchase-orders.show', [
            'purchaseOrder' => $purchaseOrder,
            'warehouseChoices' => Warehouse::query()->orderBy('code')->get(['id', 'code', 'name']),
            ...$operational,
        ]);
    }
}
