<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Client;
use App\Models\Product;
use App\Models\Invoice;
use App\Models\Quote;
use App\Models\Caution;
use App\Models\StockMovement;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class DashboardController extends Controller
{
    public function index(): JsonResponse
    {
        // Statistiques de base
        $totalClients = Client::where('is_active', true)->count();
        $totalProducts = Product::where('is_active', true)->count();
        $pendingInvoices = Invoice::where('status', 'sent')->count();
        $lowStockProducts = Product::whereRaw('current_stock <= minimum_stock')->count();
        $pendingQuotes = Quote::where('status', 'sent')->count();
        
        // Alertes cautions proches de l'échéance (7 prochains jours)
        $upcomingCautions = Caution::where('status', 'active')
            ->where('notification_date', '<=', Carbon::now()->addDays(7))
            ->where('notification_date', '>=', Carbon::now())
            ->with(['check.checkbook'])
            ->get();

        // Calculs financiers
        $totalSales = Invoice::where('type', 'sale')
            ->where('status', '!=', 'cancelled')
            ->sum('total_ttc');

        $totalPurchases = Invoice::where('type', 'purchase')
            ->where('status', '!=', 'cancelled')
            ->sum('total_ttc');

        // Évolution mensuelle du chiffre d'affaires (12 derniers mois)
        $monthlyRevenue = [];
        for ($i = 11; $i >= 0; $i--) {
            $date = Carbon::now()->subMonths($i);
            $revenue = Invoice::where('type', 'sale')
                ->where('status', '!=', 'cancelled')
                ->whereYear('date', $date->year)
                ->whereMonth('date', $date->month)
                ->sum('total_ttc');

            $monthlyRevenue[] = [
                'month' => $date->format('M Y'),
                'revenue' => (float) $revenue,
            ];
        }

        // Top 5 des produits les plus vendus
        $topProducts = DB::table('invoice_items')
            ->join('invoices', 'invoice_items.invoice_id', '=', 'invoices.id')
            ->join('products', 'invoice_items.product_id', '=', 'products.id')
            ->where('invoices.type', 'sale')
            ->where('invoices.status', '!=', 'cancelled')
            ->select(
                'products.id',
                'products.name',
                'products.reference',
                DB::raw('SUM(invoice_items.quantity) as total_quantity'),
                DB::raw('SUM(invoice_items.total_ttc) as total_revenue')
            )
            ->groupBy('products.id', 'products.name', 'products.reference')
            ->orderBy('total_revenue', 'desc')
            ->limit(5)
            ->get()
            ->map(function ($item) {
                return [
                    'product' => [
                        'id' => $item->id,
                        'name' => $item->name,
                        'reference' => $item->reference,
                    ],
                    'quantity' => (int) $item->total_quantity,
                    'revenue' => (float) $item->total_revenue,
                ];
            });

        return response()->json([
            'totalClients' => $totalClients,
            'totalProducts' => $totalProducts,
            'pendingInvoices' => $pendingInvoices,
            'pendingQuotes' => $pendingQuotes,
            'lowStockProducts' => $lowStockProducts,
            'upcomingCautions' => $upcomingCautions,
            'totalSales' => (float) $totalSales,
            'totalPurchases' => (float) $totalPurchases,
            'monthlyRevenue' => $monthlyRevenue,
            'topProducts' => $topProducts,
        ]);
    }
}