<?php
namespace App\Services;

use App\Models\Candidat;
use App\Models\Client;
use App\Models\Mission;
use App\Models\Besoin;
use App\Models\Signalement;
use App\Models\PieceJointe;
use Illuminate\Support\Collection;

class DashboardService
{
    public function getKpis(): array
    {
        return [
            'candidats_disponibles' => Candidat::where('statut', 'disponible')->count(),
            'candidats_en_mission' => Candidat::where('statut', 'en_mission')->count(),
            'candidats_en_attente' => Candidat::whereIn('statut', ['soumis', 'attente_paiement', 'paiement_recu', 'contrat_formation_signe', 'formation_suivie'])->count(),
            'missions_actives' => Mission::where('statut', 'active')->count(),
            'total_clients' => Client::count(),
            'total_candidats' => Candidat::count(),
        ];
    }

    public function getAlertes(): array
    {
        return [
            'casiers_expires' => PieceJointe::where('type_document', 'casier_judiciaire')
                ->where('date_expiration', '<', now())
                ->count(),
            'casiers_bientot_expires' => PieceJointe::where('type_document', 'casier_judiciaire')
                ->whereBetween('date_expiration', [now(), now()->addDays(30)])
                ->count(),
            'dossiers_incomplets' => Candidat::whereIn('statut', ['soumis', 'attente_paiement'])
                ->whereDoesntHave('piecesJointes', function ($query) {
                    $query->where('statut_validation', 'valide');
                })
                ->count(),
            'signalements_critiques' => Signalement::whereIn('priorite', ['haute', 'urgente'])
                ->where('statut', 'ouvert')
                ->count(),
            // missions_sans_descente_30j removed - descente_terrains table doesn't exist in Phase 4
            'missions_sans_descente_30j' => 0,
        ];
    }

    public function getActiviteRecente(): array
    {
        return [
            'derniers_besoins' => Besoin::latest()->take(5)->with(['client', 'ville', 'quartier'])->get(),
            'derniers_candidats' => Candidat::latest()->take(5)->with(['user', 'ville'])->get(),
            'dernieres_missions' => Mission::latest()->take(5)->with(['candidat.user', 'besoin.client'])->get(),
        ];
    }
}
