<?php
// model/api/avancement.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/AvancementService.php';

$service = new \model\service\AvancementService();

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

try {
    switch ($method) {
        case 'GET':
            switch ($action) {
                case 'stats':
                    echo json_encode(['success' => true, 'data' => $service->getStats()]);
                    break;

                case 'get':
                    if (!isset($_GET['id'])) {
                        echo json_encode(['success' => false, 'message' => 'ID manquant']);
                        break;
                    }
                    $data = $service->findByIdWithJoins(intval($_GET['id']));
                    echo json_encode($data ? ['success' => true, 'data' => $data] : ['success' => false, 'message' => 'Introuvable']);
                    break;

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

                case 'search':
                    // All filter extraction and pagination logic is now in the service
                    $result = $service->handleSearchRequest();
                    echo json_encode(['success' => true, 'data' => $result]);
                    break;

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

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

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

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

                case 'export':
                    $service->exportCsv();
                    break;

                default:
                    echo json_encode(['success' => false, 'message' => 'Action non reconnue']);
            }
            break;

        case 'POST':
            $input = json_decode(file_get_contents('php://input'), true);
            if (!$input) {
                echo json_encode(['success' => false, 'message' => 'Données invalides']);
                break;
            }
            $id = $service->create($input);
            echo json_encode(['success' => true, 'id' => $id, 'message' => 'Avancement créé avec succès']);
            break;

        case 'PUT':
            if (!isset($_GET['id'])) {
                echo json_encode(['success' => false, 'message' => 'ID manquant']);
                break;
            }
            $input = json_decode(file_get_contents('php://input'), true);
            if (!$input) {
                echo json_encode(['success' => false, 'message' => 'Données invalides']);
                break;
            }
            $service->update(intval($_GET['id']), $input);
            echo json_encode(['success' => true, 'message' => 'Avancement mis à jour']);
            break;

        case 'DELETE':
            if (!isset($_GET['id'])) {
                echo json_encode(['success' => false, 'message' => 'ID manquant']);
                break;
            }
            $service->deleteById(intval($_GET['id']));
            echo json_encode(['success' => true, 'message' => 'Avancement supprimé']);
            break;

        default:
            echo json_encode(['success' => false, 'message' => 'Méthode non autorisée']);
    }
} catch (\Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>