<?php

namespace App\Livewire\Inventory;

use App\Domain\Inventory\Models\Product;
use App\Domain\Inventory\Models\ProductCategory;
use App\Domain\Shared\Traits\UsesBranchScope;
use App\Livewire\Concerns\AppliesRoleScope;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('layouts.app')]
#[Title('المنتجات')]
class ProductList extends Component
{
    use WithPagination, UsesBranchScope, AppliesRoleScope;

    protected string $scopePermission = 'inventory.list';

    #[Url]
    public string $search = '';

    #[Url]
    public string $categoryFilter = '';

    #[Url]
    public string $activeFilter = '';

    #[Url]
    public string $stockFilter = '';

    public function updatedSearch(): void
    {
        $this->resetPage();
    }

    public function updatedCategoryFilter(): void
    {
        $this->resetPage();
    }

    public function updatedActiveFilter(): void
    {
        $this->resetPage();
    }

    public function updatedStockFilter(): void
    {
        $this->resetPage();
    }

    public function toggleActive(int $productId): void
    {
        $product = Product::findOrFail($productId);
        $product->update(['is_active' => !$product->is_active]);
    }

    public function render()
    {
        $branchId = $this->getActiveBranchId();

        $query = Product::query()
            ->with(['category', 'inventoryLevels'])
            ->when($branchId, fn ($q) => $q->where(function ($sub) use ($branchId) {
                $sub->where('branch_id', $branchId)->orWhereNull('branch_id');
            }))
            ->when($this->search, function ($q) {
                $search = $this->search;
                $q->where(function ($q2) use ($search) {
                    $q2->where('name_ar', 'ilike', "%{$search}%")
                       ->orWhere('name', 'ilike', "%{$search}%")
                       ->orWhere('sku', 'ilike', "%{$search}%")
                       ->orWhere('barcode', 'ilike', "%{$search}%");
                });
            })
            ->when($this->categoryFilter, fn ($q) => $q->where('category_id', $this->categoryFilter))
            ->when($this->activeFilter !== '', function ($q) {
                if ($this->activeFilter === '1') {
                    $q->where('is_active', true);
                } elseif ($this->activeFilter === '0') {
                    $q->where('is_active', false);
                }
            })
            ->when($this->stockFilter === 'low', function ($q) {
                $q->where('track_inventory', true)
                  ->where('is_active', true)
                  ->whereNotNull('min_stock_level')
                  ->where('min_stock_level', '>', 0)
                  ->whereHas('inventoryLevels', fn ($il) => $il->whereRaw('quantity_on_hand <= (SELECT min_stock_level FROM products WHERE products.id = inventory_levels.product_id)'));
            })
            ->orderByDesc('created_at');

        $this->applyRoleScope($query);

        return view('livewire.inventory.product-list', [
            'products' => $query->paginate(20),
            'categories' => ProductCategory::active()->orderBy('name_ar')->get(['id', 'name_ar']),
        ]);
    }
}
