<?php
// pages/dashboard.php
requireRole('any'); // Allow any logged in user

// Fetch some quick stats
$member_count = $pdo->query("SELECT COUNT(*) FROM members")->fetchColumn();

// Fetch issues with priority breakdown
$issue_count = $pdo->query("SELECT COUNT(*) FROM issues WHERE status IN ('Open', 'In Progress')")->fetchColumn();
$urgent_count = $pdo->query("SELECT COUNT(*) FROM issues WHERE status IN ('Open', 'In Progress') AND priority='urgent'")->fetchColumn();
$normal_count = $pdo->query("SELECT COUNT(*) FROM issues WHERE status IN ('Open', 'In Progress') AND priority='normal'")->fetchColumn();
$low_count = $pdo->query("SELECT COUNT(*) FROM issues WHERE status IN ('Open', 'In Progress') AND priority='low'")->fetchColumn();

// Fetch recent open issues for display
$recent_issues = $pdo->query("
    SELECT i.*, m1.full_name as reporter_name 
    FROM issues i
    JOIN members m1 ON i.reported_by = m1.id
    WHERE i.status IN ('Open', 'In Progress')
    ORDER BY 
        CASE i.priority 
            WHEN 'urgent' THEN 1 
            WHEN 'normal' THEN 2 
            WHEN 'low' THEN 3 
        END,
        i.created_at DESC
    LIMIT 5
")->fetchAll();

// Helper function to calculate age
function getIssueAge($created_at) {
    $now = new DateTime();
    $created = new DateTime($created_at);
    $diff = $now->diff($created);
    
    if ($diff->days == 0) {
        if ($diff->h == 0) {
            return $diff->i . " min" . ($diff->i != 1 ? 's' : '');
        }
        return $diff->h . " hour" . ($diff->h != 1 ? 's' : '');
    } elseif ($diff->days < 7) {
        return $diff->days . " day" . ($diff->days != 1 ? 's' : '');
    } elseif ($diff->days < 30) {
        $weeks = floor($diff->days / 7);
        return $weeks . " week" . ($weeks != 1 ? 's' : '');
    } else {
        $months = floor($diff->days / 30);
        return $months . " month" . ($months != 1 ? 's' : '');
    }
}

// Upcoming Service (Try catch in case table doesn't exist yet)
$upcoming_service = "No upcoming services";
try {
    $stmt = $pdo->query("SELECT * FROM services WHERE status = 'Open' AND service_date >= CURDATE() ORDER BY service_date ASC LIMIT 1");
    $service = $stmt->fetch();
    if ($service) {
        $upcoming_service = htmlspecialchars($service['type']) . " (" . date('D, M j', strtotime($service['service_date'])) . ")";
    }
} catch (Exception $e) {
    $upcoming_service = "Table 'services' not found. Please run updates.";
}

?>

<div class="dashboard-header">
    <h1>Welcome, <?php echo htmlspecialchars($_SESSION['username']); ?></h1>
    <p>Department Operations Dashboard</p>
</div>

<div class="dashboard-grid">
    <!-- Quick Actions -->
    <div class="card">
        <h3>Quick Actions</h3>
        <ul style="list-style: none; display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
            <li><a href="index.php?page=attendance_kiosk" class="btn btn-block" style="padding: 15px 10px;">Attendance Kiosk</a></li>
            <li><a href="index.php?page=roster" class="btn btn-block" style="padding: 15px 10px; background-color: var(--accent-color);">Roster Assignment</a></li>
            <li><a href="index.php?page=reports" class="btn btn-block" style="padding: 15px 10px; background-color: #666;">Reports</a></li>
            <li><a href="index.php?page=issue_form" class="btn btn-block" style="padding: 15px 10px; background-color: var(--secondary-color);">Report Issue</a></li>
        </ul>
    </div>

    <!-- Quick Stats -->
    <div class="card">
        <h3><i class="fas fa-users"></i> Total Members</h3>
        <div class="stat"><?php echo $member_count; ?></div>
        <a href="index.php?page=members">View All Members</a>
        <br>
        <a href="index.php?page=birthdays" style="font-size: 0.9em; margin-top: 5px; display: inline-block;">View Birthdays 🎂</a>
    </div>

    <div class="card">
        <h3><i class="fas fa-calendar-alt"></i> Next Service</h3>
        <div class="stat" style="font-size: 1.2rem;"><?php echo $upcoming_service; ?></div>
        <?php if (hasRole('admin') || hasRole('coordinator')): ?>
        <a href="index.php?page=services">Manage Services</a>
        <?php endif; ?>
    </div>
    
    <div class="card">
        <h3><i class="fas fa-exclamation-circle"></i> Active Issues</h3>
        <div class="stat"><?php echo $issue_count; ?></div>
        <div style="margin-top: 10px; font-size: 0.85rem;">
            <div style="display: flex; justify-content: space-between; margin-bottom: 5px;">
                <span>🔴 Urgent:</span>
                <strong style="color: var(--danger-color);"><?php echo $urgent_count; ?></strong>
            </div>
            <div style="display: flex; justify-content: space-between; margin-bottom: 5px;">
                <span>🟡 Normal:</span>
                <strong style="color: #ffa000;"><?php echo $normal_count; ?></strong>
            </div>
            <div style="display: flex; justify-content: space-between;">
                <span>🟢 Low:</span>
                <strong style="color: var(--success-color);"><?php echo $low_count; ?></strong>
            </div>
        </div>
        <a href="index.php?page=issues" style="margin-top: 10px; display: inline-block;">View All Issues</a>
    </div>

    <!-- YouTube Stats Card -->
    <?php include 'includes/youtube_stats_card.php'; ?>

    <!-- Attendance Trends Graph -->
    <div class="card" style="grid-column: span 2;">
        <h3>Attendance Trends (Last 4 Services)</h3>
        <canvas id="attendanceChart" height="100"></canvas>
    </div>
</div>

<?php 
// Last 4 Services Data for Chart
$trendData = $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(PDO::FETCH_ASSOC);
// Reverse to show oldest to newest on left-to-right graph
$trendData = array_reverse($trendData);

$labels = [];
$values = [];
foreach($trendData as $d) {
    $labels[] = date('M j', strtotime($d['event_date']));
    $values[] = $d['count'];
}
?>
<script>
    window.addEventListener('load', function() {
        const ctx = document.getElementById('attendanceChart');
        if(ctx && typeof Chart !== 'undefined') {
            new Chart(ctx, {
                type: 'line',
                data: {
                    labels: <?php echo json_encode($labels); ?>,
                    datasets: [{
                        label: 'Total Attendance',
                        data: <?php echo json_encode($values); ?>,
                        borderColor: '#4ade80', // Success green
                        backgroundColor: 'rgba(74, 222, 128, 0.2)',
                        borderWidth: 2,
                        fill: true,
                        tension: 0.3
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        legend: { labels: { color: '#ccc' } }
                    },
                    scales: {
                        x: { ticks: { color: '#bbb' }, grid: { color: '#444' } },
                        y: { ticks: { color: '#bbb' }, grid: { color: '#444' }, beginAtZero: true }
                    }
                }
            });
        }
    });
</script>

<!-- Recent Issues Section -->
<?php if (count($recent_issues) > 0): ?>
<div style="margin-top: 30px;">
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
        <h2>Recent Open Issues</h2>
        <a href="index.php?page=issues" class="btn" style="background-color: #666;">View All</a>
    </div>
    <div class="card">
        <div style="display: flex; flex-direction: column; gap: 15px;">
            <?php foreach ($recent_issues as $issue): ?>
            <div style="border-left: 4px solid <?php 
                echo $issue['priority'] == 'urgent' ? 'var(--danger-color)' : 
                     ($issue['priority'] == 'low' ? 'var(--success-color)' : '#ffa000'); 
            ?>; padding-left: 15px; padding-bottom: 10px; border-bottom: 1px solid #333;">
                <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 5px;">
                    <div style="flex: 1;">
                        <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 5px;">
                            <span style="font-size: 1.1rem;">
                                <?php echo $issue['priority'] == 'urgent' ? '🔴' : ($issue['priority'] == 'low' ? '🟢' : '🟡'); ?>
                            </span>
                            <strong><?php echo htmlspecialchars($issue['type']); ?></strong>
                            <span class="badge" style="background: <?php 
                                echo $issue['status'] == 'Open' ? 'var(--danger-color)' : '#ffa000'; 
                            ?>; padding: 2px 6px; border-radius: 4px; font-size: 0.75rem;">
                                <?php echo htmlspecialchars($issue['status']); ?>
                            </span>
                        </div>
                        <p style="margin: 5px 0; color: #ccc;">
                            <?php 
                            if (!empty($issue['description_summary'])) {
                                echo htmlspecialchars($issue['description_summary']);
                            } else {
                                $desc = htmlspecialchars($issue['description']);
                                echo strlen($desc) > 120 ? substr($desc, 0, 120) . '...' : $desc;
                            }
                            ?>
                        </p>
                        <div style="font-size: 0.8rem; color: #888;">
                            Reported by <strong><?php echo htmlspecialchars($issue['reporter_name']); ?></strong>
                            • <?php echo htmlspecialchars($issue['department']); ?>
                        </div>
                    </div>
                    <div style="text-align: right; min-width: 80px;">
                        <div style="font-size: 0.75rem; color: #888; margin-bottom: 5px;">
                            <?php echo getIssueAge($issue['created_at']); ?> ago
                        </div>
                        <a href="index.php?page=issue_form&id=<?php echo $issue['id']; ?>" class="btn" style="padding: 4px 8px; font-size: 0.75rem;">View</a>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>
<?php endif; ?>
