<?php
/**
 * Preaching Plan - CSV Export
 */

// Start output buffering to prevent any accidental output
ob_start();

require_once __DIR__ . '/../../includes/auth.php';
requireAuth();
requireAdmin();

// Clear any output that might have been generated
ob_end_clean();

$year = isset($_GET['year']) ? (int)$_GET['year'] : date('Y');
$serviceType = $_GET['service_type'] ?? 'first-service';
$month = $_GET['month'] ?? null;

// Map service type values to display names
$serviceTypeNames = [
    'first-service' => 'First Service',
    'forenoon' => 'Forenoon',
    'joint-service' => 'Joint Service'
];

// Build WHERE clause
$where = "YEAR(service_date) = ? AND service_type = ?";
$params = [$year, $serviceType];

if ($month && preg_match('/^\d{4}-\d{2}$/', $month)) {
    $where .= " AND DATE_FORMAT(service_date, '%Y-%m') = ?";
    $params[] = $month;
}

$stmt = $pdo->prepare("
    SELECT * FROM preaching_plan 
    WHERE $where
    ORDER BY service_date ASC
");
$stmt->execute($params);
$entries = $stmt->fetchAll();

// Helper function for title case
function toTitleCase($str) {
    if (empty($str)) return '';
    return ucwords(strtolower($str));
}

// Set headers for CSV download
$filename = 'preaching-plan-' . $serviceTypeNames[$serviceType] . '-' . $year;
if ($month) {
    $filename .= '-' . date('F', strtotime($month . '-01'));
}
$filename .= '-' . date('Y-m-d') . '.csv';

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Pragma: no-cache');
header('Expires: 0');

// Open output stream
$output = fopen('php://output', 'w');

// Add BOM for UTF-8 (helps Excel recognize encoding)
fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));

// Write CSV headers
$headers = ['Date', 'Service Type', 'Occasion', 'Preacher', 'Liturgist'];
if ($serviceType !== 'first-service') {
    $headers[] = 'Ga Bible Reader';
}
$headers[] = 'Twi Bible Reader';
$headers[] = 'English Bible Reader';
$headers[] = 'Remarks';

fputcsv($output, $headers);

// Write data rows
foreach ($entries as $entry) {
    $row = [
        date('Y-m-d', strtotime($entry['service_date'])),
        $serviceTypeNames[$entry['service_type']] ?? $entry['service_type'],
        toTitleCase($entry['occasion']),
        $entry['preacher'],
        $entry['liturgist']
    ];
    
    if ($serviceType !== 'first-service') {
        $row[] = $entry['ga_bible_reader'];
    }
    
    $row[] = $entry['twi_bible_reader'];
    $row[] = $entry['english_bible_reader'];
    $row[] = toTitleCase($entry['remarks']);
    
    fputcsv($output, $row);
}

fclose($output);
exit;
