<?php

namespace App\Livewire\Inventory\Parts;

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

class Index extends Component
{
    use WithPagination;

    public $search = '';
    public $categoryFilter = '';
    public $statusFilter = '';
    public $stockFilter = '';
    public $supplierFilter = '';
    public $sortBy = 'name';
    public $sortDirection = 'asc';

    protected $queryString = [
        'search' => ['except' => ''],
        'categoryFilter' => ['except' => ''],
        'statusFilter' => ['except' => ''],
        'stockFilter' => ['except' => ''],
        'supplierFilter' => ['except' => ''],
        'sortBy' => ['except' => 'name'],
        'sortDirection' => ['except' => 'asc'],
    ];

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

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

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

    public function updatingStockFilter()
    {
        $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', 'categoryFilter', 'statusFilter', 'stockFilter', 'supplierFilter']);
        $this->resetPage();
    }

    public function render()
    {
        $query = Part::with('supplier');

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

        // Apply filters
        if ($this->categoryFilter) {
            $query->where('category', $this->categoryFilter);
        }

        if ($this->statusFilter) {
            $query->where('status', $this->statusFilter);
        }

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

        if ($this->stockFilter) {
            switch ($this->stockFilter) {
                case 'low_stock':
                    $query->whereColumn('quantity_on_hand', '<=', 'minimum_stock_level');
                    break;
                case 'out_of_stock':
                    $query->where('quantity_on_hand', '<=', 0);
                    break;
                case 'overstock':
                    $query->whereColumn('quantity_on_hand', '>=', 'maximum_stock_level');
                    break;
                case 'in_stock':
                    $query->where('quantity_on_hand', '>', 0)
                          ->whereColumn('quantity_on_hand', '>', 'minimum_stock_level')
                          ->whereColumn('quantity_on_hand', '<', 'maximum_stock_level');
                    break;
            }
        }

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

        $parts = $query->paginate(15);

        // Get filter options
        $categories = Part::distinct()->pluck('category')->filter()->sort();
        $suppliers = Supplier::active()->orderBy('name')->get();

        return view('livewire.inventory.parts.index', [
            'parts' => $parts,
            'categories' => $categories,
            'suppliers' => $suppliers,
        ]);
    }
}
