<?php

namespace App\Livewire\StockEntries;

use App\Models\StockEntry;
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');
        $sourceType = request('source_type');
        $dateFrom = request('date_from');

        $stockEntries = StockEntry::query()
            ->with(['product', 'supplier', 'purchaseOrder', 'user'])
            ->when($search, function ($query) use ($search) {
                $query->where(function ($q) use ($search) {
                    $q->whereHas('product', function ($productQuery) use ($search) {
                        $productQuery->where('name', 'like', '%'.$search.'%');
                    })->orWhere('reference', 'like', '%'.$search.'%');
                });
            })
            ->when($sourceType !== null && $sourceType !== '', function ($query) use ($sourceType) {
                $query->where('source_type', $sourceType);
            })
            ->when($dateFrom, function ($query) use ($dateFrom) {
                $query->whereDate('created_at', '>=', $dateFrom);
            })
            ->orderByDesc('created_at')
            ->paginate(25)
            ->withQueryString();

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