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

$service = new FiliereService();

$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'] : '',
                    'departement_id' => isset($_GET['departement_id']) ? $_GET['departement_id'] : '',
                    'description' => isset($_GET['description']) ? $_GET['description'] : ''
                ];
                $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->getFiliere($_GET['id']);
                if ($data) {
                    echo json_encode(['success' => true, 'data' => $data]);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Filière non trouvée']);
                }
            } elseif ($action === 'stats') {
                $data = $service->getStats();
                echo json_encode(['success' => true, 'data' => $data]);
            } elseif ($action === 'all') {
                $data = $service->getAllFiliere();
                echo json_encode(['success' => true, 'data' => $data]);
            } elseif ($action === 'by_departement' && isset($_GET['departement_id'])) {
                $data = $service->getFiliereByDepartement($_GET['departement_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="filieres_' . date('Y-m-d') . '.csv"');
                    echo $csv;
                    exit();
                } else {
                    echo json_encode(['success' => false, 'message' => 'Aucune filière à 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->createFiliere($input);
                echo json_encode(['success' => true, 'id' => $id, 'message' => 'Filière 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->updateFiliere($_GET['id'], $input);
                    echo json_encode(['success' => true, 'message' => 'Filière 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->deleteFiliere($_GET['id']);
                echo json_encode(['success' => true, 'message' => 'Filière 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()]);
}
?>