<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
header("Content-Type: application/json; charset=utf-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
if ($_SERVER["REQUEST_METHOD"] === "OPTIONS") {
    http_response_code(200);
    exit;
}
require_once __DIR__ . '/../config/database.php';
class MemberDashboardController {
    private $db;
    
    const COTIS_MENSUELLES = 1;
    const AUTRES_COTIS     = 2;
    const DONS             = 3;
    const FONDS_SOCIAL     = 4;
    const ACTIVITES        = 5;
    public function __construct() {
        try {
            $this->db = (new Database())->getConnection();
        } catch (Exception $e) {
            $this->sendError(500, "Erreur de connexion: " . $e->getMessage());
        }
    }
    private function sendError($code, $message) {
        http_response_code($code);
        echo json_encode(["success" => false, "message" => $message]);
        exit();
    }
    private function getTotalByCategorie($catId, $membreId = null) {
        try {
            // AJOUT: type = 'regularisation' pour inclure les cotisations non comptabilisées
            $sql = "SELECT COALESCE(SUM(montant), 0) AS total
                    FROM operations 
                    WHERE (type = 'recette' OR type = 'entree' OR type = '' OR type = 'regularisation') 
                    AND categorie_id = :cat_id";
            
            $params = ['cat_id' => $catId];
            if ($membreId !== null) {
                $sql .= " AND membre_id = :membre_id";
                $params['membre_id'] = $membreId;
            }
            
            $stmt = $this->db->prepare($sql);
            $stmt->execute($params);
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            return (float) ($result['total'] ?? 0);
        } catch (Exception $e) {
            error_log("Erreur getTotalByCategorie: " . $e->getMessage());
            return 0;
        }
    }
    private function getDetailsByCategorie($catId, $membreId = null, $limit = 100) {
        try {
            // AJOUT: type = 'regularisation'
            $sql = "SELECT o.id, o.membre_id, o.montant, o.date_operation, o.description, o.mois_cible, o.type,
                           m.nom as membre_nom, m.prenom as membre_prenom,
                           c.nom as categorie_nom
                    FROM operations o
                    LEFT JOIN membres m ON o.membre_id = m.id
                    LEFT JOIN categories c ON o.categorie_id = c.id
                    WHERE (o.type = 'recette' OR o.type = 'entree' OR o.type = '' OR o.type = 'regularisation')
                    AND o.categorie_id = :cat_id";
            
            $params = ['cat_id' => $catId];
            
            if ($membreId !== null) {
                $sql .= " AND o.membre_id = :membre_id";
                $params['membre_id'] = $membreId;
            }
            
            if ($catId == self::COTIS_MENSUELLES) {
                $sql .= " ORDER BY o.mois_cible ASC, o.date_operation DESC";
            } else {
                $sql .= " ORDER BY o.date_operation DESC";
            }
            
            $sql .= " LIMIT :limit";
            
            $stmt = $this->db->prepare($sql);
            $stmt->bindValue(':cat_id', $catId, PDO::PARAM_INT);
            if ($membreId !== null) {
                $stmt->bindValue(':membre_id', $membreId, PDO::PARAM_INT);
            }
            $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
            
            $stmt->execute();
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (Exception $e) {
            error_log("Erreur getDetailsByCategorie: " . $e->getMessage());
            return [];
        }
    }
    private function getTotalAutres($membreId = null) {
        try {
            // AJOUT: type = 'regularisation'
            $sql = "SELECT COALESCE(SUM(montant), 0) AS total
                    FROM operations 
                    WHERE (type = 'recette' OR type = 'entree' OR type = '' OR type = 'regularisation')
                    AND categorie_id IN (:cat1, :cat2, :cat3)";
            
            $params = ['cat1' => self::AUTRES_COTIS, 'cat2' => self::FONDS_SOCIAL, 'cat3' => self::ACTIVITES];
            
            if ($membreId !== null) {
                $sql .= " AND membre_id = :membre_id";
                $params['membre_id'] = $membreId;
            }
            
            $stmt = $this->db->prepare($sql);
            $stmt->execute($params);
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            return (float) ($result['total'] ?? 0);
        } catch (Exception $e) {
            error_log("Erreur getTotalAutres: " . $e->getMessage());
            return 0;
        }
    }
    private function getDetailsAutres($membreId = null, $limit = 100) {
        try {
            // AJOUT: type = 'regularisation'
            $sql = "SELECT o.id, o.membre_id, o.montant, o.date_operation, o.description, o.mois_cible, o.categorie_id,
                           m.nom as membre_nom, m.prenom as membre_prenom,
                           c.nom as categorie_nom
                    FROM operations o
                    LEFT JOIN membres m ON o.membre_id = m.id
                    LEFT JOIN categories c ON o.categorie_id = c.id
                    WHERE (o.type = 'recette' OR o.type = 'entree' OR o.type = '' OR o.type = 'regularisation')
                    AND o.categorie_id IN (:cat1, :cat2, :cat3)";
            
            $params = ['cat1' => self::AUTRES_COTIS, 'cat2' => self::FONDS_SOCIAL, 'cat3' => self::ACTIVITES];
            
            if ($membreId !== null) {
                $sql .= " AND o.membre_id = :membre_id";
                $params['membre_id'] = $membreId;
            }
            
            $sql .= " ORDER BY o.date_operation DESC LIMIT :limit";
            
            $stmt = $this->db->prepare($sql);
            foreach ($params as $key => $value) {
                $stmt->bindValue(":$key", $value, PDO::PARAM_INT);
            }
            if ($membreId !== null) {
                $stmt->bindValue(':membre_id', $membreId, PDO::PARAM_INT);
            }
            $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
            
            $stmt->execute();
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (Exception $e) {
            error_log("Erreur getDetailsAutres: " . $e->getMessage());
            return [];
        }
    }
    private function getTotalDons($membreId = null) {
        return $this->getTotalByCategorie(self::DONS, $membreId);
    }
    private function getDetailsDons($membreId = null, $limit = 20) {
        return $this->getDetailsByCategorie(self::DONS, $membreId, $limit);
    }
    private function getEvents() {
        try {
            $stmt = $this->db->prepare("SELECT id, titre, date_evenement
                                        FROM evenements 
                                        WHERE date_evenement >= CURDATE()
                                        ORDER BY date_evenement ASC 
                                        LIMIT 5");
            $stmt->execute();
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (Exception $e) {
            error_log("Erreur getEvents: " . $e->getMessage());
            return [];
        }
    }
    private function getArriereStatsByMembre($membreId) {
        try {
            $stmt = $this->db->prepare("SELECT COUNT(*) AS total_arrieres,
                                               COALESCE(SUM(montant_du), 0) AS montant_du,
                                               COALESCE(SUM(montant_paye), 0) AS montant_paye
                                        FROM historiques_arriere 
                                        WHERE membre_id = :membre_id");
            $stmt->bindValue(':membre_id', $membreId, PDO::PARAM_INT);
            $stmt->execute();
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            
            return [
                "total_arrieres" => (int) ($result["total_arrieres"] ?? 0),
                "montant_du"     => (float) ($result["montant_du"] ?? 0),
                "montant_paye"   => (float) ($result["montant_paye"] ?? 0)
            ];
        } catch (Exception $e) {
            error_log("Erreur getArriereStatsByMembre: " . $e->getMessage());
            return ["total_arrieres" => 0, "montant_du" => 0, "montant_paye" => 0];
        }
    }
    private function getArrieresCount() {
        try {
            $stmt = $this->db->prepare("SELECT COUNT(*) AS total FROM membres WHERE statut_arriere = 'en_arriere'");
            $stmt->execute();
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            return (int) ($result['total'] ?? 0);
        } catch (Exception $e) {
            error_log("Erreur getArrieresCount: " . $e->getMessage());
            return 0;
        }
    }
    private function getArriereStats() {
        try {
            $stmt = $this->db->prepare("SELECT COUNT(*) AS total_arrieres,
                                               COALESCE(SUM(montant_du), 0) AS montant_du,
                                               COALESCE(SUM(montant_paye), 0) AS montant_paye
                                        FROM historiques_arriere");
            $stmt->execute();
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            
            return [
                "total_arrieres" => (int) ($result["total_arrieres"] ?? 0),
                "montant_du"     => (float) ($result["montant_du"] ?? 0),
                "montant_paye"   => (float) ($result["montant_paye"] ?? 0)
            ];
        } catch (Exception $e) {
            error_log("Erreur getArriereStats: " . $e->getMessage());
            return ["total_arrieres" => 0, "montant_du" => 0, "montant_paye" => 0];
        }
    }
    private function getNotifications($membreId) {
        try {
            $stmt = $this->db->prepare("SELECT id, type, titre, message, lien, est_lu, date_envoi, date_lecture
                                        FROM notifications 
                                        WHERE membre_id = :membre_id
                                        ORDER BY date_envoi DESC 
                                        LIMIT 10");
            $stmt->bindValue(':membre_id', $membreId, PDO::PARAM_INT);
            $stmt->execute();
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (Exception $e) {
            error_log("Erreur getNotifications: " . $e->getMessage());
            return [];
        }
    }
    public function stats($role, $membreId = null) {
        while (ob_get_level()) {
            ob_end_clean();
        }
        try {
            $response = ["success" => true];
            $events = $this->getEvents();
            if ($role === "admin") {
                $response = array_merge($response, [
                    "tot_mensuelles"     => $this->getTotalByCategorie(self::COTIS_MENSUELLES),
                    "details_mensuelles" => $this->getDetailsByCategorie(self::COTIS_MENSUELLES),
                    "tot_autres"         => $this->getTotalAutres(),
                    "details_autres"     => $this->getDetailsAutres(),
                    "tot_dons"           => $this->getTotalDons(),
                    "details_dons"       => $this->getDetailsDons(),
                    "arrieres"           => $this->getArrieresCount(),
                    "arriere_stats"      => $this->getArriereStats(),
                    "events"             => $events
                ]);
            } else {
                if ($membreId === null) {
                    $this->sendError(400, "Paramètre membre_id requis");
                }
                $arriereStats = $this->getArriereStatsByMembre($membreId);
                $totalMensuelles = $this->getTotalByCategorie(self::COTIS_MENSUELLES, $membreId);
                $totalAutres = $this->getTotalAutres($membreId);
                $totalDons = $this->getTotalDons($membreId);
                $mesCotisations = $totalMensuelles + $totalAutres;
                $detailsMensuelles = $this->getDetailsByCategorie(self::COTIS_MENSUELLES, $membreId);
                $response = array_merge($response, [
                    "mes_cotisations"    => $mesCotisations,
                    "tot_mensuelles"     => $totalMensuelles,
                    "details_mensuelles" => $detailsMensuelles,
                    "tot_autres"         => $totalAutres,
                    "details_autres"     => $this->getDetailsAutres($membreId),
                    "tot_dons"           => $totalDons,
                    "details_dons"       => $this->getDetailsDons($membreId),
                    "arrieres"           => $arriereStats["total_arrieres"],
                    "arriere_stats"      => $arriereStats,
                    "events"             => $events,
                    "notifications"      => $this->getNotifications($membreId)
                ]);
            }
            echo json_encode($response, JSON_UNESCAPED_UNICODE);
        } catch (Exception $e) {
            error_log("Erreur stats: " . $e->getMessage());
            $this->sendError(500, "Erreur serveur");
        }
    }
    public function all() {
        while (ob_get_level()) {
            ob_end_clean();
        }
        try {
            $stmt = $this->db->prepare("
                SELECT o.id, o.membre_id, o.categorie_id, o.montant, o.type, 
                       o.date_operation, o.mois_cible, o.description, o.created_at,
                       m.nom as membre_nom, m.prenom as membre_prenom,
                       c.nom as categorie_nom, c.type as categorie_type
                FROM operations o
                LEFT JOIN membres m ON o.membre_id = m.id
                LEFT JOIN categories c ON o.categorie_id = c.id
                ORDER BY o.date_operation DESC, o.created_at DESC
            ");
            $stmt->execute();
            $operations = $stmt->fetchAll(PDO::FETCH_ASSOC);
            $stats = [
                "total_operations" => count($operations),
                "total_recettes" => 0,
                "total_depenses" => 0,
                "par_categorie" => []
            ];
            foreach ($operations as $op) {
                // AJOUT: 'regularisation' n'est PAS compté dans total_recettes
                if (in_array($op['type'], ['recette', 'entree', ''])) {
                    $stats["total_recettes"] += (float) $op['montant'];
                } else if ($op['type'] === 'sortie') {
                    $stats["total_depenses"] += (float) $op['montant'];
                }
                // Note: 'regularisation' est ignoré ici pour les totaux financiers
                $categorie = $op['categorie_nom'] ?? 'Non catégorisé';
                if (!isset($stats["par_categorie"][$categorie])) {
                    $stats["par_categorie"][$categorie] = 0;
                }
                $stats["par_categorie"][$categorie] += (float) $op['montant'];
            }
            echo json_encode([
                "success" => true,
                "data" => [
                    "operations" => $operations,
                    "statistiques" => $stats,
                    "total" => count($operations)
                ]
            ], JSON_UNESCAPED_UNICODE);
        } catch (Exception $e) {
            error_log("Erreur all: " . $e->getMessage());
            $this->sendError(500, "Erreur serveur");
        }
    }
}
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}
try {
    $action = $_GET["action"] ?? null;
    $role = $_GET["role"] ?? "membre";
    $membreId = isset($_GET["membre_id"]) ? intval($_GET["membre_id"]) : null;
    $controller = new MemberDashboardController();
    switch ($action) {
        case "stats":
            $controller->stats($role, $membreId);
            break;
        case "all":
            $controller->all();
            break;
        default:
            http_response_code(400);
            echo json_encode([
                "success" => false, 
                "message" => "Action non reconnue"
            ]);
            break;
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        "success" => false,
        "message" => "Erreur serveur"
    ]);
}