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

$mode = isset($_GET['mode']) ? $_GET['mode'] : 'monthly'; // 'monthly' or 'quarterly'
$view = isset($_GET['view']) ? $_GET['view'] : 'detailed'; // 'detailed' (grid) or 'summary' (service list)
$month = isset($_GET['month']) ? $_GET['month'] : date('Y-m');
$year = isset($_GET['year']) ? (int)$_GET['year'] : (int)date('Y');
$quarter = isset($_GET['quarter']) ? (int)$_GET['quarter'] : (int)ceil(date('n')/3);

$title = "";
$date_query = "";
$params = [];

if ($mode === 'monthly') {
    $monthName = date('F Y', strtotime($month . "-01"));
    $title = "Monthly Attendance: " . $monthName;
    $date_query = "DATE_FORMAT(service_date, '%Y-%m') = ?";
    $params[] = $month;
} else {
    $title = "Quarterly Attendance: Q$quarter $year";
    $start_month = ($quarter - 1) * 3 + 1;
    $end_month = $start_month + 2;
    $start_date = "$year-" . str_pad($start_month, 2, '0', STR_PAD_LEFT) . "-01";
    $end_date = date("Y-m-t", strtotime("$year-" . str_pad($end_month, 2, '0', STR_PAD_LEFT) . "-01"));
    $date_query = "service_date BETWEEN ? AND ?";
    $params[] = $start_date;
    $params[] = $end_date;
}

// Fetch all services in this period
$services_stmt = $pdo->prepare("SELECT id, type, service_date, service_time FROM services WHERE $date_query ORDER BY service_date ASC");
$services_stmt->execute($params);
$services = $services_stmt->fetchAll();
$total_services = count($services);

// Fetch members (needed for absent calculation) - EXCLUDING Visitors and Non-Available statuses
$members = $pdo->query("SELECT id FROM members WHERE unit != 'Visitor' AND status = 'Available'")->fetchAll();
$total_members = count($members);

// -- LOGIC FOR SUMMARY VIEW --
$summary_data = [];
if ($view === 'summary' && !empty($services)) {
    foreach ($services as $s) {
        // Count statuses for this specific service
        $stmt = $pdo->prepare("
            SELECT 
                SUM(CASE WHEN was_late = 0 THEN 1 ELSE 0 END) as early_count,
                SUM(CASE WHEN was_late = 1 THEN 1 ELSE 0 END) as late_count,
                COUNT(*) as total_present
            FROM attendance 
            WHERE DATE(in_time) = ?
        ");
        $stmt->execute([$s['service_date']]);
        $res = $stmt->fetch();
        
        $early = (int)$res['early_count'];
        $late = (int)$res['late_count'];
        $present = (int)$res['total_present'];
        // Absent = Total Members - Present? Or use specific absent records? 
        // Let's use Total Members - Present to be consistent with "Turnout %" usually being based on available members.
        // However, if there are 'absent' records in member_attendance, we could check that.
        // For simplicity and robustness relative to the Grid logic, we'll use Total Available - Present.
        $absent = max(0, $total_members - $present);
        
        $summary_data[] = [
            'date' => $s['service_date'],
            'type' => $s['type'],
            'present' => $present,
            'early' => $early,
            'late' => $late,
            'absent' => $absent,
            'turnout' => $total_members > 0 ? round(($present / $total_members) * 100) : 0
        ];
    }
}

// -- LOGIC FOR DETAILED GRID VIEW --
$attendance_grid = [];
if ($view === 'detailed' && !empty($services)) {
    // ... (Existing Grid Logic) ...
    $dates = array_column($services, 'service_date');
    if(!empty($dates)){
        $placeholders = str_repeat('?,', count($dates) - 1) . '?';
        $att_stmt = $pdo->prepare("SELECT member_id, DATE(in_time) as att_date, was_late FROM attendance WHERE DATE(in_time) IN ($placeholders)");
        $att_stmt->execute($dates);
        while ($row = $att_stmt->fetch()) {
            $attendance_grid[$row['member_id']][$row['att_date']] = $row['was_late'] ? 'late' : 'present';
        }
    }
    // Fetch full member details for grid - EXCLUDING Visitors and Non-Available statuses
    $members_full = $pdo->query("SELECT id, full_name, unit, status FROM members WHERE unit != 'Visitor' AND status = 'Available' ORDER BY full_name ASC")->fetchAll();
    
    // Recalculate Stats for Grid Header
    $present_count = 0; $late_count = 0;
    foreach ($attendance_grid as $m_id => $dates_att) {
        foreach ($dates_att as $date => $status) {
            if ($status == 'present' || $status == 'late') $present_count++;
            if ($status == 'late') $late_count++;
        }
    }
    $total_possible = $total_services * count($members_full);
    $avg_attendance = $total_possible > 0 ? round(($present_count / $total_possible) * 100, 1) : 0;
    $late_rate = $present_count > 0 ? round(($late_count / $present_count) * 100, 1) : 0;
} else {
    // Basic stats for Summary View (Average of summary)
    $avg_attendance = 0; $late_rate = 0;
    if (!empty($summary_data)) {
        $tot_p = 0; $tot_l = 0;
        foreach($summary_data as $row) { $tot_p += $row['present']; $tot_l += $row['late']; }
        $avg_attendance = ($total_services * $total_members) > 0 ? round(($tot_p / ($total_services * $total_members)) * 100, 1) : 0;
        $late_rate = $tot_p > 0 ? round(($tot_l / $tot_p) * 100, 1) : 0;
    }
}

// Count Sunday vs Other Services
$sunday_count = 0; $other_count = 0;
foreach ($services as $s) {
    if (date('w', strtotime($s['service_date'])) == 0) $sunday_count++; else $other_count++;
}
?>

<div class="report-header no-print">
    <div style="display: flex; justify-content: space-between; align-items: flex-start; flex-wrap: wrap; gap: 15px;">
        <div>
            <h1 style="margin: 0;"><?php echo $mode === 'monthly' ? 'Monthly' : 'Quarterly'; ?> Attendance</h1>
            <p style="color: #888; margin-top: 5px;"><?php echo $title; ?></p>
        </div>
        <div class="filter-controls" style="display: flex; flex-direction: column; gap: 10px; align-items: flex-end;">
            <form method="GET" style="display: flex; gap: 10px; align-items: center;">
                <input type="hidden" name="page" value="attendance_monthly">
                
                <!-- View Toggle -->
                <div class="btn-group">
                    <button type="submit" name="view" value="detailed" class="btn" style="<?php echo $view=='detailed'?'background:#444;':'background:transparent;border:1px solid #444;'; ?>">Detailed Grid</button>
                    <button type="submit" name="view" value="summary" class="btn" style="<?php echo $view=='summary'?'background:#444;':'background:transparent;border:1px solid #444;'; ?>">Service Summary</button>
                </div>

                <div style="border-left: 1px solid #444; height: 30px; margin: 0 5px;"></div>

                <select name="mode" class="form-control" onchange="this.form.submit()" style="width: auto;">
                    <option value="monthly" <?php if($mode=='monthly') echo 'selected'; ?>>Monthly</option>
                    <option value="quarterly" <?php if($mode=='quarterly') echo 'selected'; ?>>Quarterly</option>
                </select>
                
                <?php if ($mode === 'monthly'): ?>
                    <input type="month" name="month" class="form-control" value="<?php echo $month; ?>" onchange="this.form.submit()">
                <?php else: ?>
                    <select name="quarter" class="form-control" onchange="this.form.submit()" style="width: auto;">
                        <option value="1" <?php if($quarter==1) echo 'selected'; ?>>Q1</option>
                        <option value="2" <?php if($quarter==2) echo 'selected'; ?>>Q2</option>
                        <option value="3" <?php if($quarter==3) echo 'selected'; ?>>Q3</option>
                        <option value="4" <?php if($quarter==4) echo 'selected'; ?>>Q4</option>
                    </select>
                    <input type="number" name="year" class="form-control" value="<?php echo $year; ?>" onchange="this.form.submit()" style="width: 80px;">
                <?php endif; ?>
            </form>
            <div style="display: flex; gap: 5px;">
                <button onclick="window.print()" class="btn" style="background: #444;"><i class="fas fa-print"></i> Print PDF</button>
                <button onclick="exportReportImage(this)" class="btn" style="background: var(--success-color); color: #000;"><i class="fas fa-image"></i> Export Image</button>
            </div>
        </div>
    </div>
</div>

<div id="report-capture-area" class="capture-zone">
    <!-- Print Header -->
    <div class="print-only" style="text-align: center; margin-bottom: 20px;">
        <h1 style="margin:0; font-size: 20px;">APOSTOLIC FAITH CHURCH</h1>
        <h2 style="margin:0; font-size: 16px;">WCS WECA (Anthony)</h2>
        <h2 style="margin:5px 0; font-size: 16px;"><?php echo strtoupper($title); ?> - <?php echo strtoupper($view); ?> REPORT</h2>
        <p style="font-size: 10px; color: #666;">Generated on <?php echo date('Y-m-d H:i'); ?></p>
    </div>

    <!-- Stats Cards (Shared) -->
    <div class="dashboard-grid" style="margin-bottom: 15px; grid-template-columns: repeat(4, 1fr); gap: 10px;">
        <div class="card stat-card compact">
            <div class="stat-icon-small" style="color: var(--primary-color);"><i class="fas fa-calendar-day"></i></div>
            <div class="stat-info"><span class="stat-label">Sunday Svcs</span><span class="stat-value"><?php echo $sunday_count; ?></span></div>
        </div>
        <div class="card stat-card compact">
            <div class="stat-icon-small" style="color: #6366f1;"><i class="fas fa-church"></i></div>
            <div class="stat-info"><span class="stat-label">Other Svcs</span><span class="stat-value"><?php echo $other_count; ?></span></div>
        </div>
        <div class="card stat-card compact">
            <div class="stat-icon-small" style="color: #22c55e;"><i class="fas fa-users"></i></div>
            <div class="stat-info"><span class="stat-label">Avg Turnout</span><span class="stat-value"><?php echo round($avg_attendance); ?>%</span></div>
        </div>
        <div class="card stat-card compact">
            <div class="stat-icon-small" style="color: #f59e0b;"><i class="fas fa-clock"></i></div>
            <div class="stat-info"><span class="stat-label">Lateness</span><span class="stat-value"><?php echo round($late_rate); ?>%</span></div>
        </div>
    </div>

    <!-- REPORT CONTENT BASED ON VIEW -->
    <?php if ($view === 'summary'): ?>
        
        <div class="card report-card-main">
            <div class="table-responsive">
                <table class="report-table compact" style="width: 100%;">
                    <thead>
                        <tr style="background: #222;">
                            <th style="text-align: left; padding: 10px;">Date</th>
                            <th style="padding: 10px;">Service</th>
                            <th style="padding: 10px;">Attendance</th>
                            <th style="padding: 10px; color: var(--success-color);">Early</th>
                            <th style="padding: 10px; color: #ffeb3b;">Late</th>
                            <th style="padding: 10px; color: var(--danger-color);">Absent*</th>
                            <th style="padding: 10px;">Turnout</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(empty($summary_data)): ?>
                            <tr><td colspan="7" class="text-center">No services found for this period.</td></tr>
                        <?php else: ?>
                            <?php foreach ($summary_data as $row): ?>
                            <tr>
                                <td style="padding: 8px;">
                                    <strong><?php echo date('M j, Y', strtotime($row['date'])); ?></strong><br>
                                    <small style="color:#888;"><?php echo date('l', strtotime($row['date'])); ?></small>
                                </td>
                                <td style="padding: 8px;"><?php echo htmlspecialchars($row['type']); ?></td>
                                <td style="text-align: center; font-weight: bold; font-size: 1.1rem; padding: 8px;"><?php echo $row['present']; ?></td>
                                <td style="text-align: center; color: var(--success-color) !important; padding: 8px;"><?php echo $row['early']; ?></td>
                                <td style="text-align: center; color: #ffd700 !important; padding: 8px;"><?php echo $row['late']; ?></td>
                                <td style="text-align: center; color: var(--danger-color) !important; padding: 8px;"><?php echo $row['absent']; ?></td>
                                <td style="text-align: center; padding: 8px;">
                                    <span class="badge turnout-badge-stat"><?php echo $row['turnout']; ?>%</span>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <!-- Totals Row -->
                             <tr style="background: #333; font-weight: bold;">
                                <td colspan="2" style="text-align: right; padding: 8px;">TOTALS / AVG:</td>
                                <td style="text-align: center; padding: 8px;"><?php echo array_sum(array_column($summary_data, 'present')); ?></td>
                                <td style="text-align: center; padding: 8px; color: var(--success-color) !important;"><?php echo array_sum(array_column($summary_data, 'early')); ?></td>
                                <td style="text-align: center; padding: 8px; color: #ffd700 !important;"><?php echo array_sum(array_column($summary_data, 'late')); ?></td>
                                <td style="text-align: center; padding: 8px; color: var(--danger-color) !important;"><?php echo array_sum(array_column($summary_data, 'absent')); ?></td>
                                <td style="text-align: center; padding: 8px;"><?php echo round($avg_attendance); ?>%</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <div style="font-size: 0.8rem; color: #888; margin-top: 5px;">* Absent count is calculated based on total available members (<?php echo $total_members; ?>) minus present members.</div>

    <?php else: ?>
        <!-- EXISTING DETAILED GRID VIEW -->
        <div class="card report-card-main">
            <div class="table-responsive">
                <table class="report-table compact">
                    <thead>
                        <tr>
                            <th style="width: 30px;" class="text-center">S/N</th>
                            <th class="sticky-col">Member Name</th>
                            <th class="hide-mobile">Unit</th>
                            <?php foreach ($services as $s): ?>
                                <th class="text-center">
                                    <small><?php echo date('d', strtotime($s['service_date'])); ?></small>
                                </th>
                            <?php endforeach; ?>
                            <th class="text-center score-col">%</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $sn = 1; foreach ($members_full as $m): ?>
                            <?php 
                                $m_present = 0;
                                $m_late = 0;
                            ?>
                            <tr>
                                <td class="text-center"><small><?php echo $sn++; ?></small></td>
                                <td class="sticky-col">
                                    <strong><?php echo htmlspecialchars($m['full_name']); ?></strong>
                                </td>
                                <td class="hide-mobile"><small><?php echo htmlspecialchars($m['unit']); ?></small></td>
                                <?php foreach ($services as $s): ?>
                                    <td class="text-center">
                                        <?php 
                                            $status = $attendance_grid[$m['id']][$s['service_date']] ?? 'absent';
                                            if ($status == 'late') {
                                                echo '<span class="att-dot late">L</span>';
                                                $m_present++; $m_late++;
                                            } elseif ($status == 'present') {
                                                echo '<span class="att-dot present">P</span>';
                                                $m_present++;
                                            } else {
                                                // Handle other statuses for history if needed, 
                                                // but for this grid view, these members are already filter-limited to 'Available'
                                                echo '<span class="att-dot absent">A</span>';
                                            }
                                        ?>
                                    </td>
                                <?php endforeach; ?>
                                <td class="text-center score-col">
                                    <?php echo $total_services > 0 ? round(($m_present / $total_services) * 100) : 0; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <!-- Summary / Legend within Capture Area -->
        <div class="report-summary-footer">
            <div style="font-weight: bold; border-bottom: 1px solid #444; margin-bottom: 8px; padding-bottom: 3px; font-size: 0.8rem;">Status Definitions & Legend</div>
            <div class="legend-grid">
                <div class="legend-item">
                    <span class="att-dot present">P</span>
                    <div><strong>Present:</strong> <span>Arrived before 7:30 AM</span></div>
                </div>
                <div class="legend-item">
                    <span class="att-dot late">L</span>
                    <div><strong>Late:</strong> <span>Arrived after 7:30 AM</span></div>
                </div>
                <div class="legend-item">
                    <span class="att-dot absent">A</span>
                    <div><strong>Absent:</strong> <span>Did not mark attendance / Was not in service</span></div>
                </div>
            </div>
        </div>
    <?php endif; ?>

</div>

<!-- Legend Tips (Visible only on Screen) -->
<div style="margin-top: 15px; color: #888;" class="no-print">
    <small><i class="fas fa-info-circle"></i> This report is optimized for single-page PDF/Image export. Definitions are included in the footer above.</small>
</div>

<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
<script>
async function exportReportImage(btn) {
    const area = document.getElementById('report-capture-area');
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Generating...';

    try {
        const canvas = await html2canvas(area, {
            scale: 2,
            backgroundColor: '#ffffff', // Force white background for JPEG
            useCORS: true,
            onclone: (clonedDoc) => {
                const captureArea = clonedDoc.getElementById('report-capture-area');
                captureArea.querySelectorAll('.print-only').forEach(el => el.style.display = 'block');
                captureArea.style.background = '#ffffff';
                captureArea.style.color = '#000000';
                captureArea.querySelectorAll('.card').forEach(c => {
                    c.style.background = '#ffffff';
                    c.style.color = '#000000';
                    c.style.border = '1px solid #eee';
                });
                captureArea.querySelectorAll('table, tr, td, th').forEach(el => {
                    el.style.background = '#ffffff';
                });
                captureArea.querySelectorAll('td, th').forEach(c => {
                    // Overwrite color ONLY if it's not an inline status color
                    const inlineColor = c.style.color;
                    if (!inlineColor || (!inlineColor.includes('var') && !inlineColor.includes('#'))) {
                        c.style.color = '#000000';
                    }
                    
                    c.style.borderColor = '#dddddd';
                    c.style.borderStyle = 'solid';
                    c.style.borderWidth = '1px';
                });
                // Specifically re-force status colors if they are inside spans (like att-dot)
                captureArea.querySelectorAll('.att-dot').forEach(dot => {
                    dot.style.display = 'flex';
                    dot.style.webkitPrintColorAdjust = 'exact';
                });
                captureArea.querySelectorAll('.badge').forEach(b => {
                    b.style.background = '#eeeeee';
                    b.style.color = '#000000';
                    b.style.border = '1px solid #cccccc';
                });
                captureArea.querySelectorAll('.stat-value').forEach(c => c.style.color = '#000000');
                captureArea.querySelectorAll('.stat-label').forEach(c => c.style.color = '#666666');
                const footer = captureArea.querySelector('.report-summary-footer');
                if (footer) {
                    footer.style.borderColor = '#eee';
                    footer.style.color = '#000000';
                }
            }
        });
        const link = document.createElement('a');
        const safeTitle = "<?php echo $title; ?>".replace(/[^a-z0-9]/gi, '_').toLowerCase();
        link.download = `Attendance-${safeTitle}.jpg`;
        link.href = canvas.toDataURL('image/jpeg', 0.9);
        link.click();
    } catch (err) {
        console.error(err);
        alert('Image export failed');
    } finally {
        btn.disabled = false;
        btn.innerHTML = '<i class="fas fa-image"></i> Export Image';
    }
}
</script>

<style>
    .report-header { margin-bottom: 15px; }
    .capture-zone { background: #111; padding: 10px; border-radius: 8px; }
    
    .stat-card.compact { padding: 8px 12px; flex-direction: row; justify-content: flex-start; gap: 8px; }
    .stat-icon-small { font-size: 0.9rem; width: 25px; }
    .stat-label { font-size: 0.55rem; margin-bottom: 1px; }
    .stat-value { font-size: 1rem; line-height: 1; }
    .turnout-badge-stat { background: #333; color: #fff; }
    
    .report-card-main { padding: 0; overflow: hidden; background: #222; border: 1px solid #444; margin-bottom: 15px; }
    .report-table.compact { width: 100%; border-collapse: collapse; border: 1px solid #444; }
    .report-table.compact th, .report-table.compact td { padding: 4px 2px; border: 1px solid #333; font-size: 0.7rem; }
    .report-table.compact th { color: #888; text-transform: uppercase; font-weight: normal; background: #222; border-bottom: 1px solid #444; }
    
    .sticky-col { position: sticky; left: 0; background: #222; z-index: 5; border-right: 1px solid #333; min-width: 120px; max-width: 150px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
    th.sticky-col { background: #222; }

    .report-summary-footer { margin-top: 10px; padding: 10px; border: 1px solid #333; border-radius: 6px; background: rgba(255,255,255,0.02); }
    .legend-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; }
    .legend-item { display: flex; align-items: center; gap: 8px; font-size: 0.65rem; }
    .legend-item strong { display: block; }
    .legend-item span { color: #888; }
    
    .score-col { background: rgba(255,255,255,0.03); font-weight: bold; width: 35px; font-size: 0.65rem; }
    
    .text-center { text-align: center !important; }
    
    .att-dot {
        width: 16px;
        height: 16px;
        border-radius: 2px;
        display: flex;
        font-size: 0.55rem;
        margin: 0 auto;
        align-items: center;
        justify-content: center;
        font-weight: 800;
    }
    
    .att-dot.present { background: #22c55e; color: #000; }
    .att-dot.late { background: #dfdf00; color: #000; }
    .att-dot.absent { background: #ef4444; color: #fff; }
    
    .print-only { display: none; }

    @media print {
        header, nav, .no-print { display: none !important; }
        .container { width: 100% !important; max-width: none !important; margin: 0 !important; padding: 0 !important; }
        .print-only { display: block !important; }
        .capture-zone { background: #fff !important; padding: 0 !important; }
        body { 
            background: #fff !important; 
            color: #000 !important; 
            -webkit-print-color-adjust: exact !important; 
            print-color-adjust: exact !important; 
        }
        .card { border: 1px solid #eee !important; background: #fff !important; box-shadow: none !important; }
        .report-table.compact { background: #fff !important; color: #000 !important; border: 1px solid #ccc !important; }
        .report-table.compact th, .report-table.compact td { 
            border: 1px solid #ccc !important; 
            color: #000 !important; 
            padding: 2px 1px !important; 
            background: #fff !important; 
            -webkit-print-color-adjust: exact !important;
            print-color-adjust: exact !important;
        }
        .sticky-col { background: #fff !important; min-width: 100px !important; border-right: 1px solid #ccc !important; }
        .score-col { background: #f9f9f9 !important; }
        .report-summary-footer { border: 1px solid #eee !important; color: #000 !important; background: #fff !important; }
        .att-dot { 
            width: 14px; 
            height: 14px; 
            font-size: 0.5rem; 
            -webkit-print-color-adjust: exact !important;
            print-color-adjust: exact !important;
        }
        .att-dot.present { background: #22c55e !important; color: #000 !important; border: none !important; }
        .att-dot.late { background: #dfdf00 !important; color: #000 !important; border: none !important; }
        .att-dot.absent { background: #ef4444 !important; color: #fff !important; border: none !important; }
        .badge { background: #eee !important; color: #000 !important; border: 1px solid #ccc !important; }
    }

    @media (max-width: 768px) {
        .hide-mobile { display: none; }
        .stat-value { font-size: 1rem; }
    }
</style>
