<?php
// model/api/etat_demande_document.php
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

// LE CHEMIN EXACT : model/api/ -> model/service/
require_once __DIR__ . '/../service/EtatDemandeDocumentService.php';

$service = new EtatDemandeDocumentService();
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

if ($method === 'OPTIONS') {
    http_response_code(200);
    exit();
}

try {
    switch ($method) {
        case 'GET':
            if ($action === 'search') {
                $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
                $perPage = isset($_GET['per_page']) ? (int)$_GET['per_page'] : 10;
                
                // Appel au service
                $result = $service->search($_GET, $page, $perPage);
                
                // CRUCIAL : Le JS attend { success: true, data: { data: [...] } }
                echo json_encode(['success' => true, 'data' => $result]);
            } 
            elseif ($action === 'get') {
                $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
                $etat = $service->getEtat($id);
                if ($etat) {
                    echo json_encode(['success' => true, 'data' => $etat]);
                } else {
                    echo json_encode(['success' => false, 'message' => "État introuvable."]);
                }
            } 
            elseif ($action === 'stats') {
                $stats = $service->getStats();
                echo json_encode(['success' => true, 'data' => $stats]);
            }
            break;

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

        case 'PUT':
            $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
            $input = json_decode(file_get_contents("php://input"), true);
            $service->updateEtat($id, $input);
            echo json_encode(['success' => true, 'message' => "État mis à jour avec succès !"]);
            break;

        case 'DELETE':
            $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
            $service->deleteEtat($id);
            echo json_encode(['success' => true, 'message' => "État supprimé avec succès !"]);
            break;

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