<?php
// app/model/api/module.php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

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

require_once __DIR__ . '/../service/ModuleService.php';

$service = new ModuleService();

$action = isset($_GET['action']) ? $_GET['action'] : '';
$method = $_SERVER['REQUEST_METHOD'];

try {
    switch ($method) {
        case 'GET':
            if ($action === 'search') {
                $searchData = [
                    'id' => isset($_GET['id']) ? $_GET['id'] : '',
                    'libelle' => isset($_GET['libelle']) ? $_GET['libelle'] : '',
                    'code' => isset($_GET['code']) ? $_GET['code'] : '',
                    'description' => isset($_GET['description']) ? $_GET['description'] : '',
                    'filiere_id' => isset($_GET['filiere_id']) ? $_GET['filiere_id'] : '',
                    'semestre_id' => isset($_GET['semestre_id']) ? $_GET['semestre_id'] : '',
                    'annee_universitaire' => isset($_GET['annee_universitaire']) ? $_GET['annee_universitaire'] : ''
                ];
                $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
                $perPage = isset($_GET['per_page']) ? (int)$_GET['per_page'] : 10;

                $result = $service->search($searchData, $page, $perPage);
                echo json_encode(['success' => true, 'data' => $result]);
            } elseif ($action === 'get' && isset($_GET['id'])) {
                $data = $service->getModule($_GET['id']);
                if ($data) {
                    echo json_encode(['success' => true, 'data' => $data]);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Module non trouvé']);
                }
            } elseif ($action === 'stats') {
                $data = $service->getStats();
                echo json_encode(['success' => true, 'data' => $data]);
            } elseif ($action === 'all') {
                $data = $service->getAllModules();
                echo json_encode(['success' => true, 'data' => $data]);
            } elseif ($action === 'by_semestre' && isset($_GET['semestre_id'])) {
                $data = $service->getModulesBySemestre($_GET['semestre_id']);
                echo json_encode(['success' => true, 'data' => $data]);
            } elseif ($action === 'by_filiere' && isset($_GET['filiere_id'])) {
                $data = $service->getModulesByFiliere($_GET['filiere_id']);
                echo json_encode(['success' => true, 'data' => $data]);
            } elseif ($action === 'by_annee' && isset($_GET['annee'])) {
                $data = $service->getModulesByAnnee($_GET['annee']);
                echo json_encode(['success' => true, 'data' => $data]);
            } elseif ($action === 'by_filiere_semestre' && isset($_GET['filiere_id']) && isset($_GET['semestre_id'])) {
                $data = $service->getModulesByFiliereAndSemestre($_GET['filiere_id'], $_GET['semestre_id']);
                echo json_encode(['success' => true, 'data' => $data]);
            } elseif ($action === 'filieres') {
                $data = $service->getFilieres();
                echo json_encode(['success' => true, 'data' => $data]);
            } elseif ($action === 'annees') {
                $data = $service->getAnneesUniversitaires();
                echo json_encode(['success' => true, 'data' => $data]);
            } elseif ($action === 'total_heures' && isset($_GET['semestre_id'])) {
                $data = $service->getTotalHeuresBySemestre($_GET['semestre_id']);
                echo json_encode(['success' => true, 'data' => $data]);
            } elseif ($action === 'groupes' && isset($_GET['id'])) {
                $data = $service->getTotalGroupes($_GET['id']);
                echo json_encode(['success' => true, 'data' => $data]);
            } elseif ($action === 'export') {
                $csv = $service->exportToCsv();
                if ($csv) {
                    header('Content-Type: text/csv; charset=utf-8');
                    header('Content-Disposition: attachment; filename="modules_' . date('Y-m-d') . '.csv"');
                    echo $csv;
                    exit();
                } else {
                    echo json_encode(['success' => false, 'message' => 'Aucun module à exporter']);
                }
            } else {
                $data = $service->findAll('libelle ASC');
                echo json_encode(['success' => true, 'data' => $data]);
            }
            break;

        case 'POST':
            $input = json_decode(file_get_contents('php://input'), true);
            if ($input) {
                $id = $service->createModule($input);
                echo json_encode(['success' => true, 'id' => $id, 'message' => 'Module créé avec succès']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Données invalides']);
            }
            break;

        case 'PUT':
            if (isset($_GET['id'])) {
                $input = json_decode(file_get_contents('php://input'), true);
                if ($input) {
                    $service->updateModule($_GET['id'], $input);
                    echo json_encode(['success' => true, 'message' => 'Module mis à jour avec succès']);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Données invalides']);
                }
            } else {
                echo json_encode(['success' => false, 'message' => 'ID requis']);
            }
            break;

        case 'DELETE':
            if (isset($_GET['id'])) {
                $service->deleteModule($_GET['id']);
                echo json_encode(['success' => true, 'message' => 'Module supprimé avec succès']);
            } else {
                echo json_encode(['success' => false, 'message' => 'ID requis']);
            }
            break;

        default:
            echo json_encode(['success' => false, 'message' => 'Méthode non autorisée']);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>