<?php

namespace App\Livewire\Inventory\PurchaseOrders;

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

class Index extends Component
{
    use WithPagination;

    public $search = '';
    public $statusFilter = '';
    public $supplierFilter = '';
    public $sortBy = 'order_date';
    public $sortDirection = 'desc';

    protected $queryString = [
        'search' => ['except' => ''],
        'statusFilter' => ['except' => ''],
        'supplierFilter' => ['except' => ''],
        'sortBy' => ['except' => 'order_date'],
        'sortDirection' => ['except' => 'desc'],
    ];

    public function updatingSearch()
    {
        $this->resetPage();
    }

    public function updatingStatusFilter()
    {
        $this->resetPage();
    }

    public function updatingSupplierFilter()
    {
        $this->resetPage();
    }

    public function sortBy($field)
    {
        if ($this->sortBy === $field) {
            $this->sortDirection = $this->sortDirection === 'asc' ? 'desc' : 'asc';
        } else {
            $this->sortBy = $field;
            $this->sortDirection = 'asc';
        }
    }

    public function clearFilters()
    {
        $this->reset(['search', 'statusFilter', 'supplierFilter']);
        $this->resetPage();
    }

    public function render()
    {
        $query = PurchaseOrder::with(['supplier', 'items']);

        // Apply search
        if ($this->search) {
            $query->where(function ($q) {
                $q->where('po_number', 'like', '%' . $this->search . '%')
                  ->orWhereHas('supplier', function ($sq) {
                      $sq->where('name', 'like', '%' . $this->search . '%');
                  });
            });
        }

        // Apply filters
        if ($this->statusFilter !== '') {
            $query->where('status', $this->statusFilter);
        }

        if ($this->supplierFilter !== '') {
            $query->where('supplier_id', $this->supplierFilter);
        }

        // Apply sorting
        $query->orderBy($this->sortBy, $this->sortDirection);

        $purchaseOrders = $query->paginate(15);
        $suppliers = Supplier::where('is_active', true)->orderBy('name')->get();

        return view('livewire.inventory.purchase-orders.index', [
            'purchaseOrders' => $purchaseOrders,
            'suppliers' => $suppliers,
        ]);
    }
}
