<?php

namespace App\Livewire\Inventory\Parts;

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

class History extends Component
{
    use WithPagination;

    public Part $part;
    public $eventTypeFilter = '';
    public $dateFrom = '';
    public $dateTo = '';

    protected $queryString = [
        'eventTypeFilter' => ['except' => ''],
        'dateFrom' => ['except' => ''],
        'dateTo' => ['except' => ''],
    ];

    public function mount()
    {
        // Clear date filters if they are set to today (which would exclude our test data)
        if ($this->dateFrom === now()->format('Y-m-d') && $this->dateTo === now()->format('Y-m-d')) {
            $this->dateFrom = null;
            $this->dateTo = null;
        }
    }

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

    public function clearFilters()
    {
        $this->reset(['eventTypeFilter', 'dateFrom', 'dateTo']);
        $this->resetPage();
    }

    public function goBack()
    {
        return $this->redirect(route('inventory.parts.show', $this->part), navigate: true);
    }

    public function render()
    {
        $query = PartHistory::where('part_id', $this->part->id)
            ->with(['createdBy'])
            ->orderBy('created_at', 'desc');

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

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

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

        $histories = $query->paginate(20);

        $eventTypes = [
            PartHistory::EVENT_CREATED => 'Created',
            PartHistory::EVENT_UPDATED => 'Updated',
            PartHistory::EVENT_STOCK_IN => 'Stock In',
            PartHistory::EVENT_STOCK_OUT => 'Stock Out',
            PartHistory::EVENT_ADJUSTMENT => 'Adjustment',
            PartHistory::EVENT_PRICE_CHANGE => 'Price Change',
            PartHistory::EVENT_SUPPLIER_CHANGE => 'Supplier Change',
        ];

        return view('livewire.inventory.parts.history', [
            'histories' => $histories,
            'eventTypes' => $eventTypes,
        ]);
    }
}
