$cid, 'nom' => '', 'qte_facturee' => 0, 'qte_livree' => 0]; foreach ($clients as $c) { if ((int) $c['id'] === $cid) { $byClient[$cid]['nom'] = $c['nom']; break; } } } $byClient[$cid]['qte_facturee'] += (float) ($f['quantites'] ?? 0); $byClient[$cid]['qte_livree'] += (float) ($f['qte_livree'] ?? 0); } $rows = array_values($byClient); usort($rows, fn($a, $b) => $b['qte_facturee'] <=> $a['qte_facturee']); sendJson([ 'type_filter' => $type, 'quantites_par_client' => $rows, ]); exit; } $pdo = getPdo(); $params = []; if ($type !== null && $type !== '') { $sql = " SELECT c.id AS client_id, c.nom, SUM(COALESCE(f.quantites, 0)) AS qte_facturee, SUM(COALESCE(f.qte_livree, 0)) AS qte_livree FROM clients c INNER JOIN factures f ON f.client_id = c.id AND LOWER(TRIM(f.type_produit)) = ? GROUP BY c.id, c.nom HAVING qte_facturee > 0 ORDER BY qte_facturee DESC "; $params = [$type]; } else { $sql = " SELECT c.id AS client_id, c.nom, SUM(COALESCE(f.quantites, 0)) AS qte_facturee, SUM(COALESCE(f.qte_livree, 0)) AS qte_livree FROM clients c LEFT JOIN factures f ON f.client_id = c.id GROUP BY c.id, c.nom HAVING qte_facturee > 0 ORDER BY qte_facturee DESC "; $params = []; } $stmt = $pdo->prepare($sql); $stmt->execute($params); $rows = $stmt->fetchAll(); foreach ($rows as &$r) { $r['qte_facturee'] = (float) $r['qte_facturee']; $r['qte_livree'] = (float) $r['qte_livree']; } sendJson([ 'type_filter' => $type, 'quantites_par_client' => $rows, ]);