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

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

try {
    switch ($method) {
        case 'GET':
            if ($action === 'get_annees') {
                $data = $service->getAnneesUniversitaires();
                echo json_encode(['success' => true, 'data' => $data]);
            }
            elseif ($action === 'get_filieres') {
                $annee = isset($_GET['annee']) ? $_GET['annee'] : '';
                $data = $service->getFiliereByAnnee($annee);
                echo json_encode(['success' => true, 'data' => $data]);
            }
            elseif ($action === 'get_semestres') {
                $filiereId = isset($_GET['filiere_id']) ? (int)$_GET['filiere_id'] : 0;
                $annee = isset($_GET['annee']) ? $_GET['annee'] : '';
                $data = $service->getSemestresByFiliere($filiereId, $annee);
                echo json_encode(['success' => true, 'data' => $data]);
            }
            elseif ($action === 'get_modules') {
                $filiereId = isset($_GET['filiere_id']) ? (int)$_GET['filiere_id'] : 0;
                $semestreId = isset($_GET['semestre_id']) ? (int)$_GET['semestre_id'] : 0;
                $annee = isset($_GET['annee']) ? $_GET['annee'] : '';
                $data = $service->getModulesByFiliereSemestre($filiereId, $semestreId, $annee);
                echo json_encode(['success' => true, 'data' => $data]);
            }
            // ===== NOUVEAU : Récupération des modules pour la modale =====
            elseif ($action === 'get_modules_with_affectations') {
                $data = $service->getModulesWithAffectations();
                echo json_encode(['success' => true, 'data' => $data]);
            }
            // ===== FIN NOUVEAU =====
            elseif ($action === 'get_students') {
                $inscriptionModuleId = isset($_GET['inscription_module_id']) ? (int)$_GET['inscription_module_id'] : 0;
                $data = $service->getStudentsByInscriptionModule($inscriptionModuleId);
                echo json_encode(['success' => true, 'data' => $data]);
            }
            elseif ($action === 'check_conflict') {
                $inscriptionModuleId = isset($_GET['inscription_module_id']) ? (int)$_GET['inscription_module_id'] : 0;
                $date = isset($_GET['date']) ? $_GET['date'] : '';
                $heure = isset($_GET['heure']) ? $_GET['heure'] : '';
                $excludeId = isset($_GET['exclude_id']) ? (int)$_GET['exclude_id'] : null;

                $result = $service->checkConflict($inscriptionModuleId, $date, $heure, $excludeId);
                echo json_encode(['success' => true, 'hasConflict' => $result['hasConflict'], 'existingLibelle' => $result['existingLibelle']]);
            }
            elseif ($action === 'search') {
                $criteria = [];
                if (isset($_GET['module_libelle'])) $criteria['module_libelle'] = $_GET['module_libelle'];
                if (isset($_GET['employee_nom'])) $criteria['employee_nom'] = $_GET['employee_nom'];
                if (isset($_GET['date_seance'])) $criteria['date_seance'] = $_GET['date_seance'];
                if (isset($_GET['heure_debut'])) $criteria['heure_debut'] = $_GET['heure_debut'];

                $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
                $perPage = isset($_GET['per_page']) ? (int)$_GET['per_page'] : 10;

                $result = $service->search($criteria, $page, $perPage);
                echo json_encode(['success' => true, 'data' => $result]);
            }
            elseif ($action === 'get' && isset($_GET['id'])) {
                $data = $service->getPresenceWithStudents($_GET['id']);
                if ($data) {
                    echo json_encode(['success' => true, 'data' => $data]);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Séance non trouvée']);
                }
            }
            elseif ($action === 'stats') {
                $data = $service->getStats();
                echo json_encode(['success' => true, 'data' => $data]);
            }
            else {
                $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
                $perPage = isset($_GET['per_page']) ? (int)$_GET['per_page'] : 10;
                $data = $service->search([], $page, $perPage);
                echo json_encode(['success' => true, 'data' => $data]);
            }
            break;

        case 'POST':
            $input = json_decode(file_get_contents('php://input'), true);
            if ($input && isset($input['inscription_module_id']) && isset($input['date']) && isset($input['presences'])) {
                $heureDebut = $input['heure_debut'] ?? '08:00';
                $nbHeures = $input['nb_heures'] ?? 2;
                $libelle = $input['libelle'] ?? null;

                $presenceId = $service->markPresence(
                    $input['inscription_module_id'],
                    $input['date'],
                    $heureDebut,
                    $nbHeures,
                    $libelle,
                    $input['presences']
                );
                echo json_encode(['success' => true, 'id' => $presenceId, 'message' => 'Séance créée avec succès']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Données invalides. Requis: inscription_module_id, date, presences']);
            }
            break;

        case 'PUT':
            if (isset($_GET['id'])) {
                $input = json_decode(file_get_contents('php://input'), true);
                if ($input && isset($input['presences'])) {
                    $service->updatePresence($_GET['id'], $input['presences']);
                }
                echo json_encode(['success' => true, 'message' => 'Séance mise à jour avec succès']);
            } else {
                echo json_encode(['success' => false, 'message' => 'ID requis']);
            }
            break;

        case 'DELETE':
            if (isset($_GET['id'])) {
                $service->deletePresence($_GET['id']);
                echo json_encode(['success' => true, 'message' => 'Séance 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) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>