<?php
// ============================================
// SEN RDV SANTÉ+ — Statistiques globales
// GET /api/admin/stats.php
// GET /api/admin/stats.php?debut=2026-01-01&fin=2026-03-21
// GET /api/admin/stats.php?type=revenus&debut=...&fin=...
// GET /api/admin/stats.php?hopital_id=1&type=public
// ============================================

require_once '../config/helpers.php';
require_once '../config/database.php';

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    repondre(['erreur' => 'Méthode non autorisée'], 405);
}

$userConnecte = verifierToken();
if (!in_array($userConnecte['role'], ['super_admin', 'admin_hopital'])) {
    repondre(['erreur' => 'Accès non autorisé'], 403);
}

$db = getDB();

// ── filtres ──
$debut     = $_GET['debut']     ?? date('Y-m-01');
$fin       = $_GET['fin']       ?? date('Y-m-d');
$hopitalId = $_GET['hopital_id'] ?? null;
$typeHop   = $_GET['type']      ?? null;
$modeType  = $_GET['type'] === 'revenus' ? 'revenus' : 'stats';

// si admin_hopital → limité à son hôpital
if ($userConnecte['role'] === 'admin_hopital') {
    $hopitalId = $userConnecte['hopital_id'];
}

// ── filtre hôpital pour les jointures ──
$filtreHopital = "";
$paramsHopital = [];
if ($hopitalId) {
    $filtreHopital = "AND h.id = ?";
    $paramsHopital[] = $hopitalId;
}
$filtreType = "";
if ($typeHop && $typeHop !== 'revenus') {
    $filtreType = "AND h.type = ?";
    $paramsHopital[] = $typeHop;
}

// ── nombre de patients ──
$stmt = $db->query("SELECT COUNT(*) AS total FROM utilisateurs WHERE role = 'patient' AND actif = 1");
$nbPatients = $stmt->fetch(PDO::FETCH_ASSOC)['total'];

// ── RDVs sur la période ──
$stmt = $db->prepare("
    SELECT COUNT(*) AS total FROM rendez_vous r
    JOIN services s ON s.id = r.service_id
    JOIN hopitaux h ON h.id = s.hopital_id
    WHERE DATE(r.created_at) BETWEEN ? AND ?
    $filtreHopital $filtreType
");
$stmt->execute(array_merge([$debut, $fin], $paramsHopital));
$rdvsTotal = $stmt->fetch(PDO::FETCH_ASSOC)['total'];

// ── RDVs ce mois (pour la vue nationale) ──
$stmt = $db->prepare("
    SELECT COUNT(*) AS total FROM rendez_vous r
    JOIN services s ON s.id = r.service_id
    JOIN hopitaux h ON h.id = s.hopital_id
    WHERE MONTH(r.created_at) = MONTH(NOW()) AND YEAR(r.created_at) = YEAR(NOW())
    $filtreHopital $filtreType
");
$stmt->execute($paramsHopital);
$rdvsMois = $stmt->fetch(PDO::FETCH_ASSOC)['total'];

// ── tickets payés ──
$stmt = $db->prepare("
    SELECT COUNT(*) AS total FROM rendez_vous r
    JOIN services s ON s.id = r.service_id
    JOIN hopitaux h ON h.id = s.hopital_id
    WHERE r.statut IN ('paye','consomme')
    AND DATE(r.created_at) BETWEEN ? AND ?
    $filtreHopital $filtreType
");
$stmt->execute(array_merge([$debut, $fin], $paramsHopital));
$ticketsPayes = $stmt->fetch(PDO::FETCH_ASSOC)['total'];

// ── revenus sur la période (nb paiements × prix réservation) ──
$prixReservation = (float) getParametre('prix_reservation', 200);
$stmt = $db->prepare("
    SELECT COUNT(*) AS nb, COALESCE(SUM(p.montant), 0) AS total
    FROM paiements p
    JOIN rendez_vous r ON r.id = p.rdv_id
    JOIN services s ON s.id = r.service_id
    JOIN hopitaux h ON h.id = s.hopital_id
    WHERE p.statut = 'valide'
    AND p.paye_at BETWEEN ? AND ?
    $filtreHopital $filtreType
");
$stmt->execute(array_merge([$debut . ' 00:00:00', $fin . ' 23:59:59'], $paramsHopital));
$revenus = $stmt->fetch(PDO::FETCH_ASSOC);
$revenusTotal  = (float) $revenus['total'];
$nbPaiements   = (int)   $revenus['nb'];

// ── revenus ce mois (pour vue nationale) ──
$stmt = $db->prepare("
    SELECT COALESCE(SUM(p.montant), 0) AS total
    FROM paiements p
    JOIN rendez_vous r ON r.id = p.rdv_id
    JOIN services s ON s.id = r.service_id
    JOIN hopitaux h ON h.id = s.hopital_id
    WHERE p.statut = 'valide'
    AND MONTH(p.paye_at) = MONTH(NOW()) AND YEAR(p.paye_at) = YEAR(NOW())
    $filtreHopital $filtreType
");
$stmt->execute($paramsHopital);
$revenusMois = (float) $stmt->fetch(PDO::FETCH_ASSOC)['total'];

// ── taux absentéisme ──
$stmt = $db->prepare("
    SELECT
        COUNT(CASE WHEN r.statut = 'non_honore' THEN 1 END) AS non_honores,
        COUNT(CASE WHEN r.statut IN ('paye','consomme','non_honore') THEN 1 END) AS total_payes
    FROM rendez_vous r
    JOIN services s ON s.id = r.service_id
    JOIN hopitaux h ON h.id = s.hopital_id
    WHERE DATE(r.created_at) BETWEEN ? AND ?
    $filtreHopital $filtreType
");
$stmt->execute(array_merge([$debut, $fin], $paramsHopital));
$abs = $stmt->fetch(PDO::FETCH_ASSOC);
$tauxAbsenteisme = $abs['total_payes'] > 0
    ? round(($abs['non_honores'] / $abs['total_payes']) * 100) : 0;

// ── taux paiement ──
$tauxPaiement = $rdvsTotal > 0
    ? round(($ticketsPayes / $rdvsTotal) * 100) : 0;

// ── top 5 spécialités ──
$stmt = $db->prepare("
    SELECT s.nom, COUNT(r.id) AS count
    FROM rendez_vous r
    JOIN services s ON s.id = r.service_id
    JOIN hopitaux h ON h.id = s.hopital_id
    WHERE DATE(r.created_at) BETWEEN ? AND ?
    $filtreHopital $filtreType
    GROUP BY s.id, s.nom
    ORDER BY count DESC
    LIMIT 5
");
$stmt->execute(array_merge([$debut, $fin], $paramsHopital));
$topSpecialites = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ── détail par hôpital ──
$stmt = $db->prepare("
    SELECT h.id, h.nom, h.type,
        COUNT(DISTINCT r.id)                                         AS total,
        COUNT(DISTINCT CASE WHEN r.statut = 'confirme' THEN r.id END)           AS confirmes,
        COUNT(DISTINCT CASE WHEN r.statut IN ('paye','consomme') THEN r.id END) AS payes,
        COUNT(DISTINCT CASE WHEN r.statut = 'annule' THEN r.id END)             AS annules,
        COUNT(DISTINCT CASE WHEN p.statut = 'valide' THEN p.id END)             AS nb_paiements,
        COALESCE(SUM(CASE WHEN p.statut = 'valide' THEN p.montant END), 0)      AS montant_total
    FROM hopitaux h
    LEFT JOIN services s ON s.hopital_id = h.id
    LEFT JOIN rendez_vous r ON r.service_id = s.id AND DATE(r.created_at) BETWEEN ? AND ?
    LEFT JOIN paiements p ON p.rdv_id = r.id
    WHERE h.actif = 1
    $filtreHopital $filtreType
    GROUP BY h.id
    ORDER BY total DESC
");
$stmt->execute(array_merge([$debut, $fin], $paramsHopital));
$parHopital = $stmt->fetchAll(PDO::FETCH_ASSOC);

repondre([
    'succes'      => true,
    'stats'       => [
        'patients'          => (int) $nbPatients,
        'rdvs_total'        => (int) $rdvsTotal,
        'rdvs_mois'         => (int) $rdvsMois,
        'tickets_payes'     => (int) $ticketsPayes,
        'revenus_total'     => $revenusTotal,
        'revenus_mois'      => $revenusMois,
        'nb_paiements'      => $nbPaiements,
        'taux_absenteisme'  => $tauxAbsenteisme,
        'taux_paiement'     => $tauxPaiement,
        'temps_attente_moyen' => 15, // à calculer dynamiquement plus tard
        'top_specialites'   => $topSpecialites,
    ],
    'par_hopital' => $parHopital,
]);