<?php
// app/model/api/inscription_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/InscriptionModuleService.php';
require_once __DIR__ . '/../service/InscriptionModuleDetailService.php';

$service = new InscriptionModuleService();
$detailService = new InscriptionModuleDetailService();

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

try {
    switch ($method) {
        case 'GET':
            switch ($action) {
                case 'search':
                    $filters = [
                        'annee_universitaire' => isset($_GET['annee_universitaire']) ? $_GET['annee_universitaire'] : '',
                        'filiere_id' => isset($_GET['filiere_id']) ? $_GET['filiere_id'] : '',
                        'module_id' => isset($_GET['module_id']) ? $_GET['module_id'] : '',
                        'search' => isset($_GET['search']) ? $_GET['search'] : ''
                    ];
                    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
                    $perPage = isset($_GET['per_page']) ? (int)$_GET['per_page'] : 10;

                    $result = $service->search($filters, $page, $perPage);
                    echo json_encode(['success' => true, 'data' => $result]);
                    break;

                case 'get':
                    if (isset($_GET['id'])) {
                        $data = $service->getById($_GET['id']);
                        if ($data) {
                            // Get students
                            $data['students'] = $detailService->getStudentsByInscriptionId($data['id']);
                            $data['nb_etudiants_inscrits'] = count($data['students']);
                            echo json_encode(['success' => true, 'data' => $data]);
                        } else {
                            echo json_encode(['success' => false, 'message' => 'Inscription non trouvée']);
                        }
                    } else {
                        echo json_encode(['success' => false, 'message' => 'ID requis']);
                    }
                    break;

                case 'stats':
                    $data = $service->getStats();
                    echo json_encode(['success' => true, 'data' => $data]);
                    break;

                case 'annees':
                    $data = $service->getAnneesUniversitaires();
                    echo json_encode(['success' => true, 'data' => $data]);
                    break;

                case 'students':
                    if (isset($_GET['inscription_module_id'])) {
                        $data = $detailService->getStudentsByInscriptionId($_GET['inscription_module_id']);
                        echo json_encode(['success' => true, 'data' => $data]);
                    } else {
                        echo json_encode(['success' => false, 'message' => 'inscription_module_id requis']);
                    }
                    break;

                case 'check_duplicate':
                    if (isset($_GET['filiere_id']) && isset($_GET['module_id']) && isset($_GET['annee_universitaire'])) {
                        $data = $service->checkDuplicate($_GET['filiere_id'], $_GET['module_id'], $_GET['annee_universitaire']);
                        echo json_encode(['success' => true, 'exists' => $data !== false, 'data' => $data]);
                    } else {
                        echo json_encode(['success' => false, 'message' => 'filiere_id, module_id et annee_universitaire requis']);
                    }
                    break;

                default:
                    $data = $service->search([], 1, 10);
                    echo json_encode(['success' => true, 'data' => $data]);
            }
            break;

        case 'POST':
            if ($action === 'import_csv') {
                // Handle CSV import
                if (!isset($_FILES['csv_file']) || $_FILES['csv_file']['error'] !== UPLOAD_ERR_OK) {
                    echo json_encode(['success' => false, 'message' => 'Fichier CSV invalide ou manquant']);
                    exit;
                }

                $fileType = pathinfo($_FILES['csv_file']['name'], PATHINFO_EXTENSION);
                if (strtolower($fileType) !== 'csv') {
                    echo json_encode(['success' => false, 'message' => 'Le fichier doit être au format CSV']);
                    exit;
                }

                // Get form data
                $data = json_decode(file_get_contents('php://input'), true);
                if (!$data) {
                    // Try POST data
                    $data = [
                        'filiere_id' => isset($_POST['filiere_id']) ? $_POST['filiere_id'] : null,
                        'module_id' => isset($_POST['module_id']) ? $_POST['module_id'] : null,
                        'annee_universitaire' => isset($_POST['annee_universitaire']) ? $_POST['annee_universitaire'] : null,
                        'description' => isset($_POST['description']) ? $_POST['description'] : null,
                        'column_name' => isset($_POST['column_name']) ? $_POST['column_name'] : 'cin'
                    ];
                }

                if (empty($data['filiere_id']) || empty($data['module_id']) || empty($data['annee_universitaire'])) {
                    echo json_encode(['success' => false, 'message' => 'Tous les champs sont obligatoires']);
                    exit;
                }

                // Get employee_id from session
                session_start();
                $employeeId = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 1;

                $result = $service->importCsv(
                    $_FILES['csv_file']['tmp_name'],
                    $data,
                    $employeeId
                );

                echo json_encode(['success' => true, 'data' => $result]);
                break;
            }

            // Create inscription
            $input = json_decode(file_get_contents('php://input'), true);
            if ($input) {
                $id = $service->create($input);
                echo json_encode(['success' => true, 'id' => $id, 'message' => 'Inscription 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->update($_GET['id'], $input);
                    echo json_encode(['success' => true, 'message' => 'Inscription 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->delete($_GET['id']);
                echo json_encode(['success' => true, 'message' => 'Inscription 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()]);
}