<?php

namespace App\Livewire\Inventory\StockMovements;

use App\Models\StockMovement;
use App\Models\Part;
use Livewire\Component;
use Livewire\WithPagination;

class Index extends Component
{
    use WithPagination;

    public $search = '';
    public $typeFilter = '';
    public $partFilter = '';
    public $dateFrom = '';
    public $dateTo = '';
    public $sortBy = 'created_at';
    public $sortDirection = 'desc';

    protected $queryString = [
        'search' => ['except' => ''],
        'typeFilter' => ['except' => ''],
        'partFilter' => ['except' => ''],
        'dateFrom' => ['except' => ''],
        'dateTo' => ['except' => ''],
        'sortBy' => ['except' => 'created_at'],
        'sortDirection' => ['except' => 'desc'],
    ];

    public function updatingSearch()
    {
        $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', 'typeFilter', 'partFilter', 'dateFrom', 'dateTo']);
        $this->resetPage();
    }

    public function render()
    {
        $query = StockMovement::with(['part', 'createdBy']);

        // Apply search
        if ($this->search) {
            $query->whereHas('part', function ($q) {
                $q->where('name', 'like', '%' . $this->search . '%')
                  ->orWhere('part_number', 'like', '%' . $this->search . '%');
            });
        }

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

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

        if ($this->dateFrom) {
            $query->whereDate('created_at', '>=', $this->dateFrom);
        }

        if ($this->dateTo) {
            $query->whereDate('created_at', '<=', $this->dateTo);
        }

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

        $movements = $query->paginate(20);
        $parts = Part::orderBy('name')->get();

        return view('livewire.inventory.stock-movements.index', [
            'movements' => $movements,
            'parts' => $parts,
        ]);
    }
}
