<?php

namespace App\Livewire\Reports;

use App\Models\Product;
use Livewire\Attributes\Layout;
use Livewire\Component;

#[Layout('layouts.dashboard')]
class StockReport extends Component
{
    public string $stock_status = 'all'; // all, in_stock, low_stock, out_of_stock

    public function mount(?string $stock_status = null): void
    {
        $this->stock_status = $stock_status ?? request('stock_status') ?? 'all';
    }

    private function getStockSummary()
    {
        $totalProducts = Product::where('status', Product::STATUS_ACTIVE)->count();

        $totalStockValue = Product::where('status', Product::STATUS_ACTIVE)
            ->get()
            ->sum(function ($product) {
                return $product->current_stock * ($product->purchase_price ?? 0);
            });

        $totalStockQuantity = Product::where('status', Product::STATUS_ACTIVE)
            ->sum('current_stock');

        $lowStockProducts = Product::where('status', Product::STATUS_ACTIVE)
            ->whereColumn('current_stock', '<=', 'reorder_level')
            ->count();

        $outOfStockProducts = Product::where('status', Product::STATUS_ACTIVE)
            ->where('current_stock', '<=', 0)
            ->count();

        $inStockProducts = Product::where('status', Product::STATUS_ACTIVE)
            ->where('current_stock', '>', 0)
            ->count();

        return [
            'total_products' => $totalProducts,
            'total_stock_value' => $totalStockValue,
            'total_stock_quantity' => $totalStockQuantity,
            'low_stock_products' => $lowStockProducts,
            'out_of_stock_products' => $outOfStockProducts,
            'in_stock_products' => $inStockProducts,
            'average_stock_value' => $totalProducts > 0 ? $totalStockValue / $totalProducts : 0,
        ];
    }

    private function getProductsStock()
    {
        $query = Product::with(['saleUnit', 'purchaseUnit'])
            ->where('status', Product::STATUS_ACTIVE);

        // Apply stock status filter
        if ($this->stock_status === 'in_stock') {
            $query->where('current_stock', '>', 0);
        } else        if ($this->stock_status === 'low_stock') {
            $query->whereColumn('current_stock', '<=', 'reorder_level')
                ->where('current_stock', '>', 0);
        } elseif ($this->stock_status === 'out_of_stock') {
            $query->where('current_stock', '<=', 0);
        }

        return $query->orderBy('name')
            ->get()
            ->map(function ($product) {
                $stockValue = $product->current_stock * ($product->purchase_price ?? 0);
                $stockStatus = $this->getStockStatus($product);

                // Use saleUnit name for display
                $unit = $product->saleUnit?->name ?? 'N/A';

                return [
                    'id' => $product->id,
                    'slug' => $product->slug,
                    'name' => $product->name,
                    'sku' => $product->sku,
                    'current_stock' => $product->current_stock,
                    'unit' => $unit,
                    'purchase_price' => $product->purchase_price ?? 0,
                    'stock_value' => $stockValue,
                    'stock_status' => $stockStatus,
                    'last_restocked' => $product->updated_at->format('d/m/Y'),
                ];
            });
    }

    private function getStockStatus($product)
    {
        if ($product->current_stock <= 0) {
            return [
                'label' => 'Rupture',
                'color' => 'red',
                'icon' => 'x-circle',
            ];
        } elseif ($product->current_stock <= $product->reorder_level) {
            return [
                'label' => 'Stock faible',
                'color' => 'orange',
                'icon' => 'warning',
            ];
        } else {
            return [
                'label' => 'En stock',
                'color' => 'green',
                'icon' => 'check-circle',
            ];
        }
    }

    public function render(): \Illuminate\Contracts\View\View
    {
        $stockSummary = $this->getStockSummary();
        $productsStock = $this->getProductsStock();


        return view('livewire.reports.stock.index', compact(
            'stockSummary',
            'productsStock'
        ));
    }
}
