<?php

namespace App\Http\Controllers;

use App\Models\Product;
use Carbon\Carbon;
use Illuminate\Http\Request;

class InventoryDashboardController extends Controller
{
    public function export(Request $request)
    {
        // Export implementation
    }

    public function print(Request $request)
    {
        try {
            $request->validate([
                'print_date_from' => 'required|date',
                'print_date_to' => 'required|date|after_or_equal:print_date_from',
            ]);

            $dateFrom = Carbon::parse($request->get('print_date_from'));
            $dateTo = Carbon::parse($request->get('print_date_to'));

            $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,
                ],
            ];

            $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,
                ];
            }

            return view('livewire.reports.inventory-intelligence.print', [
                'lowStock' => $lowStock,
                'outOfStock' => $outOfStock,
                'expiringSoon' => $expiringSoon,
                'inventoryOverview' => $inventoryOverview,
                'stockAnalysis' => $stockAnalysis,
                'categoryInsights' => $categoryInsights,
                'dateFrom' => $dateFrom,
                'dateTo' => $dateTo,
            ]);
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Erreur lors de l\'impression: '.$e->getMessage());
        }
    }
}
