<?php
// app/model/api/affectation_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/AffectationModuleService.php';

$service = new AffectationModuleService();

$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'] : '',
                    'module_id' => isset($_GET['module_id']) ? $_GET['module_id'] : '',
                    'module_libelle' => isset($_GET['module_libelle']) ? $_GET['module_libelle'] : '',
                    'filliere_id' => isset($_GET['filliere_id']) ? $_GET['filliere_id'] : '',
                    'semstre_id' => isset($_GET['semstre_id']) ? $_GET['semstre_id'] : '',
                    'employee_id' => isset($_GET['employee_id']) ? $_GET['employee_id'] : '',
                    'employee_nom' => isset($_GET['employee_nom']) ? $_GET['employee_nom'] : '',
                    '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->getAffectation($_GET['id']);
                if ($data) {
                    echo json_encode(['success' => true, 'data' => $data]);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Affectation non trouvée']);
                }
            } elseif ($action === 'stats') {
                $data = $service->getStats();
                echo json_encode(['success' => true, 'data' => $data]);
            } elseif ($action === 'by_employee' && isset($_GET['employee_id'])) {
                $annee = isset($_GET['annee']) ? $_GET['annee'] : null;
                $data = $service->getAffectationsByEmployee($_GET['employee_id'], $annee);
                echo json_encode(['success' => true, 'data' => $data]);
            } elseif ($action === 'by_module' && isset($_GET['module_id'])) {
                $data = $service->getAffectationsByModule($_GET['module_id']);
                echo json_encode(['success' => true, 'data' => $data]);
            } elseif ($action === 'by_annee' && isset($_GET['annee'])) {
                $data = $service->getAffectationsByAnnee($_GET['annee']);
                echo json_encode(['success' => true, 'data' => $data]);
            } elseif ($action === 'annees') {
                $data = $service->getAnneesUniversitaires();
                echo json_encode(['success' => true, 'data' => $data]);
            } elseif ($action === 'professeurs') {
                $data = $service->getProfesseursAffectes();
                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="affectations_' . date('Y-m-d') . '.csv"');
                    echo $csv;
                    exit();
                } else {
                    echo json_encode(['success' => false, 'message' => 'Aucune affectation à exporter']);
                }
            } else {
                $data = $service->findAll('id DESC');
                echo json_encode(['success' => true, 'data' => $data]);
            }
            break;

        case 'POST':
            $input = json_decode(file_get_contents('php://input'), true);
            if ($input) {
                $id = $service->createAffectation($input);
                echo json_encode(['success' => true, 'id' => $id, 'message' => 'Affectation créée 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->updateAffectation($_GET['id'], $input);
                    echo json_encode(['success' => true, 'message' => 'Affectation mise à 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->deleteAffectation($_GET['id']);
                echo json_encode(['success' => true, 'message' => 'Affectation supprimée 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()]);
}
?>