<?php

namespace App\Livewire\Reports;

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

#[Layout('layouts.dashboard')]
class InventoryIntelligence extends Component
{
    public ?string $dateFrom = null;
    public ?string $dateTo = null;

    public function mount(?string $dateFrom = null, ?string $dateTo = null): void
    {
        $this->dateFrom = $dateFrom ?? request('date_from') ?? request('dateFrom');
        $this->dateTo = $dateTo ?? request('date_to') ?? request('dateTo');
    }
    public function render(): \Illuminate\Contracts\View\View
    {
        // Set defaults if not provided
        if (!$this->dateFrom) {
            $this->dateFrom = now()->subDays(7)->format('Y-m-d');
        }
        if (!$this->dateTo) {
            $this->dateTo = now()->format('Y-m-d');
        }

        $dateFrom = $this->dateFrom;
        $dateTo = $this->dateTo;

        $products = Product::with(['category', 'saleUnit'])
            ->where('status', Product::STATUS_ACTIVE)
            ->get();
        $lowStock = $products->where('current_stock', '<=', 10);
        $outOfStock = $products->where('current_stock', 0);
        $expiringSoon = Product::where('status', Product::STATUS_ACTIVE)
            ->whereNotNull('expiry_date')
            ->where('expiry_date', '<=', Carbon::now()->addMonths(3))
            ->orderBy('expiry_date')
            ->get();

        $totalProducts = $products->count();
        $healthyCount = max($totalProducts - $lowStock->count() - $outOfStock->count(), 0);
        $totalInventoryValue = $products->sum(function ($p) { return (int)($p->current_stock ?? 0) * (int)($p->purchase_price ?? 0); });
        $stockHealthPct = $totalProducts > 0 ? (int) round(($healthyCount / $totalProducts) * 100) : 0;

        $inventoryOverview = [
            'total_inventory_value' => $totalInventoryValue,
            'total_products' => $totalProducts,
            'stock_health_percentage' => $stockHealthPct,
            'healthy_stock_products' => $healthyCount,
            'low_stock_products' => $lowStock->count(),
            'out_of_stock_products' => $outOfStock->count(),
        ];

        $stockAnalysis = [
            'stock_distribution' => [
                'out_of_stock' => $outOfStock->count(),
                'low_stock' => $lowStock->count(),
                'normal_stock' => $healthyCount,
                'high_stock' => 0,
                'overstock' => 0,
            ],
        ];

        $productPerformance = [
            'top_selling_products' => [],
        ];

        // ABC analysis placeholder (can be refined with real sales data)
        $abcAnalysis = [
            'A' => ['count' => 0, 'revenue' => 0],
            'B' => ['count' => 0, 'revenue' => 0],
            'C' => ['count' => 0, 'revenue' => 0],
        ];

        $categoryInsights = [];
        $byCategory = $products->groupBy(fn($p) => optional($p->category)->id ?: 'uncat');
        foreach ($byCategory as $group) {
            $category = optional($group->first())->category;
            $categoryInsights[] = [
                'category' => $category,
                'total_products' => $group->count(),
                'total_inventory_value' => $group->sum(function ($p) { return (int)($p->current_stock ?? 0) * (int)($p->purchase_price ?? 0); }),
                'stock_health_percentage' => $group->count() > 0 ? (int) round(($group->where('current_stock', '>', 10)->count() / $group->count()) * 100) : 0,
            ];
        }

        $strategicInsights = [];
        if ($outOfStock->count() > 0) {
            $strategicInsights[] = [
                'type' => 'warning',
                'title' => 'Ruptures de stock détectées',
                'message' => $outOfStock->count().' produits en rupture nécessitent un réapprovisionnement.',
            ];
        }

        return view('livewire.reports.inventory-intelligence.index', compact(
            'lowStock', 'outOfStock', 'expiringSoon', 'inventoryOverview', 'stockAnalysis', 'productPerformance', 'categoryInsights', 'strategicInsights', 'abcAnalysis', 'dateFrom', 'dateTo'
        ));
    }
}


