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

$service = new DocumentDossierAdministratifService();

$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'] : '',
                    'original_name' => isset($_GET['original_name']) ? $_GET['original_name'] : '',
                    'employee' => isset($_GET['employee']) ? $_GET['employee'] : '',
                    'category_id' => isset($_GET['category_id']) ? $_GET['category_id'] : '',
                    'etat_id' => isset($_GET['etat_id']) ? $_GET['etat_id'] : '',
                    'is_verified' => isset($_GET['is_verified']) ? $_GET['is_verified'] : ''
                ];
                $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->getDocument($_GET['id']);
                if ($data) {
                    echo json_encode(['success' => true, 'data' => $data]);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Document non trouvé']);
                }
            } elseif ($action === 'stats') {
                $data = $service->getStats();
                echo json_encode(['success' => true, 'data' => $data]);
            } elseif ($action === 'all') {
                $data = $service->getAllDocuments();
                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="documents_administratifs_' . date('Y-m-d') . '.csv"');
                    echo $csv;
                    exit();
                } else {
                    echo json_encode(['success' => false, 'message' => 'Aucun document à exporter']);
                }
            } else {
                $data = $service->findAll('id DESC');
                echo json_encode(['success' => true, 'data' => $data]);
            }
            break;

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