$cid, 'nom' => '', 'quantites' => 0, 'ca' => 0]; foreach ($clients as $c) { if ((int) $c['id'] === $cid) { $byClient[$cid]['nom'] = $c['nom']; break; } } } $byClient[$cid]['quantites'] += (float) ($f['quantites'] ?? 0); $byClient[$cid]['ca'] += (float) $f['montant_ht']; } $rows = array_values($byClient); usort($rows, fn($a, $b) => $b['ca'] <=> $a['ca']); $totalQte = array_sum(array_column($rows, 'quantites')); $totalCa = array_sum(array_column($rows, 'ca')); foreach ($rows as &$r) { $r['pct_qte'] = $totalQte > 0 ? round(100 * $r['quantites'] / $totalQte, 1) : 0; $r['pct_ca'] = $totalCa > 0 ? round(100 * $r['ca'] / $totalCa, 1) : 0; } sendJson([ 'type' => $type, 'cycle' => $cycle, 'top_clients' => $rows, 'total_quantites' => $totalQte, 'total_ca' => $totalCa, ]); exit; } $pdo = getPdo(); $sql = " SELECT c.id AS client_id, c.nom, SUM(COALESCE(f.quantites, 0)) AS quantites, SUM(f.montant_ht) AS ca FROM clients c JOIN factures f ON f.client_id = c.id WHERE LOWER(TRIM(f.type_produit)) = ? "; $params = [$type]; if ($cycle !== null && $cycle !== '') { $sql .= " AND TRIM(f.cycle) = ?"; $params[] = $cycle; } $sql .= " GROUP BY c.id, c.nom ORDER BY ca DESC"; $stmt = $pdo->prepare($sql); $stmt->execute($params); $rows = $stmt->fetchAll(); $totalQte = array_sum(array_column($rows, 'quantites')); $totalCa = array_sum(array_column($rows, 'ca')); foreach ($rows as &$r) { $r['quantites'] = (float) $r['quantites']; $r['ca'] = (float) $r['ca']; $r['pct_qte'] = $totalQte > 0 ? round(100 * $r['quantites'] / $totalQte, 1) : 0; $r['pct_ca'] = $totalCa > 0 ? round(100 * $r['ca'] / $totalCa, 1) : 0; } sendJson([ 'type' => $type, 'cycle' => $cycle, 'top_clients' => $rows, 'total_quantites' => $totalQte, 'total_ca' => $totalCa, ]);