<?php
/**
 * Preaching Plan - printable report matching Word document format
 */

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

$year = isset($_GET['year']) ? (int)$_GET['year'] : date('Y');
$serviceType = $_GET['service_type'] ?? 'first-service';
// Support multiple service types
$serviceTypes = isset($_GET['service_types']) ? $_GET['service_types'] : [$serviceType];
if (!is_array($serviceTypes)) {
    $serviceTypes = [$serviceTypes];
}
$month = $_GET['month'] ?? null;

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

// Map service type values to display names
$serviceTypeNames = [
    'first-service' => 'FIRST SERVICE',
    'forenoon' => 'FORENOON',
    'joint-service' => 'JOINT SERVICE'
];

// Build display text for service types
if (count($serviceTypes) === 1) {
    $serviceTypeDisplay = $serviceTypeNames[$serviceTypes[0]] ?? strtoupper($serviceTypes[0]);
} else {
    $serviceTypeDisplay = implode(' / ', array_map(function($st) use ($serviceTypeNames) {
        return $serviceTypeNames[$st] ?? strtoupper($st);
    }, $serviceTypes));
}

// Get entries grouped by month - support multiple service types
$placeholders = str_repeat('?,', count($serviceTypes) - 1) . '?';
$where = "YEAR(service_date) = ? AND service_type IN ($placeholders)";
$params = array_merge([$year], $serviceTypes);

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);
$allEntries = $stmt->fetchAll();

// Group entries by month
$entriesByMonth = [];
foreach ($allEntries as $entry) {
    $monthKey = date('Y-m', strtotime($entry['service_date']));
    if (!isset($entriesByMonth[$monthKey])) {
        $entriesByMonth[$monthKey] = [];
    }
    $entriesByMonth[$monthKey][] = $entry;
}

// Determine date range for title
if ($month) {
    $monthName = date('F Y', strtotime($month . '-01'));
    $dateRange = strtoupper($monthName);
} else {
    if (!empty($allEntries)) {
        $startMonth = date('F', strtotime($allEntries[0]['service_date']));
        $endMonth = date('F', strtotime($allEntries[count($allEntries) - 1]['service_date']));
        if ($startMonth === $endMonth) {
            $dateRange = strtoupper($startMonth . ', ' . $year);
        } else {
            $dateRange = strtoupper($startMonth . ' – ' . $endMonth . ', ' . $year);
        }
    } else {
        $dateRange = strtoupper(date('F Y'));
    }
}

$pageTitle = 'Preaching Plan Report';
$currentPage = 'events';
require_once __DIR__ . '/../../includes/header.php';
?>

<style>
.preaching-plan-report {
    max-width: 100%;
    width: 100%;
    margin: 0;
    padding: 2rem;
}
.preaching-plan-report-wrapper {
    width: 100%;
    max-width: 100%;
    margin: 0;
    padding: 0;
}
.report-header {
    text-align: center;
    margin-bottom: 2rem;
    border-bottom: 3px solid #000;
    padding-bottom: 1.5rem;
}
.report-header .logo {
    height: 90px;
    margin-bottom: 1rem;
    object-fit: contain;
}
.report-header h1 {
    font-size: 1.375rem;
    font-weight: 700;
    margin: 0.75rem 0;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    line-height: 1.3;
}
.report-header .subtitle {
    font-size: 1rem;
    font-weight: 600;
    text-transform: uppercase;
    margin-top: 0.75rem;
    letter-spacing: 0.03em;
}
.preaching-plan-table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 2rem;
    font-size: 0.875rem;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.preaching-plan-table th {
    background-color: #2c3e50;
    color: #fff;
    border: 1px solid #1a252f;
    padding: 0.75rem 0.5rem;
    font-weight: 700;
    text-align: left;
    font-size: 0.8125rem;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}
.preaching-plan-table td {
    border: 1px solid #ddd;
    padding: 0.6rem 0.5rem;
    vertical-align: top;
    background-color: #fff;
}
.preaching-plan-table tbody tr:hover td {
    background-color: #f8f9fa;
}
.preaching-plan-table .month-header {
    background-color: #34495e;
    color: #fff;
    font-weight: 700;
    text-align: center;
    font-size: 0.9375rem;
    text-transform: uppercase;
    letter-spacing: 1px;
}
.preaching-plan-table .month-header td {
    background-color: #34495e;
    color: #fff;
    padding: 0.75rem;
}
.preaching-plan-table .date-cell {
    font-weight: 600;
    color: #2c3e50;
}
.preaching-plan-table .occasion-bold {
    font-weight: 700;
    color: #1a252f;
}

@media print {
    body {
        background: white;
    }
    .sidebar,
    .header-actions,
    .filter-bar,
    button,
    .btn,
    a[href] {
        display: none !important;
    }
    .main {
        margin: 0;
        padding: 0;
        max-width: 100%;
        width: 100%;
    }
    .preaching-plan-report {
        padding: 1.5cm;
        max-width: 100%;
        width: 100%;
    }
    .report-header {
        margin-bottom: 1.5rem;
        padding-bottom: 1rem;
    }
    .report-header .logo {
        height: 70px;
    }
    .preaching-plan-table {
        font-size: 0.75rem;
        box-shadow: none;
    }
    .preaching-plan-table th {
        background-color: #2c3e50 !important;
        color: #fff !important;
        -webkit-print-color-adjust: exact;
        print-color-adjust: exact;
    }
    .preaching-plan-table .month-header td {
        background-color: #34495e !important;
        color: #fff !important;
        -webkit-print-color-adjust: exact;
        print-color-adjust: exact;
    }
    .preaching-plan-table th,
    .preaching-plan-table td {
        padding: 0.4rem 0.3rem;
        border: 1px solid #000 !important;
    }
    .preaching-plan-table tbody tr:hover td {
        background-color: #fff !important;
    }
    @page {
        margin: 1.5cm;
        size: A4 landscape;
    }
}
</style>

<div class="preaching-plan-report-wrapper">
<div class="preaching-plan-report">
    <div class="report-header">
        <img src="<?= BASE_PATH ?>/public/img/logo.png" alt="PCG Logo" class="logo">
        <h1><?= htmlspecialchars(SITE_FULL_NAME) ?></h1>
        <div class="subtitle">PREACHING PLAN <?= $dateRange ?> <?= $serviceTypeDisplay ?></div>
    </div>

    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem; flex-wrap: wrap; gap: 1rem;">
        <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 1rem; max-width: 500px; width: 100%;">
            <a href="?year=<?= $year ?>&service_type=first-service<?= $month ? '&month=' . urlencode($month) : '' ?>" 
               style="display: block; text-decoration: none; color: <?= $serviceType === 'first-service' ? 'var(--primary)' : 'var(--text)' ?>; font-size: 0.9375rem; font-weight: <?= $serviceType === 'first-service' ? '600' : '400' ?>; padding: 0.75rem 1rem; text-align: center; border-bottom: <?= $serviceType === 'first-service' ? '2px solid var(--primary)' : '2px solid transparent' ?>; background: <?= $serviceType === 'first-service' ? '#f0f4f8' : 'transparent' ?>; border-radius: 4px 4px 0 0; transition: all 0.2s;">
                First Service
            </a>
            <a href="?year=<?= $year ?>&service_type=forenoon<?= $month ? '&month=' . urlencode($month) : '' ?>" 
               style="display: block; text-decoration: none; color: <?= $serviceType === 'forenoon' ? 'var(--primary)' : 'var(--text)' ?>; font-size: 0.9375rem; font-weight: <?= $serviceType === 'forenoon' ? '600' : '400' ?>; padding: 0.75rem 1rem; text-align: center; border-bottom: <?= $serviceType === 'forenoon' ? '2px solid var(--primary)' : '2px solid transparent' ?>; background: <?= $serviceType === 'forenoon' ? '#f0f4f8' : 'transparent' ?>; border-radius: 4px 4px 0 0; transition: all 0.2s;">
                Forenoon
            </a>
            <a href="?year=<?= $year ?>&service_type=joint-service<?= $month ? '&month=' . urlencode($month) : '' ?>" 
               style="display: block; text-decoration: none; color: <?= $serviceType === 'joint-service' ? 'var(--primary)' : 'var(--text)' ?>; font-size: 0.9375rem; font-weight: <?= $serviceType === 'joint-service' ? '600' : '400' ?>; padding: 0.75rem 1rem; text-align: center; border-bottom: <?= $serviceType === 'joint-service' ? '2px solid var(--primary)' : '2px solid transparent' ?>; background: <?= $serviceType === 'joint-service' ? '#f0f4f8' : 'transparent' ?>; border-radius: 4px 4px 0 0; transition: all 0.2s;">
                Joint Service
            </a>
        </div>
        <button type="button" onclick="window.print()" class="btn">Print</button>
    </div>

    <table class="preaching-plan-table">
        <thead>
            <tr>
                <th style="width: <?= $serviceType === 'first-service' ? '8%' : '7%' ?>;">DATE</th>
                <th style="width: <?= $serviceType === 'first-service' ? '18%' : '15%' ?>;">OCCASSION</th>
                <th style="width: <?= $serviceType === 'first-service' ? '18%' : '15%' ?>;">PREACHER</th>
                <th style="width: <?= $serviceType === 'first-service' ? '18%' : '15%' ?>;">LITURGIST</th>
                <?php if ($serviceType !== 'first-service'): ?>
                <th style="width: 15%;">GA BIBLE READER</th>
                <?php endif; ?>
                <th style="width: <?= $serviceType === 'first-service' ? '18%' : '15%' ?>;">TWI BIBLE READER</th>
                <th style="width: <?= $serviceType === 'first-service' ? '18%' : '15%' ?>;">ENGLISH BIBLE READER</th>
                <th style="width: <?= $serviceType === 'first-service' ? '8%' : '7%' ?>;">REMARKS</th>
            </tr>
        </thead>
        <tbody>
            <?php 
            $currentMonthNum = null;
            foreach ($entriesByMonth as $monthKey => $monthEntries): 
                $monthNum = (int)substr($monthKey, 5, 2);
                $monthName = strtoupper(date('F', strtotime($monthKey . '-01')));
            ?>
            <tr class="month-header">
                <td colspan="<?= $serviceType === 'first-service' ? '7' : '8' ?>"><?= $monthName ?></td>
            </tr>
            <?php foreach ($monthEntries as $entry): 
                $dayNum = date('j', strtotime($entry['service_date']));
                $daySuffix = strtoupper(date('S', strtotime($entry['service_date'])));
                $occasion = $entry['occasion'] ?: '';
                $isBoldOccasion = preg_match('/BIBLE|SUNDAY|YOUTH|STUDENT|PALM|ASH|EPIPHANY|COMMUNION|COVENANT/i', $occasion);
            ?>
            <tr>
                <td class="date-cell"><?= $dayNum ?><?= $daySuffix ?></td>
                <td class="<?= $isBoldOccasion ? 'occasion-bold' : '' ?>"><?= htmlspecialchars(toTitleCase($occasion)) ?></td>
                <td><?= htmlspecialchars($entry['preacher'] ?: '—') ?></td>
                <td><?= htmlspecialchars($entry['liturgist'] ?: '—') ?></td>
                <?php if ($serviceType !== 'first-service'): ?>
                <td><?= htmlspecialchars($entry['ga_bible_reader'] ?: '—') ?></td>
                <?php endif; ?>
                <td><?= htmlspecialchars($entry['twi_bible_reader'] ?: '—') ?></td>
                <td><?= htmlspecialchars($entry['english_bible_reader'] ?: '—') ?></td>
                <td><?= htmlspecialchars(toTitleCase($entry['remarks'])) ?></td>
            </tr>
            <?php endforeach; ?>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>
</div>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
