<?php

namespace App\Http\Controllers;

use App\Models\Achat;
use App\Models\Caution;
use App\Models\Creance;
use App\Models\Transfert;
use App\Models\Vente;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;

class DashboardController extends Controller
{
    public function __invoke(Request $request)
    {
        // Statistiques globales
        $totalVentes = (int) Vente::sum('montant');

        $totalAchats = (int) Achat::where('type', Achat::TYPE_ACHAT)
            ->sum('montant');

        $achatsImpayes = (int) Achat::where('statut', Achat::STATUT_IMPAYE)
            ->sum('montant');

        $retoursAchat = (int) Achat::where('type', Achat::TYPE_RETOUR)
            ->sum('montant');

        $facturesImpayees = (int) Creance::where('statut', 'impaye')
            ->sum('montant_restant');

        $stats = [
            'totalVentes' => $totalVentes,
            'totalAchats' => $totalAchats,
            'net' => $totalVentes - $totalAchats,
            'achatsImpayes' => $achatsImpayes,
            'retoursAchat' => $retoursAchat,
            'facturesImpayees' => $facturesImpayees,
        ];

        // Évolution des ventes sur les 30 derniers jours par magasin
        $startDate = now()->subDays(29)->startOfDay();

        $ventes = Vente::with('magasin:id,nom')
            ->whereDate('date_vente', '>=', $startDate->toDateString())
            ->get();

        $labels = [];
        for ($d = 29; $d >= 0; $d--) {
            $labels[] = now()->subDays($d)->toDateString();
        }

        /** @var \Illuminate\Support\Collection<int, string> $magasinNoms */
        $magasinNoms = $ventes
            ->filter(fn(Vente $vente) => $vente->magasin)
            ->pluck('magasin.nom')
            ->unique()
            ->values();

        $ventesParMagasin = [];

        /** @var string $nom */
        foreach ($magasinNoms as $nom) {
            $serie = [];

            foreach ($labels as $date) {
                $total = (int) $ventes
                    ->filter(function (Vente $vente) use ($nom, $date) {
                        return $vente->magasin
                            && $vente->magasin->nom === $nom
                            && optional($vente->date_vente)->toDateString() === $date;
                    })
                    ->sum('montant');

                $serie[] = [
                    'date' => $date,
                    'montant' => $total,
                ];
            }

            $ventesParMagasin[$nom] = $serie;
        }

        // Activité récente : derniers transferts, ventes et cautions
        $recentTransferts = Transfert::with(['magasinOrigine', 'magasinDestination', 'produit'])
            ->latest('date_transfert')
            ->take(3)
            ->get();

        $recentVentes = Vente::with(['client', 'magasin'])
            ->latest('date_vente')
            ->take(3)
            ->get();

        $recentCautions = Caution::with('client')
            ->latest('date_depot')
            ->take(3)
            ->get();

        dd($stats);

        return view('dashboard', [
            'stats' => $stats,
            'ventesParMagasin' => $ventesParMagasin,
            'recentTransferts' => $recentTransferts,
            'recentVentes' => $recentVentes,
            'recentCautions' => $recentCautions,
        ]);
    }
}
