<?php
// combo_data.php - API pour récupérer les données des combobox
require_once 'config.php';

Utils::setCorsHeaders();

class ComboDataService {
    
    private $pdo;
    
    public function __construct() {
        $this->pdo = DatabaseConfig::getConnection();
    }
    
    /**
     * Récupérer toutes les données pour les combobox
     */
    public function getAllComboData() {
        try {
            $data = [];
            
            // Clients
            $stmt = $this->pdo->query("
                SELECT DISTINCT NomClient as value, NomClient as label 
                FROM pesee 
                WHERE NomClient IS NOT NULL AND NomClient != '' 
                ORDER BY NomClient
            ");
            $data['clients'] = $stmt->fetchAll();
            
            // Fournisseurs
            $stmt = $this->pdo->query("
                SELECT DISTINCT NomFournisseur as value, NomFournisseur as label 
                FROM pesee 
                WHERE NomFournisseur IS NOT NULL AND NomFournisseur != '' 
                ORDER BY NomFournisseur
            ");
            $data['fournisseurs'] = $stmt->fetchAll();
            
            // Produits
            $stmt = $this->pdo->query("
                SELECT DISTINCT NomProduit as value, NomProduit as label 
                FROM pesee 
                WHERE NomProduit IS NOT NULL AND NomProduit != '' 
                ORDER BY NomProduit
            ");
            $data['produits'] = $stmt->fetchAll();
            
            // Sites
            $stmt = $this->pdo->query("
                SELECT DISTINCT CodeSite as value, CONCAT(CodeSite, ' - ', NomSite) as label 
                FROM pesee 
                WHERE CodeSite IS NOT NULL AND CodeSite != '' 
                ORDER BY CodeSite
            ");
            $data['sites'] = $stmt->fetchAll();
            
            // Provenance
            $stmt = $this->pdo->query("
                SELECT DISTINCT Provenance as value, Provenance as label 
                FROM pesee 
                WHERE Provenance IS NOT NULL AND Provenance != '' 
                ORDER BY Provenance
            ");
            $data['provenances'] = $stmt->fetchAll();
            
            // Destinations
            $stmt = $this->pdo->query("
                SELECT DISTINCT Destination as value, Destination as label 
                FROM pesee 
                WHERE Destination IS NOT NULL AND Destination != '' 
                ORDER BY Destination
            ");
            $data['destinations'] = $stmt->fetchAll();
            
            // Codes Pesée (derniers 50)
            $stmt = $this->pdo->query("
                SELECT DISTINCT CodePesee as value, CodePesee as label 
                FROM pesee 
                WHERE CodePesee IS NOT NULL AND CodePesee != '' 
                ORDER BY CodePesee DESC 
                LIMIT 50
            ");
            $data['codesPesee'] = $stmt->fetchAll();
            
            // Numéros de Ticket (derniers 50)
            $stmt = $this->pdo->query("
                SELECT DISTINCT NumTicket as value, NumTicket as label 
                FROM pesee 
                WHERE NumTicket IS NOT NULL AND NumTicket != '' 
                ORDER BY NumTicket DESC 
                LIMIT 50
            ");
            $data['tickets'] = $stmt->fetchAll();
            
            // Campagnes
            $stmt = $this->pdo->query("
                SELECT DISTINCT Campagne as value, Campagne as label 
                FROM pesee 
                WHERE Campagne IS NOT NULL AND Campagne != '' 
                ORDER BY Campagne DESC
            ");
            $data['campagnes'] = $stmt->fetchAll();
            
            // Mouvements
            $stmt = $this->pdo->query("
                SELECT DISTINCT Mouvement as value, Mouvement as label 
                FROM pesee 
                WHERE Mouvement IS NOT NULL AND Mouvement != '' 
                ORDER BY Mouvement
            ");
            $data['mouvements'] = $stmt->fetchAll();
            
            // Peseurs
            $stmt = $this->pdo->query("
                SELECT DISTINCT NomPeseur1 as value, NomPeseur1 as label 
                FROM pesee 
                WHERE NomPeseur1 IS NOT NULL AND NomPeseur1 != '' 
                ORDER BY NomPeseur1
            ");
            $data['peseurs'] = $stmt->fetchAll();
            
            // Transporteurs
            $stmt = $this->pdo->query("
                SELECT DISTINCT NomTransporteur as value, NomTransporteur as label 
                FROM pesee 
                WHERE NomTransporteur IS NOT NULL AND NomTransporteur != '' 
                ORDER BY NomTransporteur
            ");
            $data['transporteurs'] = $stmt->fetchAll();
            
            // Années disponibles (pour les filtres de dates)
            $stmt = $this->pdo->query("
                SELECT DISTINCT YEAR(dmv) as value, YEAR(dmv) as label 
                FROM pesee 
                WHERE dmv IS NOT NULL 
                ORDER BY YEAR(dmv) DESC
            ");
            $data['annees'] = $stmt->fetchAll();
            
            // Mois disponibles pour l'année courante
            $stmt = $this->pdo->query("
                SELECT DISTINCT 
                    MONTH(dmv) as value, 
                    DATE_FORMAT(dmv, '%m - %M') as label 
                FROM pesee 
                WHERE YEAR(dmv) = YEAR(CURDATE()) 
                ORDER BY MONTH(dmv) DESC
            ");
            $data['mois'] = $stmt->fetchAll();
            
            return $data;
            
        } catch (PDOException $e) {
            Utils::logError("Erreur lors de la récupération des données combo", ['error' => $e->getMessage()]);
            throw new Exception("Erreur lors de la récupération des données");
        }
    }
    
    /**
     * Récupérer les données pour une combobox spécifique
     */
    public function getComboData($type) {
        try {
            $data = [];
            
            switch ($type) {
                case 'clients':
                    $stmt = $this->pdo->query("
                        SELECT DISTINCT NomClient as value, 
                               CONCAT(NomClient, ' (', COUNT(*), ' pesées)') as label,
                               COUNT(*) as count
                        FROM pesee 
                        WHERE NomClient IS NOT NULL AND NomClient != '' 
                        GROUP BY NomClient 
                        ORDER BY COUNT(*) DESC, NomClient
                    ");
                    $data = $stmt->fetchAll();
                    break;
                    
                case 'produits':
                    $stmt = $this->pdo->query("
                        SELECT DISTINCT NomProduit as value, 
                               CONCAT(NomProduit, ' (', COUNT(*), ' pesées)') as label,
                               COUNT(*) as count
                        FROM pesee 
                        WHERE NomProduit IS NOT NULL AND NomProduit != '' 
                        GROUP BY NomProduit 
                        ORDER BY COUNT(*) DESC, NomProduit
                    ");
                    $data = $stmt->fetchAll();
                    break;
                    
                case 'fournisseurs':
                    $stmt = $this->pdo->query("
                        SELECT DISTINCT NomFournisseur as value, 
                               CONCAT(NomFournisseur, ' (', COUNT(*), ' pesées)') as label,
                               COUNT(*) as count
                        FROM pesee 
                        WHERE NomFournisseur IS NOT NULL AND NomFournisseur != '' 
                        GROUP BY NomFournisseur 
                        ORDER BY COUNT(*) DESC, NomFournisseur
                    ");
                    $data = $stmt->fetchAll();
                    break;
                    
                case 'tickets':
                    $stmt = $this->pdo->query("
                        SELECT NumTicket as value, 
                               CONCAT(NumTicket, ' - ', NomClient, ' (', DATE_FORMAT(dmv, '%d/%m/%Y'), ')') as label,
                               dmv
                        FROM pesee 
                        WHERE NumTicket IS NOT NULL AND NumTicket != '' 
                        ORDER BY dmv DESC 
                        LIMIT 100
                    ");
                    $data = $stmt->fetchAll();
                    break;
                    
                case 'periodes':
                    // Générer des périodes prédéfinies
                    $periodes = [
                        ['value' => 'aujourd_hui', 'label' => 'Aujourd\'hui'],
                        ['value' => 'cette_semaine', 'label' => 'Cette semaine'],
                        ['value' => 'ce_mois', 'label' => 'Ce mois'],
                        ['value' => 'mois_dernier', 'label' => 'Mois dernier'],
                        ['value' => 'cette_annee', 'label' => 'Cette année'],
                        ['value' => 'annee_derniere', 'label' => 'Année dernière'],
                        ['value' => 'tout', 'label' => 'Toutes les périodes']
                    ];
                    $data = $periodes;
                    break;
                    
                default:
                    throw new Exception("Type de combobox non reconnu: $type");
            }
            
            return $data;
            
        } catch (PDOException $e) {
            Utils::logError("Erreur lors de la récupération des données combo pour $type", ['error' => $e->getMessage()]);
            throw new Exception("Erreur lors de la récupération des données");
        }
    }
    
    /**
     * Obtenir des statistiques sur les données
     */
    public function getDataStats() {
        try {
            $stats = [];
            
            // Compter les éléments uniques
            $queries = [
                'total_pesees' => "SELECT COUNT(*) as count FROM pesee",
                'clients_uniques' => "SELECT COUNT(DISTINCT NomClient) as count FROM pesee WHERE NomClient IS NOT NULL AND NomClient != ''",
                'produits_uniques' => "SELECT COUNT(DISTINCT NomProduit) as count FROM pesee WHERE NomProduit IS NOT NULL AND NomProduit != ''",
                'fournisseurs_uniques' => "SELECT COUNT(DISTINCT NomFournisseur) as count FROM pesee WHERE NomFournisseur IS NOT NULL AND NomFournisseur != ''",
                'sites_uniques' => "SELECT COUNT(DISTINCT CodeSite) as count FROM pesee WHERE CodeSite IS NOT NULL AND CodeSite != ''",
                'periode_debut' => "SELECT MIN(dmv) as date FROM pesee WHERE dmv IS NOT NULL",
                'periode_fin' => "SELECT MAX(dmv) as date FROM pesee WHERE dmv IS NOT NULL"
            ];
            
            foreach ($queries as $key => $sql) {
                $stmt = $this->pdo->query($sql);
                $result = $stmt->fetch();
                $stats[$key] = $result['count'] ?? $result['date'] ?? 0;
            }
            
            return $stats;
            
        } catch (PDOException $e) {
            Utils::logError("Erreur lors du calcul des statistiques", ['error' => $e->getMessage()]);
            throw new Exception("Erreur lors du calcul des statistiques");
        }
    }
}

// Vérification de l'authentification
function verifyAuth() {
    $headers = getallheaders();
    $token = isset($headers['Authorization']) ? str_replace('Bearer ', '', $headers['Authorization']) : null;
    
    if (!$token) {
        Utils::errorResponse('Token d\'authentification requis', 401);
    }
    
    // Vérifier le token
    require_once 'auth.php';
    $authService = new AuthService();
    $user = $authService->verifyToken($token);
    
    if (!$user) {
        Utils::errorResponse('Token invalide', 401);
    }
    
    return $user;
}

// Traitement des requêtes
$user = verifyAuth();
$comboService = new ComboDataService();
$method = $_SERVER['REQUEST_METHOD'];

try {
    if ($method === 'GET') {
        $action = $_GET['action'] ?? 'all';
        
        switch ($action) {
            case 'all':
                $result = $comboService->getAllComboData();
                Utils::jsonResponse($result, true, 'Données des combobox récupérées');
                break;
                
            case 'specific':
                $type = $_GET['type'] ?? '';
                if (empty($type)) {
                    Utils::errorResponse('Type de combobox requis');
                }
                $result = $comboService->getComboData($type);
                Utils::jsonResponse($result, true, "Données pour $type récupérées");
                break;
                
            case 'stats':
                $result = $comboService->getDataStats();
                Utils::jsonResponse($result, true, 'Statistiques récupérées');
                break;
                
            default:
                Utils::errorResponse('Action non reconnue');
        }
    } else {
        Utils::errorResponse('Méthode non supportée', 405);
    }
    
} catch (Exception $e) {
    Utils::logError("Erreur dans combo_data.php", ['error' => $e->getMessage()]);
    Utils::errorResponse('Erreur: ' . $e->getMessage(), 500);
}
?>