<?php

namespace App\Livewire\Products;

use App\Models\Category;
use App\Models\Product;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Url;
use Livewire\WithPagination;
use Livewire\Component;

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

    // Filters (synced to query string)
    #[Url(as: 'search')]
    public string $search = '';

    #[Url(as: 'category_id')]
    public $category_id = '';

    #[Url(as: 'stock_status')]
    public string $stock_status = '';

    #[Url(as: 'status')]
    public $status = '';

    // Reset pagination when filters change
    public function updatedSearch(): void { $this->resetPage(); }
    public function updatedCategoryId(): void { $this->resetPage(); }
    public function updatedStockStatus(): void { $this->resetPage(); }
    public function updatedStatus(): void { $this->resetPage(); }
    /**
     * Render the component
     */
    public function render(): \Illuminate\Contracts\View\View
    {
        // Load products with pagination and filters
        $products = Product::with(['category', 'saleUnit'])
            ->when($this->search !== '', function ($query) {
                $search = $this->search;
                $query->where(function ($q) use ($search) {
                    $q->where('name', 'like', "%{$search}%")
                      ->orWhere('sku', 'like', "%{$search}%");
                });
            })
            ->when($this->category_id !== '' && $this->category_id !== null, function ($query) {
                $query->where('category_id', $this->category_id);
            })
            ->when($this->stock_status !== '', function ($query) {
                if ($this->stock_status === 'low') {
                    $query->whereColumn('current_stock', '<=', 'reorder_level')
                          ->where('current_stock', '>', 0);
                } elseif ($this->stock_status === 'out') {
                    $query->where('current_stock', 0);
                } elseif ($this->stock_status === 'in') {
                    $query->where('current_stock', '>', 0)
                          ->whereColumn('current_stock', '>', 'reorder_level');
                }
            })
            ->when($this->status !== '' && $this->status !== null, function ($query) {
                $query->where('status', $this->status);
            })
            ->latest()
            ->paginate(15);

        // Load categories for filter dropdown
        $categories = collect([
            (object) ['value' => '', 'label' => 'Tous'],
            ...Category::orderBy('name')->get()->map(function ($category) {
                return (object) [
                    'value' => $category->id,
                    'label' => $category->name,
                ];
            }),
        ]);

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