<?php
// pages/worship_reports.php
requireRole('any');

// Filters
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';
$type_filter = isset($_GET['type_filter']) ? $_GET['type_filter'] : '';

// Build Query
$sql = "SELECT `id`, `service_date`, `ds_sermon_preacher` as preacher, `ds_sermon_title` as topic, `att_devotional_t` as attendance FROM `worship_reports` WHERE 1=1";
$params = [];

if ($date_from) {
    $sql .= " AND service_date >= ?";
    $params[] = $date_from;
}
if ($date_to) {
    $sql .= " AND service_date <= ?";
    $params[] = $date_to;
}

$sql .= " ORDER BY service_date DESC LIMIT 50";

try {
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $reports = $stmt->fetchAll();
} catch (PDOException $e) {
    if (strpos($e->getMessage(), 'ds_sermon_preacher') !== false) {
        die("
            <div style='background:#C00; color:#FFF; padding:30px; border-radius:10px; text-align:center; margin:50px;'>
                <h2>Database Sync Error</h2>
                <p>It looks like your database is missing some new features (V2 columns).</p>
                <p>This usually happens after a Restore. Click the button below to fix it instantly.</p>
                <br>
                <a href='repair.php' style='background:#FFF; color:#000; padding:15px 30px; text-decoration:none; border-radius:5px; font-weight:bold;'>Repair Database Schema</a>
            </div>
        ");
    }
    throw $e;
}

// Handle Delete
if (isset($_GET['delete_id'])) {
    requireRole('admin');
    $delStmt = $pdo->prepare("DELETE FROM worship_reports WHERE id = ?");
    if ($delStmt->execute([$_GET['delete_id']])) {
        redirect('index.php?page=worship_reports&msg=Report deleted successfully.');
    } else {
        redirect('index.php?page=worship_reports&error=Failed to delete report.');
    }
}
?>

<div style="display: flex; justify-content: space-between; align-items: center;">
    <h1>Worship Reports</h1>
    <div style="display: flex; gap: 10px;">
        <a href="index.php?page=worship_review" class="btn" style="background: transparent; border: 1px solid #444;">
            <i class="fas fa-file-invoice"></i> Review Summary
        </a>
        <a href="index.php?page=worship_report_form" class="btn">Create New Report</a>
    </div>
</div>

<div class="card" style="margin-top: 20px;">
    <!-- Filters -->
    <form method="GET" style="display: flex; gap: 15px; flex-wrap: wrap; margin-bottom: 20px; border-bottom: 1px solid #444; padding-bottom: 15px;">
        <input type="hidden" name="page" value="worship_reports">
        <div>
            <label style="font-size: 0.8rem; color: #888;">From Date</label>
            <input type="date" name="date_from" class="form-control" style="padding: 5px;" value="<?php echo htmlspecialchars($date_from); ?>">
        </div>
        <div>
            <label style="font-size: 0.8rem; color: #888;">To Date</label>
            <input type="date" name="date_to" class="form-control" style="padding: 5px;" value="<?php echo htmlspecialchars($date_to); ?>">
        </div>
        <div style="display: flex; align-items: flex-end;">
            <button type="submit" class="btn" style="padding: 6px 15px;">Filter</button>
            <?php if($date_from || $date_to): ?>
                <a href="index.php?page=worship_reports" class="btn" style="background: #666; margin-left: 5px; padding: 6px 15px;">Clear</a>
            <?php endif; ?>
        </div>
    </form>

    <div class="table-responsive">
        <table>
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Devotional Preacher</th>
                    <th>Sermon Topic</th>
                    <th style="text-align: center;">Devotional Att.</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($reports)): ?>
                <tr><td colspan="5" style="text-align: center; padding: 20px;">No reports found.</td></tr>
                <?php else: ?>
                    <?php foreach ($reports as $r): ?>
                    <tr>
                        <td>
                            <strong><?php echo date('M j, Y', strtotime($r['service_date'])); ?></strong><br>
                            <small style="color: #888;"><?php echo date('l', strtotime($r['service_date'])); ?></small>
                        </td>
                        <td><?php echo htmlspecialchars($r['preacher'] ?: '-'); ?></td>
                        <td><?php echo htmlspecialchars($r['topic'] ?: '-'); ?></td>
                        <td style="text-align: center;">
                            <span class="badge" style="background: #333; font-size: 1rem;"><?php echo $r['attendance']; ?></span>
                        </td>
                        <td>
                            <a href="index.php?page=worship_report_form&id=<?php echo $r['id']; ?>" class="btn" style="padding: 5px 10px; font-size: 0.8rem; margin-right: 5px;">Edit</a>
                            <a href="index.php?page=worship_report_view&id=<?php echo $r['id']; ?>" class="btn" style="padding: 5px 10px; font-size: 0.8rem; background: var(--success-color); color:#000;">View</a>
                            <a href="index.php?page=worship_reports&delete_id=<?php echo $r['id']; ?>" class="btn" style="padding: 5px 10px; font-size: 0.8rem; background: var(--danger-color);" onclick="return confirm('Delete this report?')">Delete</a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>
