<?php
declare(strict_types=1);

namespace Infolab\Controllers;

use Infolab\Database;
use Infolab\Request;
use Infolab\Response;

/**
 * GET /api/stats — KPIs du dashboard.
 *
 *  - projects_{active,completed,archived,total} : projets non soft-deletés
 *  - participants_total : total des membres de l'annuaire
 *    (interprétation : "annuaire des contributeurs" = participants potentiels)
 *  - by_category : un objet { slug, name, color_hex, count } par catégorie
 *  - by_dimension : { social, ecologique, transversal } sommés sur projets non-deleted
 */
final class StatsController
{
    public function index(Request $req, array $params): void
    {
        // Compteurs par status (projets non soft-deletés).
        $statusCounts = Database::fetchAll(
            'SELECT status, COUNT(*) AS c FROM projects WHERE deleted_at IS NULL GROUP BY status',
        );
        $byStatus = ['active' => 0, 'completed' => 0, 'archived' => 0];
        foreach ($statusCounts as $r) {
            $byStatus[$r['status']] = (int) $r['c'];
        }

        $participantsTotal = (int) Database::fetchValue('SELECT COUNT(*) FROM members');

        // Compteur par catégorie : LEFT JOIN pour inclure les catégories à 0 projet.
        $byCategoryRows = Database::fetchAll(
            'SELECT c.slug, c.name, c.color_hex, c.dimension,
                    COALESCE(SUM(CASE WHEN p.deleted_at IS NULL THEN 1 ELSE 0 END), 0) AS count
             FROM categories c
             LEFT JOIN projects p ON p.category_id = c.id
             GROUP BY c.id, c.slug, c.name, c.color_hex, c.dimension
             ORDER BY c.sort_order ASC',
        );

        $byDimension = ['social' => 0, 'ecologique' => 0, 'transversal' => 0];
        $byCategory  = [];
        foreach ($byCategoryRows as $r) {
            $count = (int) $r['count'];
            $byCategory[] = [
                'slug'      => $r['slug'],
                'name'      => $r['name'],
                'color_hex' => $r['color_hex'],
                'count'     => $count,
            ];
            $byDimension[$r['dimension']] = ($byDimension[$r['dimension']] ?? 0) + $count;
        }

        Response::json([
            'projects_active'    => $byStatus['active'],
            'projects_completed' => $byStatus['completed'],
            'projects_archived'  => $byStatus['archived'],
            'projects_total'     => $byStatus['active'] + $byStatus['completed'] + $byStatus['archived'],
            'participants_total' => $participantsTotal,
            'by_category'        => $byCategory,
            'by_dimension'       => $byDimension,
        ]);
    }
}
