<?php

namespace App\Livewire\PurchaseOrders;

use App\Models\PurchaseOrder;
use App\Models\Supplier;
use Livewire\Attributes\Layout;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('layouts.dashboard')]
class Index extends Component
{
    use WithPagination;

    protected string $paginationTheme = 'tailwind';

    public function render(): \Illuminate\Contracts\View\View
    {
        // Get filter values from request
        $search = request('search');
        $supplierId = request('supplier_id');
        $status = request('status');

        $purchaseOrders = PurchaseOrder::query()
            ->with(['supplier', 'user'])
            ->withCount('items')
            ->when($search, function ($query) use ($search) {
                $query->where(function ($q) use ($search) {
                    $q->where('reference', 'like', '%'.$search.'%')
                        ->orWhereHas('supplier', function ($supplierQuery) use ($search) {
                            $supplierQuery->where('name', 'like', '%'.$search.'%');
                        });
                });
            })
            ->when($supplierId, function ($query) use ($supplierId) {
                $query->where('supplier_id', $supplierId);
            })
            ->when($status !== null && $status !== '', function ($query) use ($status) {
                $query->where('status', $status);
            })
            ->orderByDesc('created_at')
            ->paginate(25)
            ->withQueryString();

        $suppliers = collect(
            Supplier::orderBy('name')->get()->map(function ($supplier) {
                return (object) [
                    'id' => $supplier->id,
                    'name' => $supplier->name,
                ];
            })
        );

        return view('livewire.purchase-orders.index', compact('purchaseOrders', 'suppliers'));
    }
}
