<?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/DemandeDocumentService.php';

$service = new DemandeDocumentService();

$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'] ?? '',
                    'description' => $_GET['description'] ?? '',
                    'employee_id' => $_GET['employee_id'] ?? '',
                    'type_demande_document_id' => $_GET['type_demande_document_id'] ?? '',
                    'etat_demande_document_id' => $_GET['etat_demande_document_id'] ?? '',
                    'date_soumission_debut' => $_GET['date_soumission_debut'] ?? '',
                    'date_soumission_fin' => $_GET['date_soumission_fin'] ?? ''

                ];

                $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->getDemandeDocument($_GET['id']);

                if ($data) {

                    echo json_encode([
                        'success' => true,
                        'data' => $data
                    ]);

                } else {

                    echo json_encode([
                        'success' => false,
                        'message' => 'Demande introuvable'
                    ]);

                }

            } elseif ($action === 'stats') {

                $data = $service->getStats();

                echo json_encode([
                    'success' => true,
                    'data' => $data
                ]);

            } elseif ($action === 'employees') {

                $data = $service->getemployees();

                echo json_encode([
                    'success' => true,
                    'data' => $data
                ]);

            } elseif ($action === 'types_demande_documents') {

                $data = $service->getTypesDemandeDocuments();

                echo json_encode([
                    'success' => true,
                    'data' => $data
                ]);

            } elseif ($action === 'etats') {

                $data = $service->getEtats();

                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="demande_document_' . date('Y-m-d') . '.csv"');

                    echo $csv;
                    exit();

                } else {

                    echo json_encode([
                        'success' => false,
                        'message' => 'Aucune donnée à exporter'
                    ]);

                }

            } else {

                $data = $service->findAll('date_creation DESC');

                echo json_encode([
                    'success' => true,
                    'data' => $data
                ]);

            }

            break;
                  case 'POST':
    $input = json_decode(file_get_contents('php://input'), true);

    if ($input) {
        // التحقق من وجود action لتمييز العملية
        $action = isset($input['action']) ? $input['action'] : 'create';

        if ($action === 'update') {
            // حالة التعديل
            $service->updateDemandeDocument($input['id'], $input);
            echo json_encode(['success' => true, 'message' => 'Modification effectuée']);
        } 
        elseif ($action === 'delete') {
            // حالة الحذف
            $service->deleteDemandeDocument($input['id']);
            echo json_encode(['success' => true, 'message' => 'Suppression effectuée']);
        }
        else {
            // حالة الإنشاء (create)
            $id = $service->createDemandeDocument($input);
            echo json_encode(['success' => true, 'id' => $id, 'message' => 'Création effectuée']);
        }
    } 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->updateDemandeDocument($_GET['id'], $input);

                    echo json_encode([
                        'success' => true,
                        'message' => 'Demande 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->deleteDemandeDocument($_GET['id']);

                echo json_encode([
                    'success' => true,
                    'message' => 'Demande 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()
    ]);

}
?>
