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

// Helpers for Date Logic
$nov2025 = '2025-11-01'; // Absenteeism Start Date

// Function removed - now in includes/functions.php

// Stats for General Tab
$last4Services = $pdo->query("SELECT event_date, COUNT(*) as count FROM member_attendance WHERE status IN ('present','late') GROUP BY event_date ORDER BY event_date DESC LIMIT 4")->fetchAll();

// ABSENTEEISM LOGIC
// "Absent for 4 consecutive Sundays" (starting from Nov 2025)
// 1. Get all Sundays in the past 4 months
$sundays = [];
$start = (new DateTime())->modify('-4 months');
$today = new DateTime();

// Find first sunday on or after 4 months ago
$clone = clone $start;
if ($clone->format('w') != 0) {
    $clone->modify('next sunday');
}
$sundayInterval = new DateInterval('P7D');
$period = new DatePeriod($clone, $sundayInterval, $today);
foreach ($period as $dt) {
    $sundays[] = $dt->format('Y-m-d');
}
// Get last 4 sundays
$checkSundays = array_slice($sundays, -4);
$absentMembers = [];

if (count($checkSundays) >= 4) {
    // Check members who have NO present/late record in these 4 dates
    // Simplified: Find members who ARE present in ANY of these dates, exclude them.
    $datesStr = "'" . implode("','", $checkSundays) . "'";
    $sql = "SELECT DISTINCT member_id FROM member_attendance WHERE event_date IN ($datesStr) AND status IN ('present','late')";
    $presentIds = $pdo->query($sql)->fetchAll(PDO::FETCH_COLUMN);
    
    // Get all Active Members (EXCLUDING Visitors and Non-Available statuses)
    $allMembers = $pdo->query("SELECT id, full_name, phone FROM members WHERE status='Available' AND unit != 'Visitor'")->fetchAll();
    
    foreach ($allMembers as $m) {
        if (!in_array($m['id'], $presentIds)) {
            $absentMembers[] = $m;
        }
    }
}

// SPOOL / GROUPING
$spoolData = [];
$spoolFilter = isset($_GET['spool_filter']) ? $_GET['spool_filter'] : 'all'; // 'all' or specific service type?
// Just listing all dates with summary
$spoolSql = "SELECT event_date, 
    SUM(CASE WHEN status='present' OR status='late' THEN 1 ELSE 0 END) as present_count,
    SUM(CASE WHEN status='absent' THEN 1 ELSE 0 END) as absent_count
    FROM member_attendance GROUP BY event_date ORDER BY event_date DESC LIMIT 20";
$spoolData = $pdo->query($spoolSql)->fetchAll();

// PERSONAL REPORT
$personalId = isset($_GET['p_member']) ? (int)$_GET['p_member'] : 0;
$personalStats = [];
if ($personalId) {
    // Join with attendance to get exact in_time
    $personalStats = $pdo->prepare("
        SELECT ma.event_date, ma.status, a.in_time 
        FROM member_attendance ma 
        LEFT JOIN attendance a ON ma.member_id = a.member_id AND ma.event_date = DATE(a.in_time)
        WHERE ma.member_id = ? 
        ORDER BY ma.event_date DESC LIMIT 20
    ");
    $personalStats->execute([$personalId]);
    $personalStats = $personalStats->fetchAll();
}

$allMembersList = $pdo->query("SELECT id, full_name FROM members ORDER BY full_name")->fetchAll();

// MEMBER ASSIGNMENT HISTORY REPORT
$historyId = isset($_GET['h_member']) ? (int)$_GET['h_member'] : 0;
$h_date_from = isset($_GET['h_date_from']) ? $_GET['h_date_from'] : '';
$h_date_to = isset($_GET['h_date_to']) ? $_GET['h_date_to'] : '';
$assignmentHistory = [];

if ($historyId) {
    $h_sql = "
        SELECT s.service_date, s.type, ra.role_name 
        FROM roster_assignments ra
        JOIN rosters r ON ra.roster_id = r.id
        JOIN services s ON r.service_id = s.id
        WHERE ra.person_name = (SELECT full_name FROM members WHERE id = ?)
    ";
    
    $h_params = [$historyId];
    
    if (!empty($h_date_from)) {
        $h_sql .= " AND s.service_date >= ?";
        $h_params[] = $h_date_from;
    }
    if (!empty($h_date_to)) {
        $h_sql .= " AND s.service_date <= ?";
        $h_params[] = $h_date_to;
    }
    
    $h_sql .= " ORDER BY s.service_date DESC LIMIT 50";
    
    $h_stmt = $pdo->prepare($h_sql);
    $h_stmt->execute($h_params);
    $assignmentHistory = $h_stmt->fetchAll();
}

// ATTENDANCE HIGHLIGHTS LOGIC
$currentYear = date('Y');
$highlights = [];
for ($m = 1; $m <= 12; $m++) {
    $monthName = date('F', mktime(0, 0, 0, $m, 1));
    $startDate = "$currentYear-" . str_pad($m, 2, "0", STR_PAD_LEFT) . "-01";
    $endDate = date('Y-m-t', strtotime($startDate));
    
    // TOP 10 (Earliest Average Arrival)
    $topStmt = $pdo->prepare("
        SELECT m.full_name, ROUND(AVG(TIME_TO_SEC(a.in_time))) as avg_seconds, COUNT(*) as count
        FROM attendance a
        JOIN members m ON a.member_id = m.id
        WHERE m.status = 'Available' AND m.unit != 'Visitor'
        AND DATE(a.in_time) BETWEEN ? AND ?
        GROUP BY m.id 
        HAVING count >= 2
        ORDER BY avg_seconds ASC LIMIT 10
    ");
    $topStmt->execute([$startDate, $endDate]);
    $top10 = $topStmt->fetchAll();
    
    // BOTTOM 10 (Latest Average Arrival)
    $bottomStmt = $pdo->prepare("
        SELECT m.full_name, ROUND(AVG(TIME_TO_SEC(a.in_time))) as avg_seconds, COUNT(*) as count
        FROM attendance a
        JOIN members m ON a.member_id = m.id
        WHERE m.status = 'Available' AND m.unit != 'Visitor'
        AND DATE(a.in_time) BETWEEN ? AND ?
        GROUP BY m.id 
        HAVING count >= 1
        ORDER BY avg_seconds DESC LIMIT 10
    ");
    $bottomStmt->execute([$startDate, $endDate]);
    $bottom10 = $bottomStmt->fetchAll();
    
    if (!empty($top10)) {
        $highlights[$monthName] = ['top' => $top10, 'bottom' => $bottom10];
    }
}

// QUARTERLY PUNCTUAL CHAMPION LOGIC
$q_quarter = isset($_GET['q_quarter']) ? (int)$_GET['q_quarter'] : (int)ceil(date('n')/3);
$q_year = isset($_GET['q_year']) ? (int)$_GET['q_year'] : (int)date('Y');

$currentQuarter = $q_quarter;
$currentYear_q = $q_year;

$start_q_month = ($currentQuarter - 1) * 3 + 1;
$end_q_month = $start_q_month + 2;
$start_q_date = "$currentYear_q-" . str_pad($start_q_month, 2, '0', STR_PAD_LEFT) . "-01";
$end_q_date = date("Y-m-t", strtotime("$currentYear_q-" . str_pad($end_q_month, 2, '0', STR_PAD_LEFT) . "-01"));

// 1. Get total services in this quarter that have passed
$totalServicesStmt = $pdo->prepare("SELECT COUNT(*) FROM services WHERE service_date BETWEEN ? AND ? AND service_date <= CURRENT_DATE");
$totalServicesStmt->execute([$start_q_date, $end_q_date]);
$totalQServices = $totalServicesStmt->fetchColumn();

$punctualChampions = [];
if ($totalQServices > 0) {
    // 2. Find members with high punctuality consistency
    // Logic: Attended at least 50% of available services. Ranked by Punctuality %
    
    // Calculate 50% threshold
    $minservices = ceil($totalQServices * 0.5);
    
    $champStmt = $pdo->prepare("
        SELECT m.full_name, m.unit, 
               COUNT(a.id) as attended_count,
               SUM(CASE WHEN a.was_late = 0 THEN 1 ELSE 0 END) as punctual_count,
               (SUM(CASE WHEN a.was_late = 0 THEN 1 ELSE 0 END) / COUNT(a.id)) * 100 as pct_punctual,
               ROUND(AVG(TIME_TO_SEC(a.in_time))) as avg_seconds
        FROM members m
        JOIN attendance a ON m.id = a.member_id
        WHERE DATE(a.in_time) BETWEEN ? AND ?
        GROUP BY m.id
        HAVING attended_count >= ?
        ORDER BY pct_punctual DESC, avg_seconds ASC
        LIMIT 20
    ");
    $champStmt->execute([$start_q_date, $end_q_date, $minservices]);
    $punctualChampions = $champStmt->fetchAll();
}
?>

<?php
// ANALYSIS REPORT DATA
// Default: Last 12 Months
$a_start_date = isset($_GET['a_start_date']) ? $_GET['a_start_date'] : date('Y-m-d', strtotime('-12 months'));
$a_end_date = isset($_GET['a_end_date']) ? $_GET['a_end_date'] : date('Y-m-d');

$yearTrend = $pdo->prepare("
    SELECT DATE_FORMAT(event_date, '%Y-%m') as m, 
           COUNT(*) as total,
           SUM(CASE WHEN status='present' THEN 1 ELSE 0 END) as present,
           SUM(CASE WHEN status='late' THEN 1 ELSE 0 END) as late
    FROM member_attendance 
    WHERE event_date BETWEEN ? AND ?
    AND status IN ('present', 'late', 'absent') 
    GROUP BY m 
    ORDER BY m ASC
");
$yearTrend->execute([$a_start_date, $a_end_date]);
$yearTrend = $yearTrend->fetchAll(PDO::FETCH_ASSOC);

$trendLabels = [];
$trendPresent = [];
$trendLate = [];
foreach($yearTrend as $t) {
    $trendLabels[] = date('M Y', strtotime($t['m'] . "-01"));
    $trendPresent[] = $t['present'];
    $trendLate[] = $t['late'];
}
?>

<h1>Reports & Analytics</h1>

<div class="tabs">
    <button class="tab-btn active" onclick="openTab('general')">General</button>
    <button class="tab-btn" onclick="openTab('analysis')">Analysis</button>
    <button class="tab-btn" onclick="openTab('spool')">Service Spool</button>
    <button class="tab-btn" onclick="openTab('absent')">Absenteeism</button>
    <button class="tab-btn" onclick="openTab('personal')">Attendance History</button>
    <button class="tab-btn" onclick="openTab('history')">Assignment History</button>
    <button class="tab-btn" onclick="openTab('highlights')">Highlights</button>
    <button class="tab-btn" onclick="openTab('champions')">Champions</button>
    <button class="tab-btn" onclick="openTab('worship')">Worship Review</button>
</div>

<!-- Analysis Tab -->
<div id="analysis" class="tab-content" style="display:none;">
    <div class="card">
        <h3>Attendance Analysis</h3>
        
        <form method="GET" class="no-print" style="margin-bottom: 20px;">
            <input type="hidden" name="page" value="reports">
            <input type="hidden" name="tab" value="analysis">
            <div style="display: flex; gap: 10px; align-items: flex-end; flex-wrap: wrap;">
                <div>
                    <label>From</label>
                    <input type="date" name="a_start_date" class="form-control" value="<?php echo htmlspecialchars($a_start_date); ?>">
                </div>
                 <div>
                    <label>To</label>
                    <input type="date" name="a_end_date" class="form-control" value="<?php echo htmlspecialchars($a_end_date); ?>">
                </div>
                <button type="submit" class="btn">Filter</button>
                
                <div style="margin-left: auto; display: flex; gap: 10px;">
                     <button type="button" onclick="printAnalysisSection()" class="btn" style="background: #444;"><i class="fas fa-print"></i> Print PDF</button>
                     <button type="button" onclick="exportAnalysisJPG(this)" class="btn" style="background: var(--success-color); color: #000;"><i class="fas fa-image"></i> Export JPG</button>
                </div>
            </div>
            <div style="margin-top: 15px;">
                <label>Chart Type: </label>
                <select id="chartTypeSelector" class="form-control" style="width: auto; display: inline-block;">
                    <option value="bar">Bar Chart (Monthly Breakdown)</option>
                    <option value="line">Line Chart (Trend)</option>
                    <option value="pie">Pie Chart (Overall Ratio)</option>
                </select>
            </div>
        </form>
        
        <div id="analysis-chart-container" style="height: 400px; padding: 20px; background: #fff; border-radius: 4px; position: relative;"> 
            <?php if(empty($trendLabels)): ?>
                <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); color: #666;">
                    No attendance data found for the selected period.
                </div>
            <?php else: ?>
                <canvas id="analysisCanvas"></canvas>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
    let analysisChart = null;
    const trendLabels = <?php echo json_encode($trendLabels); ?>;
    const trendPresent = <?php echo json_encode($trendPresent); ?>;
    const trendLate = <?php echo json_encode($trendLate); ?>;

    // Aggregates for Pie
    const totalPresent = trendPresent.reduce((a, b) => a + Number(b), 0);
    const totalLate = trendLate.reduce((a, b) => a + Number(b), 0);
    
    function renderAnalysisChart(type) {
        const ctx = document.getElementById('analysisCanvas');
        if(!ctx) return; // Canvas might not exist if no data
        
        if(analysisChart) analysisChart.destroy();
        
        let config = {};
        
        if (type === 'pie') {
            config = {
                type: 'pie',
                data: {
                    labels: ['On Time', 'Late'],
                    datasets: [{
                        data: [totalPresent, totalLate],
                        backgroundColor: ['#4ade80', '#fbbf24']
                    }]
                },
                options: { maintainAspectRatio: false }
            };
        } else {
            // Bar or Line
            config = {
                type: type,
                data: {
                    labels: trendLabels,
                    datasets: [
                        {
                            label: 'On Time',
                            data: trendPresent,
                            backgroundColor: '#4ade80',
                            borderColor: '#4ade80',
                            borderWidth: 1
                        },
                        {
                            label: 'Late',
                            data: trendLate,
                            backgroundColor: '#fbbf24',
                            borderColor: '#fbbf24',
                            borderWidth: 1
                        }
                    ]
                },
                options: {
                    maintainAspectRatio: false,
                    scales: {
                        y: { beginAtZero: true, grid: { color: '#444' }, ticks: { color: '#ccc'} },
                        x: { grid: { color: '#444' }, ticks: { color: '#ccc'} }
                    },
                    plugins: {
                        legend: { labels: { color: '#333' } } // Dark text for white bg
                    }
                }
            };
        }

        analysisChart = new Chart(ctx, config);
    }
    
    // JS functions for export defined later...
    
    function printAnalysisSection() {
        // Temporarily force Analysis tab display for print
        document.body.classList.add('printing-analysis-active');
        window.print();
        setTimeout(() => {
            document.body.classList.remove('printing-analysis-active');
        }, 1000);
    }

    async function exportAnalysisJPG(btn) {
        const area = document.getElementById('analysis-chart-container');
        btn.disabled = true;
        const originalText = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> ...';
        
        try {
            const canvas = await html2canvas(area, {
                scale: 2,
                backgroundColor: '#ffffff'
            });
            const link = document.createElement('a');
            const safeDate = new Date().toISOString().slice(0,10);
            link.download = `Attendance-Analysis-${safeDate}.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 = originalText;
        }
    }
    
    // Init on Load
    document.addEventListener('DOMContentLoaded', () => {
        const selector = document.getElementById('chartTypeSelector');
        if(selector) {
            selector.addEventListener('change', (e) => renderAnalysisChart(e.target.value));
        }

        // Auto-open analysis tab if in URL
        const urlParams = new URLSearchParams(window.location.search);
        if(urlParams.get('tab') === 'analysis') {
             const btn = document.querySelector("button[onclick=\"openTab('analysis')\"]");
             if(btn) btn.click();
             // Initial Render
             renderAnalysisChart('bar');
        }
    });
    
    // Hook into openTab
    if (typeof openTab === 'function') {
        const _oldOpenTab = openTab;
        window.openTab = function(tabName) {
            _oldOpenTab(tabName);
            if(tabName === 'analysis') {
                setTimeout(() => {
                    if(!analysisChart) renderAnalysisChart('bar'); 
                    else analysisChart.resize(); 
                }, 100);
            }
        }
    }
</script>

<style>
    @media print {
        body.printing-analysis-active #analysis { display: block !important; }
        /* Hide everything else is handled by global print styles mostly, 
           but ensure we target this specific print mode */
        body.printing-analysis-active .tab-content { display: none; }
        body.printing-analysis-active #analysis { display: block !important; }
        
        /* Ensure chart background is white for print */
        #analysis-chart-container { background-color: #ffffff !important; border: 1px solid #ccc; }
    }
</style>

<div id="general" class="tab-content style='display:block;'">
    <div class="dashboard-grid">
         <div class="card">
            <h3>Attendance Trends</h3>
            <p>Last 4 Services</p>
            <table>
                <?php foreach ($last4Services as $s): ?>
                <tr>
                    <td><?php echo $s['event_date']; ?><br><small><?php echo getServiceName($s['event_date'], $pdo); ?></small></td>
                    <td><strong><?php echo $s['count']; ?></strong> Present</td>
                </tr>
                <?php endforeach; ?>
            </table>
        </div>
    </div>
</div>

<div id="spool" class="tab-content" style="display:none;">
    <div class="card">
        <h3>Service Attendance Spool</h3>
        <div class="table-responsive">
            <table>
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Service Name</th>
                        <th>Present</th>
                        <th>Absent</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($spoolData as $row): ?>
                    <tr onclick="window.location='index.php?page=service_attendance_detail&date=<?php echo $row['event_date']; ?>'" style="cursor:pointer;" title="Click to view details">
                        <td><a href="index.php?page=service_attendance_detail&date=<?php echo $row['event_date']; ?>"><?php echo $row['event_date']; ?></a></td>
                        <td><?php echo getServiceName($row['event_date'], $pdo); ?></td>
                        <td><span class="badge" style="background:var(--success-color)"><?php echo $row['present_count']; ?></span></td>
                        <td><?php echo $row['absent_count']; ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div id="absent" class="tab-content" style="display:none;">
    <div class="card">
        <h3>Consistent Absenteeism</h3>
        <p>Members absent for at least 4 consecutive Sundays (Past 4 Months)</p>
        <?php if (count($checkSundays) < 4): ?>
            <div class="alert alert-warning">Not enough Sundays have passed in the last 4 months to generate this report.</div>
<?php else: ?>
            <ul>
                <?php foreach ($absentMembers as $am): ?>
                <li>
                    <strong><?php echo htmlspecialchars($am['full_name']); ?></strong> 
                    <a href="tel:<?php echo $am['phone']; ?>"><?php echo $am['phone']; ?></a>
                </li>
                <?php endforeach; ?>
                <?php if(empty($absentMembers)) echo "<li>No consistently absent members found.</li>"; ?>
            </ul>
        <?php endif; ?>
    </div>
</div>

<div id="personal" class="tab-content" style="display:none;">
    <div class="card">
        <h3>Personal Attendance History</h3>
        
        <?php
        // Date and Quarterly filters for Personal Report
        $p_date_from = isset($_GET['p_date_from']) ? $_GET['p_date_from'] : '';
        $p_date_to = isset($_GET['p_date_to']) ? $_GET['p_date_to'] : '';
        $p_quarter = isset($_GET['p_quarter']) ? (int)$_GET['p_quarter'] : 0;
        $p_year = isset($_GET['p_year']) ? (int)$_GET['p_year'] : (int)date('Y');

        if ($p_quarter > 0) {
            $start_month = ($p_quarter - 1) * 3 + 1;
            $end_month = $start_month + 2;
            $p_date_from = "$p_year-" . str_pad($start_month, 2, '0', STR_PAD_LEFT) . "-01";
            $p_date_to = date("Y-m-t", strtotime("$p_year-" . str_pad($end_month, 2, '0', STR_PAD_LEFT) . "-01"));
        }
        
        // Enhance SQL with filters if dates provided
        if ($personalId) {
            $p_sql = "
                SELECT ma.event_date, ma.status, a.in_time 
                FROM member_attendance ma 
                LEFT JOIN attendance a ON ma.member_id = a.member_id AND ma.event_date = DATE(a.in_time)
                WHERE ma.member_id = ?
            ";
            $p_params = [$personalId];
            
            if ($p_date_from) {
                $p_sql .= " AND ma.event_date >= ?";
                $p_params[] = $p_date_from;
            }
            if ($p_date_to) {
                $p_sql .= " AND ma.event_date <= ?";
                $p_params[] = $p_date_to;
            }
            
            $p_sql .= " ORDER BY ma.event_date DESC LIMIT 50";
            
            $p_stmt = $pdo->prepare($p_sql);
            $p_stmt->execute($p_params);
            $personalStats = $p_stmt->fetchAll();
            
            // Calculate Summary
            $p_summary = ['Present' => 0, 'Late' => 0, 'Absent' => 0];
            foreach ($personalStats as $s) {
                $st = strtolower($s['status']);
                if ($st == 'present') $p_summary['Present']++; // 'Early/Present' logic
                elseif ($st == 'late' || $st == 'very late') $p_summary['Late']++;
                elseif ($st == 'absent') $p_summary['Absent']++;
            }
        }
        ?>

        <form method="GET" class="no-print" style="margin-bottom: 20px;">
            <input type="hidden" name="page" value="reports">
            <input type="hidden" name="tab" value="personal">
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 10px; align-items: end;">
                <div>
                    <label>Select Member</label>
                    <select name="p_member" class="form-control" onchange="this.form.submit()">
                        <option value="">-- Select Member --</option>
                        <?php foreach($allMembersList as $m): ?>
                        <option value="<?php echo $m['id']; ?>" <?php if($personalId == $m['id']) echo 'selected'; ?>>
                            <?php echo htmlspecialchars($m['full_name']); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label>From Date</label>
                    <input type="date" name="p_date_from" class="form-control" value="<?php echo htmlspecialchars($p_date_from); ?>">
                </div>
                <div>
                    <label>To Date</label>
                    <input type="date" name="p_date_to" class="form-control" value="<?php echo htmlspecialchars($p_date_to); ?>">
                </div>
                <div>
                    <label>Quarter</label>
                    <div style="display: flex; gap: 5px;">
                        <select name="p_quarter" class="form-control" style="width: 70px;">
                            <option value="0">--</option>
                            <option value="1" <?php if($p_quarter == 1) echo 'selected'; ?>>Q1</option>
                            <option value="2" <?php if($p_quarter == 2) echo 'selected'; ?>>Q2</option>
                            <option value="3" <?php if($p_quarter == 3) echo 'selected'; ?>>Q3</option>
                            <option value="4" <?php if($p_quarter == 4) echo 'selected'; ?>>Q4</option>
                        </select>
                        <input type="number" name="p_year" class="form-control" value="<?php echo $p_year; ?>" style="width: 80px;">
                    </div>
                </div>
                <div>
                    <button type="submit" class="btn">Filter</button>
                    <?php if($personalId): ?>
                        <div class="btn-group" style="display: inline-block;">
                            <button type="button" onclick="printPersonalSection()" class="btn" style="background: #444;"><i class="fas fa-print"></i> Print PDF</button>
                            <button type="button" onclick="exportPersonalJPG(this)" class="btn" style="background: var(--success-color); color: #000;"><i class="fas fa-image"></i> Export JPG</button>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </form>
        
        <?php if($personalId): ?>
        <div id="personal-print-area" class="personal-print-area" style="background: #fff; color: #000; padding: 15px; border-radius: 8px;"> <!-- Hidden by CSS unless printing or capturing -->
            <?php 
            $memberName = '';
            foreach($allMembersList as $m) if($m['id'] == $personalId) $memberName = $m['full_name'];
            ?>
            <div style="text-align: center; margin-bottom: 20px;">
                <h2 style="margin: 0; color: #000;">Personal Attendance Report</h2>
                <h3 style="margin: 5px 0; color: #555;"><?php echo htmlspecialchars($memberName); ?></h3>
                <p style="font-size: 0.9rem; color: #777;">Generated on <?php echo date('M j, Y'); ?></p>
            </div>
            
            <!-- Summary Box -->
            <div style="display: flex; gap: 0; margin-bottom: 20px; border: 1px solid #ccc; background: #f9f9f9; border-radius: 4px; overflow: hidden;">
                <div style="text-align: center; flex: 1; padding: 15px;">
                    <div style="font-size: 2rem; color: var(--success-color); font-weight: bold;"><?php echo $p_summary['Present']; ?></div>
                    <div style="color: #666; font-size: 0.8rem; font-weight: bold; text-transform: uppercase;">Early / Present</div>
                </div>
                <div style="text-align: center; flex: 1; border-left: 1px solid #ccc; border-right: 1px solid #ccc; padding: 15px;">
                    <div style="font-size: 2rem; color: #ffa000; font-weight: bold;"><?php echo $p_summary['Late']; ?></div>
                    <div style="color: #666; font-size: 0.8rem; font-weight: bold; text-transform: uppercase;">Late</div>
                </div>
                <div style="text-align: center; flex: 1; padding: 15px;">
                    <div style="font-size: 2rem; color: var(--danger-color); font-weight: bold;"><?php echo $p_summary['Absent']; ?></div>
                    <div style="color: #666; font-size: 0.8rem; font-weight: bold; text-transform: uppercase;">Absent</div>
                </div>
            </div>

            <table style="width: 100%; border-collapse: collapse; margin-top: 10px;">
                <thead>
                    <tr style="background: #f0f0f0;">
                        <th style="padding: 8px; border: 1px solid #ccc; text-align: left; color: #000;">Date</th>
                        <th style="padding: 8px; border: 1px solid #ccc; text-align: left; color: #000;">Service</th>
                        <th style="padding: 8px; border: 1px solid #ccc; text-align: left; color: #000;">Status</th>
                        <th style="padding: 8px; border: 1px solid #ccc; text-align: left; color: #000;">Checked In</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($personalStats as $ps): 
                        $rawStatus = strtolower($ps['status']);
                        $statusColor = '#000';
                        $statusBg = '#fff';
                        
                        if ($rawStatus == 'present') { $statusColor = 'var(--success-color)'; $statusBg = '#e6fffa'; }
                        elseif ($rawStatus == 'late' || $rawStatus == 'very late') { $statusColor = '#d97706'; $statusBg = '#fffbeb'; }
                        elseif ($rawStatus == 'absent') { $statusColor = 'var(--danger-color)'; $statusBg = '#fef2f2'; }
                        elseif ($rawStatus == 'travelled') { $statusColor = '#ffa000'; $statusBg = '#fff7ed'; }
                        elseif ($rawStatus == 'gospel errand') { $statusColor = '#9c27b0'; $statusBg = '#faf5ff'; }
                        elseif ($rawStatus == 'not available') { $statusColor = '#64748b'; $statusBg = '#f1f5f9'; }
                    ?>
                    <tr>
                        <td style="padding: 8px; border: 1px solid #ccc; color: #000;"><?php echo $ps['event_date']; ?></td>
                        <td style="padding: 8px; border: 1px solid #ccc; color: #000;"><?php echo getServiceName($ps['event_date'], $pdo); ?></td>
                        <td style="padding: 8px; border: 1px solid #ccc; font-weight: bold; color: <?php echo $statusColor; ?> !important; background-color: <?php echo $statusBg; ?> !important;">
                            <?php echo ucfirst($ps['status']); ?>
                        </td>
                        <td style="padding: 8px; border: 1px solid #ccc; color: #000;"><?php echo $ps['in_time'] ? date("g:i A", strtotime($ps['in_time'])) : '---'; ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        
        <!-- On-Screen Preview (Dark Mode optimized, separate from print area for better UX) -->
         <div class="no-print" style="margin-top: 20px;">
            <!-- Re-render for screen if needed, or just let users view it via export. 
                 Actually, better to show the data on screen normally, and use the hidden cleaner div for export. 
            -->
             <div style="display: flex; gap: 20px; margin-bottom: 20px; padding: 15px; background: #222; border-radius: 4px; color: #fff;">
                <div style="text-align: center; flex: 1;">
                    <div style="font-size: 2rem; color: var(--success-color); font-weight: bold;"><?php echo $p_summary['Present']; ?></div>
                    <div style="color: #ccc; font-size: 0.9rem;">EARLY / PRESENT</div>
                </div>
                <div style="text-align: center; flex: 1; border-left: 1px solid #444; border-right: 1px solid #444;">
                    <div style="font-size: 2rem; color: #ffa000; font-weight: bold;"><?php echo $p_summary['Late']; ?></div>
                    <div style="color: #ccc; font-size: 0.9rem;">LATE</div>
                </div>
                <div style="text-align: center; flex: 1;">
                    <div style="font-size: 2rem; color: var(--danger-color); font-weight: bold;"><?php echo $p_summary['Absent']; ?></div>
                    <div style="color: #ccc; font-size: 0.9rem;">ABSENT</div>
                </div>
            </div>

            <table style="width: 100%;">
                <thead>
                    <tr>
                        <th style="text-align: left;">Date</th>
                        <th style="text-align: left;">Service</th>
                        <th style="text-align: left;">Status</th>
                        <th style="text-align: left;">Checked In</th>
                    </tr>
                </thead>
                <tbody>
                     <?php foreach ($personalStats as $ps): 
                        $rawStatus = strtolower($ps['status']);
                        $statusColor = 'inherit';
                        if ($rawStatus == 'present') $statusColor = 'var(--success-color)';
                        elseif ($rawStatus == 'late' || $rawStatus == 'very late') $statusColor = '#ffa000';
                        elseif ($rawStatus == 'absent') $statusColor = 'var(--danger-color)';
                    ?>
                    <tr>
                        <td><?php echo $ps['event_date']; ?></td>
                        <td><?php echo getServiceName($ps['event_date'], $pdo); ?></td>
                        <td style="color: <?php echo $statusColor; ?>; font-weight: bold;">
                            <?php echo ucfirst($ps['status']); ?>
                        </td>
                        <td><?php echo $ps['in_time'] ? date("g:i A", strtotime($ps['in_time'])) : '---'; ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
         </div>

        <?php endif; ?>
    </div>
</div>

<script>
function printPersonalSection() {
    document.body.classList.add('printing-personal-active');
    window.print();
    setTimeout(() => {
        document.body.classList.remove('printing-personal-active');
    }, 1000);
}

async function exportPersonalJPG(btn) {
    const area = document.getElementById('personal-print-area');
    btn.disabled = true;
    const originalText = btn.innerHTML;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> ...';
    
    // Ensure area is visible for capture but clean
    area.classList.add('capturing-jpg');
    
    try {
        const canvas = await html2canvas(area, {
            scale: 2,
            backgroundColor: '#ffffff',
            useCORS: true,
            onclone: (clonedDoc) => {
                const clonedArea = clonedDoc.getElementById('personal-print-area');
                clonedArea.style.display = 'block';
                clonedArea.style.backgroundColor = '#ffffff';
                clonedArea.style.color = '#000000';
                clonedArea.querySelectorAll('td, th').forEach(el => {
                    el.style.backgroundColor = '#ffffff';
                    
                    // Preserve status colors if present
                    const text = el.innerText.toLowerCase();
                    if (text.includes('present')) { el.style.color = '#22c55e'; }
                    else if (text.includes('late')) { el.style.color = '#dfdf00'; }
                    else if (text.includes('absent')) { el.style.color = '#ef4444'; }
                    else { el.style.color = '#000000'; }

                    el.style.borderColor = '#ccc';
                    el.style.borderStyle = 'solid';
                    el.style.borderWidth = '1px';
                });
            }
        });
        const link = document.createElement('a');
        const safeDate = new Date().toISOString().slice(0,10);
        link.download = `Personal-Attendance-${safeDate}.jpg`;
        link.href = canvas.toDataURL('image/jpeg', 0.9);
        link.click();
    } catch (err) {
        console.error(err);
        alert('Image export failed.');
    } finally {
        area.classList.remove('capturing-jpg');
        btn.disabled = false;
        btn.innerHTML = originalText;
    }
}
</script>

<div id="history" class="tab-content" style="display:none;">
    <div class="card">
        <h3>Member Assignment History</h3>
        <form method="GET">
            <input type="hidden" name="page" value="reports">
            <input type="hidden" name="tab" value="history">
            
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; align-items: end;">
                <div>
                    <label style="font-size: 0.85rem; color: #888; margin-bottom: 5px; display: block;">Select Member</label>
                    <select name="h_member" class="form-control" onchange="this.form.submit()">
                        <option value="">-- Select Member --</option>
                        <?php foreach($allMembersList as $m): ?>
                        <option value="<?php echo $m['id']; ?>" <?php if($historyId == $m['id']) echo 'selected'; ?>>
                            <?php echo htmlspecialchars($m['full_name']); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label style="font-size: 0.85rem; color: #888; margin-bottom: 5px; display: block;">From Date</label>
                    <input type="date" name="h_date_from" class="form-control" value="<?php echo htmlspecialchars($h_date_from); ?>">
                </div>
                <div>
                    <label style="font-size: 0.85rem; color: #888; margin-bottom: 5px; display: block;">To Date</label>
                    <input type="date" name="h_date_to" class="form-control" value="<?php echo htmlspecialchars($h_date_to); ?>">
                </div>
                <div>
                    <button type="submit" class="btn">Filter</button>
                </div>
            </div>
        </form>
        
        <?php if($historyId): ?>
        <div class="table-responsive" style="margin-top: 20px;">
            <table>
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Service Type</th>
                        <th>Role / Assignment</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($assignmentHistory as $h): ?>
                    <tr>
                        <td><?php echo date("M j, Y", strtotime($h['service_date'])); ?></td>
                        <td><?php echo $h['type']; ?></td>
                        <td><strong><?php echo htmlspecialchars($h['role_name']); ?></strong></td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if(empty($assignmentHistory)): ?>
                    <tr><td colspan="3" style="text-align: center;">No assignments found for this period.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>
    </div>
</div>

<div id="highlights" class="tab-content" style="display:none;">
    <div class="card">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
            <h3>Attendance Highlights (<?php echo $currentYear; ?>)</h3>
            <button onclick="printSection('highlights')" class="btn no-print"><i class="fas fa-print"></i> Print Highlights</button>
        </div>
        <p style="color: #888; margin-bottom: 20px;" class="no-print">Ranked by <strong>average arrival time</strong> (Monthly).</p>
        
        <div id="highlights-print-area">
        <?php foreach ($highlights as $month => $data): ?>
        <div style="margin-bottom: 30px; border: 1px solid #333; border-radius: 8px; overflow: hidden; break-inside: avoid;">
            <div style="background: #222; padding: 10px 15px; font-weight: bold; border-bottom: 1px solid #333; color: var(--accent-color);" class="highlight-month-header">
                <?php echo strtoupper($month); ?>
            </div>
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 0;">
                <!-- Top 10 -->
                <div style="border-right: 1px solid #333; padding: 10px; background: rgba(34, 197, 94, 0.05);" class="highlight-top-box">
                    <div style="font-size: 0.8rem; text-transform: uppercase; color: var(--success-color); margin-bottom: 10px; font-weight: bold;">
                        <i class="fas fa-trophy"></i> Earliest Arrivals (Top 10)
                    </div>
                    <table style="font-size: 0.85rem;">
                        <?php $rank = 1; foreach ($data['top'] as $m): ?>
                        <tr>
                            <td style="width: 25px; color: #666;"><?php echo $rank++; ?>.</td>
                            <td><?php echo htmlspecialchars($m['full_name']); ?></td>
                            <td style="text-align: right; font-weight: bold;"><?php echo date("g:i A", (int)$m['avg_seconds']); ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </table>
                </div>
                <!-- Bottom 10 -->
                <div style="padding: 10px; background: rgba(239, 68, 68, 0.05);" class="highlight-bottom-box">
                    <div style="font-size: 0.8rem; text-transform: uppercase; color: var(--danger-color); margin-bottom: 10px; font-weight: bold;">
                        <i class="fas fa-clock"></i> Latest Arrivals (Last 10)
                    </div>
                    <table style="font-size: 0.85rem;">
                        <?php $rank = 1; foreach ($data['bottom'] as $m): ?>
                        <tr>
                            <td style="width: 25px; color: #666;"><?php echo $rank++; ?>.</td>
                            <td><?php echo htmlspecialchars($m['full_name']); ?></td>
                            <td style="text-align: right; font-weight: bold; color: #888;"><?php echo date("g:i A", (int)$m['avg_seconds']); ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </table>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
        </div>
        
        <?php if(empty($highlights)): ?>
            <div class="alert alert-info">No highlights data available for the current year.</div>
        <?php endif; ?>
    </div>
</div>

<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>

<div id="champions" class="tab-content" style="display:none;">
    <div class="card">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
            <h3>Quarterly Punctual Champions (Q<?php echo $currentQuarter; ?> <?php echo $currentYear_q; ?>)</h3>
            <div style="display: flex; gap: 10px; align-items: center;" class="no-print">
                <form method="GET" style="display: flex; gap: 5px; align-items: center;">
                    <input type="hidden" name="page" value="reports">
                    <input type="hidden" name="tab" value="champions">
                    <select name="q_quarter" class="form-control" onchange="this.form.submit()" style="width: auto;">
                        <option value="1" <?php if($q_quarter == 1) echo 'selected'; ?>>Q1</option>
                        <option value="2" <?php if($q_quarter == 2) echo 'selected'; ?>>Q2</option>
                        <option value="3" <?php if($q_quarter == 3) echo 'selected'; ?>>Q3</option>
                        <option value="4" <?php if($q_quarter == 4) echo 'selected'; ?>>Q4</option>
                    </select>
                    <input type="number" name="q_year" class="form-control" value="<?php echo $q_year; ?>" onchange="this.form.submit()" style="width: 80px;">
                </form>
                <button onclick="printSection('champions')" class="btn" style="background: #444;"><i class="fas fa-print"></i> Print PDF</button>
            </div>
        </div>
        <p style="color: #888; margin-bottom: 20px;">Members with <strong>100% Punctual Attendance</strong> this quarter.</p>
        
        <div id="champions-print-area">
            <?php if (empty($punctualChampions)): ?>
                <div class="alert alert-info">No 100% punctual champions identified for this quarter yet. (Total services processed: <?php echo $totalQServices; ?>)</div>
            <?php else: ?>
                <div class="table-responsive">
                    <table>
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Name</th>
                                <th>Unit</th>
                                <th>Attended</th>
                                <th>Punctual</th>
                                <th>Avg. Arrival</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $rank = 1; foreach ($punctualChampions as $c): ?>
                            <tr>
                                <td><?php echo $rank++; ?></td>
                                <td><strong><?php echo htmlspecialchars($c['full_name']); ?></strong></td>
                                <td><?php echo htmlspecialchars($c['unit']); ?></td>
                                <td><?php echo $c['attended_count']; ?> / <?php echo $totalQServices; ?></td>
                                <td>
                                    <span class="badge" style="background: var(--success-color); color: #000;"><?php echo round($c['pct_punctual'], 1); ?>%</span>
                                    <small>(<?php echo $c['punctual_count']; ?>)</small>
                                </td>
                                <td><?php echo date("g:i A", (int)$c['avg_seconds']); ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<style>
    .tabs { display: flex; gap: 10px; margin-bottom: 20px; border-bottom: 1px solid #444; padding-bottom: 10px; overflow-x: auto;}
    .tab-btn { background: transparent; border: none; color: #888; padding: 10px 20px; cursor: pointer; font-size: 1rem; border-bottom: 2px solid transparent;}
    .tab-btn.active { color: var(--primary-color); border-bottom-color: var(--primary-color); font-weight: bold;}
    .tab-content { animation: fadeIn 0.3s; }

    @media print {
        /* Force color printing */
        * {
            -webkit-print-color-adjust: exact !important;
            print-color-adjust: exact !important;
            color-adjust: exact !important;
        }
        
        header, nav, .tabs, .no-print, .btn { display: none !important; }
        .container { width: 100% !important; max-width: none !important; margin: 0 !important; padding: 0 !important; }
        body, html { background-color: #ffffff !important; color: #000000 !important; }
        .wrapper, .content-wrapper, .main-panel { background-color: #ffffff !important; } /* Override theme containers */
        .card { border: 1px solid #ddd !important; background: #fff !important; box-shadow: none !important; padding: 20px !important; }
        
        /* Preserve colors for highlights */
        #highlights-print-area div { border-color: #ddd !important; }
        .highlight-month-header { 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important; 
            color: #fff !important; 
            border-bottom: 1px solid #ccc !important; 
            padding: 10px 15px !important;
        }
        .highlight-top-box { 
            background: linear-gradient(135deg, rgba(34, 197, 94, 0.1) 0%, rgba(34, 197, 94, 0.05) 100%) !important; 
            border-right: 1px solid #ddd !important;
        }
        .highlight-bottom-box { 
            background: linear-gradient(135deg, rgba(239, 68, 68, 0.1) 0%, rgba(239, 68, 68, 0.05) 100%) !important; 
        }
        
        /* Preserve badge colors */
        .badge { 
            -webkit-print-color-adjust: exact !important;
            print-color-adjust: exact !important;
        }
        
        /* Explicitly force white background on all table elements to override dark theme */
        table, tr, td, th, tbody, thead {
            background-color: #ffffff !important;
            color: #333 !important;
        }
        
        /* Preserve badge colors and status text colors */
        .badge, [style*="color:"] {
            -webkit-print-color-adjust: exact !important;
            print-color-adjust: exact !important;
        }
        
        table th { background: #f3f4f6 !important; color: #000 !important; padding: 4px !important; border: 1px solid #ddd !important; font-size: 0.9rem !important; } /* Keep light gray for headers */
        
        .tab-content { display: none !important; }
        
        body.printing-highlights #highlights { display: block !important; }
        body.printing-champions #champions { display: block !important; }
        body.printing-personal #personal { display: block !important; }
        
        /* If generic print (Ctrl+P), try to show what's currently visible on screen? 
           For now, relying on the buttons ensures strict output. */
        
        /* Spool table colors */
        #spool table td, #spool table th { border: 1px solid #ddd !important; }

        .personal-print-area { display: none !important; }
        body.printing-personal-active #personal,
        body.printing-personal-active #personal .card,
        body.printing-personal-active #personal-print-area { 
            display: block !important; 
            visibility: visible !important;
        }
        body.printing-personal-active #personal-print-area {
            position: fixed !important;
            top: 0 !important;
            left: 0 !important;
            width: 100% !important;
            z-index: 9999 !important;
            background: #fff !important;
        }
    }

    /* JPG Capture Visibility */
    .personal-print-area { display: none; }
    .personal-print-area.capturing-jpg { display: block; position: absolute; left: -9999px; }
</style>

<script>
function openTab(tabId) {
    document.querySelectorAll('.tab-content').forEach(el => el.style.display = 'none');
    document.querySelectorAll('.tab-btn').forEach(el => el.classList.remove('active'));
    
    document.getElementById(tabId).style.display = 'block';
    
    // Highlight button (simple logic here, or passed via event)
    const btns = document.querySelectorAll('.tab-btn');
    if(tabId=='general') btns[0].classList.add('active');
    if(tabId=='spool') btns[1].classList.add('active');
    if(tabId=='absent') btns[2].classList.add('active');
    if(tabId=='personal') btns[3].classList.add('active');
    if(tabId=='history') btns[4].classList.add('active');
    if(tabId=='highlights') btns[5].classList.add('active');
    if(tabId=='champions') btns[6].classList.add('active');
}

function printSection(section) {
    // Add class to body to trigger CSS visibility
    document.body.classList.add('printing-' + section);
    window.print();
}

// Clean up after print
window.onafterprint = function() {
    document.body.classList.remove('printing-highlights', 'printing-champions', 'printing-personal');
};
// Fallback for browsers that don't support onafterprint or block it (optional)
setTimeout(function() {
    document.body.classList.remove('printing-highlights', 'printing-champions', 'printing-personal');
}, 2000);

// Check URL param to open tab if refreshed
const urlParams = new URLSearchParams(window.location.search);
const activeTab = urlParams.get('tab');
if(activeTab) openTab(activeTab);
else if(urlParams.get('p_member')) openTab('personal');
else if(urlParams.get('h_member')) openTab('history');
</script>
<div id="worship" class="tab-content" style="display:none;">
    <div class="card">
        <h3>Worship Reports Review</h3>
        <p>Generate a summary report of all worship events and sermons over a selected period.</p>
        <div style="margin-top: 20px;">
            <a href="index.php?page=worship_review" class="btn"><i class="fas fa-file-invoice"></i> Go to Worship Review</a>
        </div>
    </div>
</div>
