<?php
declare(strict_types=1);

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/maintenance_stages.php';
require_once __DIR__ . '/../app/helpers/rbac.php';
require_once __DIR__ . '/../app/helpers/audit.php';
require_once __DIR__ . '/../app/helpers/csrf.php';
require_once __DIR__ . '/../app/helpers/alerts.php';
require_once __DIR__ . '/../app/helpers/api_security.php';
require_once __DIR__ . '/../app/helpers/uploads.php';
require_once __DIR__ . '/../app/helpers/soft_delete.php';
require_once __DIR__ . '/../app/helpers/normalize.php';

require_once __DIR__ . '/maintenance/helpers.php';
require_once __DIR__ . '/maintenance/jobs.php';
require_once __DIR__ . '/maintenance/rfq.php';
require_once __DIR__ . '/maintenance/workflow.php';
require_once __DIR__ . '/maintenance/service_intervals.php';

header('Content-Type: application/json');

requireApiLogin();
enforceCsrfForUnsafeRequest();

if (!isAdmin() && !can('maintenance.view')) {
    respond(['status' => 'error', 'message' => 'Unauthorized']);
}

$action = $_GET['action'] ?? '';

try {
    switch ($action) {
        case 'reference_data':
            handleReferenceData($pdo);
            break;
        case 'jobs':
            handleJobs($pdo);
            break;
        case 'timeline':
            handleTimeline($pdo);
            break;
        case 'save_job':
            handleSaveJob($pdo);
            break;
        case 'stage_action':
            handleStageAction($pdo);
            break;
        case 'job_details':
            handleJobDetails($pdo);
            break;
        case 'rfq_list':
            handleRfqList($pdo);
            break;
        case 'add_rfq_vendor':
            handleAddRfqVendor($pdo);
            break;
        case 'upload_quote':
            handleUploadQuote($pdo);
            break;
        case 'select_final_workshop':
            handleSelectFinalWorkshop($pdo);
            break;
        case 'requisition_report':
            handleRequisitionReport($pdo);
            break;
        case 'service_intervals':
            handleServiceIntervals($pdo);
            break;
        case 'save_service_interval':
            handleSaveServiceInterval($pdo);
            break;
        case 'delete_service_interval':
            handleDeleteServiceInterval($pdo);
            break;
        case 'check_due_services':
            handleCheckDueServices($pdo);
            break;
        case 'generate_pm_job':
            handleGeneratePmJob($pdo);
            break;
        default:
            respond(['status' => 'error', 'message' => 'Invalid action']);
    }
} catch (Throwable $e) {
    respond(['status' => 'error', 'message' => $e->getMessage()]);
}
