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

$service = new EchelonService();


$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'] : '',
                    'echelle_id' => isset($_GET['echelle_id']) ? $_GET['echelle_id'] : '',
                    'grade_id' => isset($_GET['grade_id']) ? $_GET['grade_id'] : '',
                    'type_grade_id' => isset($_GET['type_grade_id']) ? $_GET['type_grade_id'] : '',
                    'description' => isset($_GET['description']) ? $_GET['description'] : '',
                    'echellon_suivant_id' => isset($_GET['echellon_suivant_id']) ? $_GET['echellon_suivant_id'] : ''
                ];
                $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->getEchellon($_GET['id']);
                if ($data) {
                    echo json_encode(['success' => true, 'data' => $data]);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Échelon non trouvé']);
                }
            } elseif ($action === 'stats') {
                $data = $service->getStats();
                echo json_encode(['success' => true, 'data' => $data]);
            } elseif ($action === 'all') {
                $data = $service->getAllEchellons();
                echo json_encode(['success' => true, 'data' => $data]);
            } elseif ($action === 'by_echelle' && isset($_GET['echelle_id'])) {
                $data = $service->getEchellonsByEchelle($_GET['echelle_id']);
                echo json_encode(['success' => true, 'data' => $data]);
            } elseif ($action === 'chain' && isset($_GET['id'])) {
                $data = $service->getEchellonChain($_GET['id']);
                echo json_encode(['success' => true, 'data' => $data]);
            } elseif ($action === 'is_last' && isset($_GET['id'])) {
                $data = $service->isLastEchellon($_GET['id']);
                echo json_encode(['success' => true, 'data' => ['is_last' => $data]]);
            } elseif ($action === 'export') {
                $csv = $service->exportToCsv();
                if ($csv) {
                    header('Content-Type: text/csv; charset=utf-8');
                    header('Content-Disposition: attachment; filename="echellons_' . date('Y-m-d') . '.csv"');
                    echo $csv;
                    exit();
                } else {
                    echo json_encode(['success' => false, 'message' => 'Aucun échelon à exporter']);
                }
            } else {
                $data = $service->findAll('code ASC');
                echo json_encode(['success' => true, 'data' => $data]);
            }
            break;

        case 'POST':
            $input = json_decode(file_get_contents('php://input'), true);
            if ($input) {
                $id = $service->createEchellon($input);
                echo json_encode(['success' => true, 'id' => $id, 'message' => 'Échelon 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->updateEchellon($_GET['id'], $input);
                    echo json_encode(['success' => true, 'message' => 'Échelon 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->deleteEchellon($_GET['id']);
                echo json_encode(['success' => true, 'message' => 'Échelon 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()]);
}
?>
