<?php
// Excel Export Helper Functions

function exportToExcel($data, $filename, $headers = []) {
    // Set headers for Excel download
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;filename="' . $filename . '"');
    header('Cache-Control: max-age=0');
    
    // Open output stream
    $output = fopen('php://output', 'w');
    
    // Add BOM for UTF-8
    fwrite($output, "\xEF\xBB\xBF");
    
    // If headers are provided, write them first
    if (!empty($headers)) {
        fputcsv($output, $headers, "\t");
    }
    
    // Write data rows
    foreach ($data as $row) {
        // Clean data and convert to proper format for Excel
        $cleanRow = [];
        foreach ($row as $value) {
            // Remove newlines and tabs, and escape quotes
            $cleanValue = str_replace(["\n", "\r", "\t"], " ", $value);
            $cleanValue = str_replace('"', '""', $cleanValue);
            $cleanRow[] = $cleanValue;
        }
        fputcsv($output, $cleanRow, "\t");
    }
    
    // Close output stream
    fclose($output);
    exit();
}

function formatDateTime($datetime) {
    if (empty($datetime)) return '';
    return date('d-M-Y H:i', strtotime($datetime));
}

function formatDate($date) {
    if (empty($date)) return '';
    return date('d-M-Y', strtotime($date));
}

function cleanForExcel($value) {
    if (empty($value)) return '';
    // Remove HTML tags and extra whitespace
    $value = strip_tags($value);
    $value = trim($value);
    // Convert newlines to spaces
    $value = str_replace(["\n", "\r"], " ", $value);
    return $value;
}
?>
