<?php

namespace App\Livewire\StockAdjustments;

use App\Models\StockAdjustment;
use Livewire\Attributes\Layout;
use Livewire\Component;
use Livewire\WithPagination;

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

    protected string $paginationTheme = 'tailwind';

    public string $search = '';

    public string $statusFilter = '';

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

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

    public function render(): \Illuminate\Contracts\View\View
    {
        $adjustments = StockAdjustment::query()
            ->with(['items.product', 'user'])
            ->when($this->search, function ($query) {
                $query->whereHas('items.product', function ($q) {
                    $q->where('name', 'like', '%'.$this->search.'%');
                })->orWhere('reference', 'like', '%'.$this->search.'%');
            })
            ->when($this->statusFilter, function ($query) {
                $query->where('status', $this->statusFilter);
            })
            ->orderByDesc('created_at')
            ->paginate(25);

        return view('livewire.stock-adjustments.index', compact('adjustments'));
    }
}
