<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Models\Emplette;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;

class DashboardController extends Controller
{
    public function __invoke(): JsonResponse
    {
        $now = now();
        $todayStart = $now->copy()->startOfDay();
        $monthStart = $now->copy()->startOfMonth();
        $timeseriesStart = $now->copy()->subDays(29)->startOfDay(); // 30 derniers jours

        // Commandes payées uniquement pour les montants
        $paidOrdersQuery = Order::where('payment_status', Order::PAYMENT_PAID);

        $totalOrders = Order::count();
        $totalRevenue = (float) $paidOrdersQuery->clone()->sum('total');

        $todayOrders = $paidOrdersQuery->clone()
            ->whereBetween('created_at', [$todayStart, $now])
            ->count();
        $todayRevenue = (float) $paidOrdersQuery->clone()
            ->whereBetween('created_at', [$todayStart, $now])
            ->sum('total');

        $monthOrders = $paidOrdersQuery->clone()
            ->whereBetween('created_at', [$monthStart, $now])
            ->count();
        $monthRevenue = (float) $paidOrdersQuery->clone()
            ->whereBetween('created_at', [$monthStart, $now])
            ->sum('total');

        // Emplettes en cours (pas encore converties ou rejetées)
        $pendingEmplettes = Emplette::whereIn('status', [
            Emplette::STATUS_SUBMITTED,
            Emplette::STATUS_QUOTING,
            Emplette::STATUS_QUOTED,
            Emplette::STATUS_CLIENT_REVIEW,
        ])->count();

        // Livreurs actifs
        $activeLivreurs = User::where('role', User::ROLE_LIVREUR)
            ->where('is_active', true)
            ->count();

        // Livraisons en cours (commandes non livrées / non annulées)
        $deliveriesInProgress = Order::whereIn('delivery_status', [
            Order::DELIVERY_ASSIGNED,
            Order::DELIVERY_ACCEPTED,
            Order::DELIVERY_PICKED_UP,
            Order::DELIVERY_IN_TRANSIT,
        ])->count();

        // Timeseries commandes / revenus (30 derniers jours, commandes payées)
        $ordersTimeseriesRaw = $paidOrdersQuery->clone()
            ->whereBetween('created_at', [$timeseriesStart, $now])
            ->selectRaw('DATE(created_at) as date, COUNT(*) as orders, SUM(total) as revenue')
            ->groupBy('date')
            ->orderBy('date')
            ->get()
            ->keyBy('date');

        $ordersTimeseries = [];
        $cursor = $timeseriesStart->copy();
        while ($cursor->lte($now)) {
            $key = $cursor->toDateString();
            $row = $ordersTimeseriesRaw->get($key);
            $ordersTimeseries[] = [
                'date' => $key,
                'orders' => $row ? (int) $row->orders : 0,
                'revenue' => $row ? (float) $row->revenue : 0.0,
            ];
            $cursor->addDay();
        }

        // Top produits (hors emplettes custom, donc product_id non nul)
        $topProducts = OrderItem::query()
            ->whereNotNull('product_id')
            ->selectRaw('product_id, product_name, SUM(quantity) as quantity, SUM(total) as revenue')
            ->groupBy('product_id', 'product_name')
            ->orderByDesc('quantity')
            ->limit(5)
            ->get()
            ->map(fn (OrderItem $item) => [
                'product_id' => $item->product_id,
                'product_name' => $item->product_name,
                'quantity' => (int) $item->quantity,
                'revenue' => (float) $item->revenue,
            ])
            ->values();

        // Dernières commandes
        $recentOrders = Order::with('user')
            ->latest('created_at')
            ->limit(5)
            ->get()
            ->map(fn (Order $order) => [
                'id' => $order->id,
                'number' => $order->number,
                'total' => (float) $order->total,
                'status' => $order->status,
                'payment_status' => $order->payment_status,
                'created_at' => $order->created_at?->toIso8601String(),
                'customer_name' => $order->user?->name,
            ])
            ->values();

        return response()->json([
            'data' => [
                'cards' => [
                    'total_orders' => $totalOrders,
                    'total_revenue' => $totalRevenue,
                    'today_orders' => $todayOrders,
                    'today_revenue' => $todayRevenue,
                    'month_orders' => $monthOrders,
                    'month_revenue' => $monthRevenue,
                    'pending_emplettes' => $pendingEmplettes,
                    'active_livreurs' => $activeLivreurs,
                    'deliveries_in_progress' => $deliveriesInProgress,
                ],
                'top_products' => $topProducts,
                'recent_orders' => $recentOrders,
                'orders_timeseries' => $ordersTimeseries,
                'generated_at' => Carbon::now()->toIso8601String(),
            ],
        ]);
    }
}

