<?php
declare(strict_types=1);

require_once '../config/database.php';
require_once '../app/helpers/rbac.php';
require_once '../app/helpers/api_security.php';
require_once __DIR__ . '/../vendor/autoload.php';

requireApiLogin();
enforceCsrfForUnsafeRequest();

if (!isAdmin() && !can('data.export') && !can('report.view')) {
    apiRespond(['status' => 'error', 'message' => 'Unauthorized']);
}

$type = $_GET['type'] ?? '';
$format = $_GET['format'] ?? 'csv';

try {
    switch ($type) {
        case 'vehicles':   doExport('vehicles', $format, $pdo); break;
        case 'drivers':    doExport('drivers', $format, $pdo); break;
        case 'trips':      doExport('trips', $format, $pdo); break;
        case 'insurance':  doExport('insurance', $format, $pdo); break;
        case 'incidents':  doExport('incidents', $format, $pdo); break;
        case 'parts':      doExport('parts', $format, $pdo); break;
        case 'tyres':      doExport('tyres', $format, $pdo); break;
        case 'expenses':   doExport('expenses', $format, $pdo); break;
        case 'tco':        exportTco($format, $pdo); break;
        case 'maintenance': exportMaintenance($format, $pdo); break;
        case 'fuel':        exportFuel($format, $pdo); break;
        case 'workshop':    doExport('workshop', $format, $pdo); break;
        case 'compliance':  doExport('compliance', $format, $pdo); break;
        case 'vehicle_inspection': doExport('vehicle_inspection', $format, $pdo); break;
        case 'insurance_claims':  exportInsuranceClaims($format, $pdo); break;
        case 'driver_off_duty':   doExport('driver_off_duty', $format, $pdo); break;
        default: apiRespond(['status' => 'error', 'message' => 'Unknown export type']);
    }
} catch (Exception $e) {
    apiRespond(['status' => 'error', 'message' => $e->getMessage()]);
}

function doExport(string $type, string $format, PDO $pdo): void
{
    $exporters = [
        'vehicles' => ['fn' => 'getVehicleRows', 'headers' => ['ID','Plate Number','Make','Model','Type','Year','Color','Engine No','Chassis No','Status','Created'], 'filename' => 'vehicles'],
        'drivers'  => ['fn' => 'getDriverRows', 'headers' => ['ID','Name','Phone','Date of Birth','Status','Created'], 'filename' => 'drivers'],
        'trips'    => ['fn' => 'getTripRows', 'headers' => ['ID','Vehicle','Driver','Start Date','End Date','Start Odometer','End Odometer','Start Location','End Location','Purpose','Status'], 'filename' => 'trips'],
        'insurance' => ['fn' => 'getInsuranceRows', 'headers' => ['ID','Vehicle','Policy No','Insurer','Type','Start','End','Premium','Active'], 'filename' => 'insurance_policies'],
        'incidents' => ['fn' => 'getIncidentRows', 'headers' => ['ID','Vehicle','Driver','Date','Type','Severity','Location','Description','Status'], 'filename' => 'incidents'],
        'parts'    => ['fn' => 'getPartRows', 'headers' => ['ID','Category','Part No','Name','Stock','Reorder Level','Unit Cost','Supplier','Bin'], 'filename' => 'parts_inventory'],
        'tyres'    => ['fn' => 'getTyreRows', 'headers' => ['ID','Vehicle','Brand','Size','Serial No','Position','Purchase Date','Fitted Date','Fitted Odometer','Status'], 'filename' => 'tyres'],
        'expenses' => ['fn' => 'getExpenseRows', 'headers' => ['ID','Vehicle','Category','Date','Amount','Description','Driver'], 'filename' => 'vehicle_expenses'],
        'workshop' => ['fn' => 'getWorkshopRows', 'headers' => ['ID','Name','Address','Phone','Email','Contact Person','Contact Phone','Status'], 'filename' => 'workshops'],
        'compliance' => ['fn' => 'getComplianceRows', 'headers' => ['ID','Vehicle','Document Type','Jurisdiction','Document No','Issue Date','Expiry Date','Status'], 'filename' => 'compliance_renewals'],
        'vehicle_inspection' => ['fn' => 'getVehicleInspectionRows', 'headers' => ['ID','Vehicle','Inspection Date','Inspector','Total Items','Fails','Result','Notes'], 'filename' => 'vehicle_inspections'],
        'driver_off_duty' => ['fn' => 'getDriverOffDutyRows', 'headers' => ['Driver','Month','Days Taken','Max','Remaining'], 'filename' => 'driver_off_duty'],
    ];
    $cfg = $exporters[$type];
    $rows = $cfg['fn']($pdo);
    $headers = $cfg['headers'];
    $filename = $cfg['filename'];

    if ($format === 'csv') {
        outputCsv($rows, $headers, $filename);
    } else {
        outputSpreadsheet($rows, $headers, $filename, $format);
    }
}

function outputCsv(array $rows, array $headers, string $filename): void
{
    if (ob_get_level()) ob_end_clean();
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '_' . date('Ymd_His') . '.csv"');
    $out = fopen('php://output', 'w');
    fprintf($out, chr(0xEF) . chr(0xBB) . chr(0xBF));
    fputcsv($out, $headers);
    foreach ($rows as $row) {
        $line = array_values((array)$row);
        if (count($line) > count($headers)) $line = array_slice($line, 0, count($headers));
        fputcsv($out, $line);
    }
    fclose($out);
    exit;
}

function outputSpreadsheet(array $rows, array $headers, string $filename, string $format): void
{
    if (ob_get_level()) ob_end_clean();

    if ($format === 'pdf') {
        outputPdf($rows, $headers, $filename);
        return;
    }

    $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();
    $sheet->setTitle(substr($filename, 0, 31));

    foreach ($headers as $col => $header) {
        $cell = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($col + 1) . '1';
        $sheet->setCellValue($cell, $header);
    }

    foreach ($rows as $r => $row) {
        $vals = array_values((array)$row);
        if (count($vals) > count($headers)) $vals = array_slice($vals, 0, count($headers));
        foreach ($vals as $c => $v) {
            $cell = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($c + 1) . ($r + 2);
            $sheet->setCellValueExplicit($cell, (string)($v ?? ''), \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
        }
    }

    foreach (range(1, count($headers)) as $col) {
        $sheet->getColumnDimensionByColumn($col)->setAutoSize(true);
    }

    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment; filename="' . $filename . '_' . date('Ymd_His') . '.xlsx"');
    $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
    $writer->save('php://output');
    exit;
}

function outputPdf(array $rows, array $headers, string $filename): void
{
    if (ob_get_level()) ob_end_clean();
    require_once __DIR__ . '/../vendor/autoload.php';

    if (class_exists('\Mpdf\Mpdf')) {
        $mpdf = new \Mpdf\Mpdf(['orientation' => 'L', 'tempDir' => sys_get_temp_dir(), 'default_font_size' => 9]);
        $mpdf->SetTitle(ucwords(str_replace('_', ' ', $filename)));
        $html = '<h2>' . htmlspecialchars(ucwords(str_replace('_', ' ', $filename)), ENT_QUOTES, 'UTF-8') . '</h2>'
              . '<p style="font-size:9px;color:#666">Generated: ' . date('Y-m-d H:i') . '</p>'
              . '<table border="1" cellpadding="4" cellspacing="0" style="border-collapse:collapse;width:100%;font-size:9px">'
              . '<thead><tr style="background:#2563eb;color:#fff">';
        foreach ($headers as $h) {
            $html .= '<th style="padding:4px 6px;text-align:left">' . htmlspecialchars((string)$h, ENT_QUOTES, 'UTF-8') . '</th>';
        }
        $html .= '</tr></thead><tbody>';
        foreach ($rows as $row) {
            $vals = array_values((array)$row);
            if (count($vals) > count($headers)) $vals = array_slice($vals, 0, count($headers));
            $html .= '<tr>';
            foreach ($vals as $v) {
                $html .= '<td style="padding:3px 6px">' . htmlspecialchars((string)($v ?? ''), ENT_QUOTES, 'UTF-8') . '</td>';
            }
            $html .= '</tr>';
        }
        $html .= '</tbody></table>';
        $mpdf->WriteHTML($html);
        $mpdf->Output($filename . '_' . date('Ymd_His') . '.pdf', 'D');
        exit;
    }

    // Pure PHP fallback — minimal valid PDF
    require_once __DIR__ . '/../app/helpers/minipdf.php';
    $colCount = count($headers);
    $pageW = 280;
    $colW = max(15, min(55, (int)(($pageW - $colCount) / max($colCount, 1))));
    $usableW = $colW * $colCount;

    $pdf = new MiniPdf('L', 'mm', 'A4');
    $pdf->setTitle(ucwords(str_replace('_', ' ', $filename)));
    $pdf->addPage();
    $pdf->setFont('Helvetica', 14);
    $pdf->cell($usableW, 8, ucwords(str_replace('_', ' ', $filename)), 0, 1, 'L');
    $pdf->setFont('Helvetica', 7);
    $pdf->cell($usableW, 5, 'Generated: ' . date('Y-m-d H:i'), 0, 1, 'L');
    $pdf->ln(3);

    $pdf->setFont('Helvetica', 7);
    $headerH = 6;
    $rowH = 5;

    // Headers
    $pdf->setFillColor(37, 99, 235);
    $pdf->setTextColor(255, 255, 255);
    foreach ($headers as $i => $h) {
        $pdf->cell($colW, $headerH, (string)$h, 1, 0, 'L', true);
    }
    $pdf->ln();

    // Rows
    $pdf->setTextColor(0, 0, 0);
    $fill = false;
    foreach ($rows as $row) {
        $vals = array_values((array)$row);
        if (count($vals) > $colCount) $vals = array_slice($vals, 0, $colCount);
        if ($fill) $pdf->setFillColor(249, 250, 251);
        else $pdf->setFillColor(255, 255, 255);
        foreach ($vals as $v) {
            $pdf->cell($colW, $rowH, (string)($v ?? ''), 1, 0, 'L', true);
        }
        $pdf->ln();
        $fill = !$fill;
    }

    $pdf->output($filename . '_' . date('Ymd_His') . '.pdf');
    exit;
}

function getVehicleRows(PDO $pdo): array
{
    return $pdo->query("SELECT v.id, v.plate_number, v.vehicle_model AS make, v.vehicle_type, v.year_of_manufacturing AS year, v.color, v.engine_number, v.chassis_number, v.vehicle_status AS status, v.created_at FROM vehicles v WHERE v.deleted_at IS NULL ORDER BY v.id DESC")->fetchAll();
}
function getDriverRows(PDO $pdo): array
{
    return $pdo->query("SELECT d.id, d.full_name AS name, d.phone, d.date_of_birth, COALESCE(d.driver_status, d.active_status) AS status, d.created_at FROM drivers d WHERE d.deleted_at IS NULL ORDER BY d.full_name ASC")->fetchAll();
}
function getTripRows(PDO $pdo): array
{
    return $pdo->query("SELECT t.id, v.plate_number AS vehicle, d.full_name AS driver, t.start_date, t.end_date, t.start_odometer, t.end_odometer, t.start_location, t.end_location, t.purpose, t.status FROM trips t LEFT JOIN vehicles v ON v.id=t.vehicle_id LEFT JOIN drivers d ON d.id=t.driver_id WHERE t.deleted_at IS NULL ORDER BY t.start_date DESC")->fetchAll();
}
function getInsuranceRows(PDO $pdo): array
{
    return $pdo->query("SELECT p.id, v.plate_number AS vehicle, p.policy_number, COALESCE(i.name, p.insurer_name) AS insurer, p.policy_type, p.coverage_start, p.coverage_end, p.premium_amount, CASE WHEN p.is_active=1 THEN 'Yes' ELSE 'No' END AS active FROM vehicle_insurance_policies p LEFT JOIN vehicles v ON v.id=p.vehicle_id LEFT JOIN insurers i ON i.id=p.insurer_id WHERE p.deleted_at IS NULL ORDER BY p.coverage_end ASC")->fetchAll();
}
function getIncidentRows(PDO $pdo): array
{
    return $pdo->query("SELECT i.id, v.plate_number AS vehicle, d.full_name AS driver, i.incident_date, i.incident_type, i.severity, i.location, i.description, i.status FROM incidents i LEFT JOIN vehicles v ON v.id=i.vehicle_id LEFT JOIN drivers d ON d.id=i.driver_id WHERE i.deleted_at IS NULL ORDER BY i.incident_date DESC")->fetchAll();
}
function getPartRows(PDO $pdo): array
{
    return $pdo->query("SELECT p.id, pc.name AS category, p.part_number, p.name, p.quantity_in_stock, p.reorder_level, p.unit_cost, COALESCE(s.name,'') AS supplier, bl.name AS bin FROM parts p LEFT JOIN part_categories pc ON pc.id=p.category_id LEFT JOIN suppliers s ON s.id=p.supplier_id AND s.deleted_at IS NULL LEFT JOIN bin_locations bl ON bl.id=p.bin_location_id WHERE p.deleted_at IS NULL ORDER BY p.name ASC")->fetchAll();
}
function getTyreRows(PDO $pdo): array
{
    return $pdo->query("SELECT t.id, v.plate_number AS vehicle, COALESCE(b.name,t.brand) AS brand, t.size, t.serial_number, t.position, t.purchase_date, t.created_at AS fitted_date, t.purchase_cost AS fitted_odometer, t.status FROM tyres t LEFT JOIN vehicles v ON v.id=t.vehicle_id LEFT JOIN tyre_brands b ON b.id=t.brand_id WHERE t.deleted_at IS NULL ORDER BY t.purchase_date DESC")->fetchAll();
}
function getExpenseRows(PDO $pdo): array
{
    return $pdo->query("SELECT e.id, v.plate_number AS vehicle, ec.name AS category, e.expense_date, e.amount, e.description, d.full_name AS driver FROM vehicle_expenses e LEFT JOIN vehicles v ON v.id=e.vehicle_id LEFT JOIN expense_categories ec ON ec.id=e.category_id LEFT JOIN drivers d ON d.id=e.driver_id WHERE e.deleted_at IS NULL ORDER BY e.expense_date DESC")->fetchAll();
}
function getWorkshopRows(PDO $pdo): array
{
    return $pdo->query("SELECT w.id, w.name, w.address, w.phone, w.email, w.contact_person, w.contact_phone, w.status FROM workshops w WHERE w.deleted_at IS NULL ORDER BY w.name ASC")->fetchAll();
}
function getComplianceRows(PDO $pdo): array
{
    return $pdo->query("SELECT vdr.id, v.plate_number AS vehicle, ndt.name AS document_type, vdr.jurisdiction, vdr.document_number, vdr.issue_date, vdr.expiry_date, vdr.status FROM vehicle_document_renewals vdr INNER JOIN vehicle_document_profiles vdp ON vdp.id=vdr.profile_id INNER JOIN vehicles v ON v.id=vdp.vehicle_id INNER JOIN nigeria_document_types ndt ON ndt.id=vdp.document_type_id WHERE vdr.deleted_at IS NULL ORDER BY vdr.expiry_date DESC")->fetchAll();
}
function getVehicleInspectionRows(PDO $pdo): array
{
    return $pdo->query("SELECT i.id, v.plate_number AS vehicle, i.inspection_date, i.inspector_name AS inspector, (SELECT COUNT(*) FROM inspection_results r WHERE r.inspection_id=i.id) AS total_items, (SELECT COUNT(*) FROM inspection_results r WHERE r.inspection_id=i.id AND r.result='fail') AS fails, CASE WHEN (SELECT COUNT(*) FROM inspection_results r WHERE r.inspection_id=i.id AND r.result='fail')>0 THEN 'Fail' ELSE 'Pass' END AS result, i.notes FROM vehicle_inspections i LEFT JOIN vehicles v ON v.id=i.vehicle_id WHERE i.deleted_at IS NULL ORDER BY i.inspection_date DESC")->fetchAll();
}

function getDriverOffDutyRows(PDO $pdo): array
{
    $month = $_GET['month'] ?? date('Y-m');
    $stmt = $pdo->prepare("
        SELECT d.full_name AS driver, COALESCE(o.month_year, :month) AS month_year,
               COALESCE(o.days_taken, 0) AS days_taken, 5 AS max_days,
               GREATEST(0, 5 - COALESCE(o.days_taken, 0)) AS remaining
        FROM drivers d
        LEFT JOIN (
            SELECT driver_id, month_year, COUNT(*) AS days_taken
            FROM driver_off_duty
            WHERE month_year = :month2 AND deleted_at IS NULL
            GROUP BY driver_id, month_year
        ) o ON o.driver_id = d.id
        WHERE d.deleted_at IS NULL
        ORDER BY d.full_name ASC
    ");
    $stmt->execute(['month' => $month, 'month2' => $month]);
    return $stmt->fetchAll();
}

function exportFuel(string $format, PDO $pdo): void
{
    $startDate = $_GET['start_date'] ?? '';
    $endDate = $_GET['end_date'] ?? '';
    $vehicleId = (int)($_GET['vehicle_id'] ?? 0);
    $search = trim($_GET['search'] ?? '');

    $where = ['vfe.deleted_at IS NULL'];
    $params = [];
    if ($vehicleId > 0) { $where[] = 'vfe.vehicle_id=:vid'; $params['vid'] = $vehicleId; }
    if ($search !== '') { $where[] = '(vfe.voucher_id LIKE :q OR v.plate_number LIKE :q2)'; $params['q'] = "%$search%"; $params['q2'] = "%$search%"; }
    if ($startDate !== '') { $where[] = 'vfe.record_date>=:sd'; $params['sd'] = $startDate; }
    if ($endDate !== '') { $where[] = 'vfe.record_date<=:ed'; $params['ed'] = $endDate; }

    $stmt = $pdo->prepare("SELECT vfe.voucher_id, vfe.record_date, vfe.fueling_type, v.plate_number, vfe.driver_name, ft.name AS fuel_type, vfe.quantity_litres, vfe.naira_per_liter, vfe.total_amount, vfe.mileage_km, vfe.approval_status FROM vehicle_fuel_entries vfe INNER JOIN vehicles v ON v.id=vfe.vehicle_id LEFT JOIN fuel_types ft ON ft.id=vfe.fuel_type_id WHERE " . implode(' AND ', $where) . " ORDER BY vfe.record_date DESC");
    $stmt->execute($params);
    $rows = $stmt->fetchAll();

    $headers = ['Voucher ID','Date','Fueling Type','Plate Number','Driver','Fuel Type','Quantity (L)','Rate (NGN/L)','Total Amount','Mileage','Status'];
    if ($format === 'csv') {
        outputCsv($rows, $headers, 'fuel_entries');
    } else {
        outputSpreadsheet($rows, $headers, 'fuel_entries', $format);
    }
}

function exportMaintenance(string $format, PDO $pdo): void
{
    $stage = trim($_GET['stage'] ?? '');
    $search = trim($_GET['search'] ?? '');
    $startDate = trim($_GET['start_date'] ?? '');
    $endDate = trim($_GET['end_date'] ?? '');

    $where = ['mj.deleted_at IS NULL'];
    $params = [];
    if ($stage !== '') { $where[] = 'mj.workflow_stage=:ws'; $params['ws'] = $stage; }
    if ($search !== '') { $where[] = '(v.plate_number LIKE :q OR mj.complaint_title LIKE :q2)'; $params['q'] = "%$search%"; $params['q2'] = "%$search%"; }
    if ($startDate !== '') { $where[] = 'mj.complaint_date>=:sd'; $params['sd'] = $startDate; }
    if ($endDate !== '') { $where[] = 'mj.complaint_date<=:ed'; $params['ed'] = $endDate; }

    $stmt = $pdo->prepare("SELECT mj.work_order_number, v.plate_number, d.full_name AS driver, mj.complaint_date, mj.complaint_title, mj.nature_of_fault, mj.workshop, mj.workflow_stage, COALESCE(mj.approved_amount,mj.cost_of_repair,0) AS cost, mj.created_at FROM maintenance_jobs mj INNER JOIN vehicles v ON v.id=mj.vehicle_id LEFT JOIN drivers d ON d.id=mj.driver_id WHERE " . implode(' AND ', $where) . " ORDER BY mj.created_at DESC");
    $stmt->execute($params);
    $rows = $stmt->fetchAll();

    $headers = ['Work Order','Plate Number','Driver','Date','Title','Fault','Workshop','Stage','Cost','Created'];
    if ($format === 'csv') {
        outputCsv($rows, $headers, 'maintenance_export');
    } else {
        outputSpreadsheet($rows, $headers, 'maintenance_export', $format);
    }
}

function exportTco(string $format, PDO $pdo): void
{
    $year = (int)($_GET['year'] ?? date('Y'));
    $vehicleId = (int)($_GET['vehicle_id'] ?? 0);
    $startDate = $_GET['start_date'] ?? "$year-01-01";
    $endDate = $_GET['end_date'] ?? "$year-12-31";

    $vehicleWhere = '';
    $params = [':start' => $startDate, ':end' => $endDate];
    if ($vehicleId > 0) { $vehicleWhere = ' AND v.id=:vid'; $params[':vid'] = $vehicleId; }

    $stmt = $pdo->prepare("SELECT v.plate_number, v.vehicle_model, v.vehicle_type, v.year_of_manufacturing AS model_year, COALESCE((SELECT SUM(f.total_amount) FROM vehicle_fuel_entries f WHERE f.vehicle_id=v.id AND f.deleted_at IS NULL AND f.approval_status='Approved' AND f.record_date BETWEEN :start AND :end),0) AS fuel_cost, COALESCE((SELECT COALESCE(SUM(m.approved_amount),SUM(m.cost_of_repair),0) FROM maintenance_jobs m WHERE m.vehicle_id=v.id AND m.deleted_at IS NULL AND m.complaint_date BETWEEN :start2 AND :end2),0) AS maint_cost, COALESCE((SELECT SUM(p.premium_amount) FROM vehicle_insurance_policies p WHERE p.vehicle_id=v.id AND p.deleted_at IS NULL AND (p.coverage_start BETWEEN :start3 AND :end3 OR p.coverage_end BETWEEN :start3 AND :end3)),0) AS ins_cost, COALESCE((SELECT SUM(e.amount) FROM vehicle_expenses e WHERE e.vehicle_id=v.id AND e.deleted_at IS NULL AND e.expense_date BETWEEN :start4 AND :end4),0) AS expense_cost FROM vehicles v WHERE v.deleted_at IS NULL AND v.vehicle_status IN ('active','Active','ACTIVE')$vehicleWhere ORDER BY v.plate_number");
    $stmt->execute(array_merge($params, [':start2'=>$startDate,':end2'=>$endDate,':start3'=>$startDate,':end3'=>$endDate,':start4'=>$startDate,':end4'=>$endDate]));
    $rows = $stmt->fetchAll();

    $data = [];
    foreach ($rows as $r) {
        $tco = (float)$r['fuel_cost'] + (float)$r['maint_cost'] + (float)$r['ins_cost'] + (float)$r['expense_cost'];
        $data[] = ['plate_number'=>$r['plate_number'],'vehicle_model'=>$r['vehicle_model']??'','vehicle_type'=>$r['vehicle_type'],'model_year'=>$r['model_year'],'fuel_cost'=>round((float)$r['fuel_cost'],2),'maint_cost'=>round((float)$r['maint_cost'],2),'ins_cost'=>round((float)$r['ins_cost'],2),'expense_cost'=>round((float)$r['expense_cost'],2),'tco'=>round($tco,2)];
    }

    $headers = ['Plate Number','Make/Model','Type','Model Year','Fuel Cost','Maintenance','Insurance','Expenses','TCO'];
    if ($format === 'csv') {
        outputCsv($data, $headers, 'tco_report');
    } else {
        outputSpreadsheet($data, $headers, 'tco_report', $format);
    }
}

function exportInsuranceClaims(string $format, PDO $pdo): void
{
    $rows = $pdo->query("SELECT c.claim_number, p.policy_number, p.insurer_name, v.plate_number AS vehicle, c.incident_date, c.claim_amount, c.settlement_amount, c.payment_date, c.status, c.description, c.created_at FROM insurance_claims c LEFT JOIN vehicle_insurance_policies p ON p.id=c.policy_id LEFT JOIN vehicles v ON v.id=p.vehicle_id ORDER BY c.incident_date DESC")->fetchAll();
    $headers = ['Claim Number','Policy Number','Insurer','Vehicle','Incident Date','Claim Amount','Settlement Amount','Payment Date','Status','Description','Created At'];
    if ($format === 'csv') {
        outputCsv($rows, $headers, 'insurance_claims');
    } else {
        outputSpreadsheet($rows, $headers, 'insurance_claims', $format);
    }
}
