<?php
/**
 * API pour les données du Tableau de Bord
 * À installer sur le serveur cPanel dans le dossier api/apiggr/
 */

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit;
}

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

$action = $_REQUEST['action'] ?? '';

try {
    $db = Database::getInstance();

    switch ($action) {
        case 'get_dashboard_stats':
            $exerciseYear = isset($_REQUEST['exercise']) ? (int)$_REQUEST['exercise'] : date('Y');
            $month = isset($_REQUEST['month']) ? (int)$_REQUEST['month'] : date('n');

            $exercise = $db->selectOne("SELECT id FROM exercices WHERE annee = ?", [$exerciseYear]);

            if (!$exercise) {
                echo json_encode(['success' => false, 'message' => 'Exercice non trouvé']);
                exit;
            }
            $exerciseId = $exercise['id'];

            $stats = [];
            $stats['total_clients'] = $db->selectOne("SELECT COUNT(*) as total FROM clients WHERE YEAR(created_at) = ?", [$exerciseYear])['total'];
            $stats['total_factures'] = $db->selectOne("SELECT COUNT(*) as total FROM factures WHERE YEAR(date_facture) = ?", [$exerciseYear])['total'];
            $stats['factures_payees'] = $db->selectOne("SELECT COUNT(*) as total FROM factures WHERE YEAR(date_facture) = ? AND statut = 'payee'", [$exerciseYear])['total'];
            $stats['factures_en_attente'] = $db->selectOne("SELECT COUNT(*) as total FROM factures WHERE YEAR(date_facture) = ? AND statut IN ('validee', 'brouillon')", [$exerciseYear])['total'];
            $stats['chiffre_affaires'] = $db->selectOne("SELECT COALESCE(SUM(montant_ttc), 0) as total FROM factures WHERE YEAR(date_facture) = ? AND statut = 'payee'", [$exerciseYear])['total'];
            $stats['ca_mensuel'] = $db->selectOne("SELECT COALESCE(SUM(montant_ttc), 0) as total FROM factures WHERE YEAR(date_facture) = ? AND MONTH(date_facture) = ? AND statut = 'payee'", [$exerciseYear, $month])['total'];

            $stats['ventes_data'] = $db->select(
                "SELECT v.type_prod, v.site, SUM(v.total_ttc) AS total
                 FROM ventes v
                 WHERE v.exercice_id = ? AND MONTH(v.date_fact) = ?
                 GROUP BY v.type_prod, v.site
                 ORDER BY v.type_prod, v.site",
                 [$exerciseId, $month]
            );

            echo json_encode(['success' => true, 'data' => $stats]);
            break;

        case 'get_recent_activities':
            $activities = [];

            $activities['factures'] = $db->select("SELECT id, numero_facture, date_facture, montant_ttc, statut, client_id FROM factures ORDER BY date_facture DESC LIMIT 5");

            foreach ($activities['factures'] as &$facture) {
                $client = $db->selectOne("SELECT nom, prenom FROM clients WHERE id = ?", [$facture['client_id']]);
                $facture['nom'] = $client ? $client['nom'] : 'Inconnu';
                $facture['prenom'] = $client ? $client['prenom'] : '';
            }

            $activities['paiements'] = $db->select("SELECT p.*, f.numero_facture, c.nom, c.prenom FROM paiements p JOIN factures f ON p.facture_id = f.id JOIN clients c ON f.client_id = c.id ORDER BY p.date_paiement DESC LIMIT 5");
            $activities['clients'] = $db->select("SELECT id, code_client, nom, prenom, created_at FROM clients ORDER BY created_at DESC LIMIT 5");

            echo json_encode(['success' => true, 'data' => $activities]);
            break;

        case 'get_exercises':
            $exercises = $db->select("SELECT * FROM exercices ORDER BY annee DESC");
            echo json_encode(['success' => true, 'data' => $exercises]);
            break;
            
        case 'get_exercise_by_year':
            $year = isset($_REQUEST['year']) ? (int)$_REQUEST['year'] : date('Y');
            $exercise = $db->selectOne("SELECT * FROM exercices WHERE annee = ?", [$year]);
            echo json_encode(['success' => true, 'data' => $exercise]);
            break;

        case 'get_sites':
            $sites = $db->select('SELECT SiteID, Nom_Site FROM Sites WHERE SiteID != "SG" ORDER BY SiteID');
            echo json_encode(['success' => true, 'data' => $sites]);
            break;

        default:
            echo json_encode(['success' => false, 'message' => 'Action inconnue']);
            break;
    }

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Erreur: ' . $e->getMessage()]);
}
