<?php
// model/api/etat_demande_document.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/EtatDemandeDocumentService.php';
$service = new EtatDemandeDocumentService();

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

try {
    switch ($method) {
        case 'GET':
            if ($action === 'search') {
                $searchData = [
                    'id' => $_GET['id'] ?? '',
                    'libelle' => $_GET['libelle'] ?? '',
                    'code' => $_GET['code'] ?? '',
                    'description' => $_GET['description'] ?? ''
                ];
                $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
                $perPage = isset($_GET['per_page']) ? (int)$_GET['per_page'] : 10;
                echo json_encode(['success' => true, 'data' => $service->search($searchData, $page, $perPage)]);
            } elseif ($action === 'get' && isset($_GET['id'])) {
                echo json_encode(['success' => true, 'data' => $service->getEtatDemande($_GET['id'])]);
            } elseif ($action === 'stats') {
                echo json_encode(['success' => true, 'data' => $service->getStats()]);
            }
            break;

        case 'POST':
            $input = json_decode(file_get_contents('php://input'), true);
            $id = $service->createEtatDemande($input);
            echo json_encode(['success' => true, 'id' => $id, 'message' => 'État créé avec succès']);
            break;

        case 'PUT':
            if (isset($_GET['id'])) {
                $input = json_decode(file_get_contents('php://input'), true);
                $service->updateEtatDemande($_GET['id'], $input);
                echo json_encode(['success' => true, 'message' => 'État mis à jour avec succès']);
            }
            break;

        case 'DELETE':
            if (isset($_GET['id'])) {
                $service->deleteEtatDemande($_GET['id']);
                echo json_encode(['success' => true, 'message' => 'État supprimé avec succès']);
            }
            break;
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}