<?php
/**
 * Preaching Plan - Broadcast/Notification view
 */

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

$year = isset($_GET['year']) ? (int)$_GET['year'] : date('Y');
$serviceTypes = isset($_GET['service_types']) ? $_GET['service_types'] : ['first-service'];
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 WHERE clause for 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, service_type ASC
");
$stmt->execute($params);
$allEntries = $stmt->fetchAll();

// Group entries by date
$entriesByDate = [];
foreach ($allEntries as $entry) {
    $dateKey = $entry['service_date'];
    if (!isset($entriesByDate[$dateKey])) {
        $entriesByDate[$dateKey] = [];
    }
    $entriesByDate[$dateKey][] = $entry;
}

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

<style>
.broadcast-container {
    max-width: 900px;
    margin: 0 auto;
}
.broadcast-filter {
    background: var(--white);
    border-radius: 6px;
    padding: 1.5rem;
    border: 1px solid var(--border);
    margin-bottom: 1.5rem;
}
.broadcast-entry {
    background: var(--white);
    border-radius: 6px;
    padding: 1.5rem;
    border: 1px solid var(--border);
    margin-bottom: 1rem;
}
.broadcast-date {
    font-size: 1.25rem;
    font-weight: 600;
    margin-bottom: 0.75rem;
    color: var(--primary);
}
.broadcast-service {
    margin-bottom: 1rem;
    padding-bottom: 1rem;
    border-bottom: 1px solid #eee;
}
.broadcast-service:last-child {
    border-bottom: none;
    margin-bottom: 0;
    padding-bottom: 0;
}
.broadcast-service-type {
    font-weight: 600;
    color: var(--text);
    margin-bottom: 0.5rem;
}
.broadcast-field {
    margin-bottom: 0.5rem;
}
.broadcast-field-label {
    font-weight: 600;
    display: inline-block;
    min-width: 120px;
}
</style>

<div class="header">
    <h1>Preaching Plan - Broadcast</h1>
    <div class="header-actions">
        <a href="<?= BASE_PATH ?>/events/preaching-plan" class="btn btn-secondary">Back to Preaching Plan</a>
        <a href="<?= BASE_PATH ?>/logout">Logout</a>
    </div>
</div>

<div class="broadcast-container">
    <div class="broadcast-filter">
        <h2 style="margin-top: 0;">Filter Services</h2>
        <form method="get" style="display: flex; flex-direction: column; gap: 1rem;">
            <div style="display: flex; gap: 1rem; flex-wrap: wrap;">
                <div style="flex: 1; min-width: 150px;">
                    <label>Year:</label>
                    <select name="year" style="width: 100%;">
                        <?php for ($y = date('Y') - 1; $y <= date('Y') + 1; $y++): ?>
                        <option value="<?= $y ?>" <?= $year == $y ? 'selected' : '' ?>><?= $y ?></option>
                        <?php endfor; ?>
                    </select>
                </div>
                <div style="flex: 1; min-width: 150px;">
                    <label>Month (optional):</label>
                    <input type="month" name="month" value="<?= htmlspecialchars($month ?? '') ?>" style="width: 100%;">
                </div>
            </div>
            <div>
                <label style="display: block; margin-bottom: 0.5rem;">Service Types:</label>
                <div style="display: flex; gap: 1rem; flex-wrap: wrap;">
                    <?php foreach ($serviceTypeNames as $value => $label): ?>
                    <label style="display: flex; align-items: center; gap: 0.5rem;">
                        <input type="checkbox" name="service_types[]" value="<?= htmlspecialchars($value) ?>" 
                            <?= in_array($value, $serviceTypes) ? 'checked' : '' ?>>
                        <span><?= htmlspecialchars($label) ?></span>
                    </label>
                    <?php endforeach; ?>
                </div>
            </div>
            <button type="submit" class="btn">Apply Filters</button>
        </form>
    </div>

    <?php if (empty($entriesByDate)): ?>
    <p class="text-muted">No entries found for the selected filters.</p>
    <?php else: ?>
    <?php foreach ($entriesByDate as $date => $dateEntries): ?>
    <div class="broadcast-entry">
        <div class="broadcast-date">
            <?= date('l, F j, Y', strtotime($date)) ?>
        </div>
        <?php foreach ($dateEntries as $entry): ?>
        <div class="broadcast-service">
            <div class="broadcast-service-type">
                <?= htmlspecialchars($serviceTypeNames[$entry['service_type']] ?? $entry['service_type']) ?>
                <?php if ($entry['occasion']): ?>
                    - <?= htmlspecialchars(toTitleCase($entry['occasion'])) ?>
                <?php endif; ?>
            </div>
            <?php if ($entry['preacher']): ?>
            <div class="broadcast-field">
                <span class="broadcast-field-label">Preacher:</span>
                <?= htmlspecialchars($entry['preacher']) ?>
            </div>
            <?php endif; ?>
            <?php if ($entry['liturgist']): ?>
            <div class="broadcast-field">
                <span class="broadcast-field-label">Liturgist:</span>
                <?= htmlspecialchars($entry['liturgist']) ?>
            </div>
            <?php endif; ?>
            <?php if ($entry['service_type'] !== 'first-service' && $entry['ga_bible_reader']): ?>
            <div class="broadcast-field">
                <span class="broadcast-field-label">Ga Bible Reader:</span>
                <?= htmlspecialchars($entry['ga_bible_reader']) ?>
            </div>
            <?php endif; ?>
            <?php if ($entry['twi_bible_reader']): ?>
            <div class="broadcast-field">
                <span class="broadcast-field-label">Twi Bible Reader:</span>
                <?= htmlspecialchars($entry['twi_bible_reader']) ?>
            </div>
            <?php endif; ?>
            <?php if ($entry['english_bible_reader']): ?>
            <div class="broadcast-field">
                <span class="broadcast-field-label">English Bible Reader:</span>
                <?= htmlspecialchars($entry['english_bible_reader']) ?>
            </div>
            <?php endif; ?>
            <?php if ($entry['remarks']): ?>
            <div class="broadcast-field">
                <span class="broadcast-field-label">Remarks:</span>
                <?= htmlspecialchars(toTitleCase($entry['remarks'])) ?>
            </div>
            <?php endif; ?>
        </div>
        <?php endforeach; ?>
    </div>
    <?php endforeach; ?>
    <?php endif; ?>
</div>

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