<?php
/**
 * Admin dashboard – reference-style: stat cards with icons, Offerings, New members, Upcoming, Groups
 */
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/birthdays.php';
requireAuth();
requireAdmin();

$pageTitle = 'Dashboard';
$currentPage = 'dashboard';

$stats = ['members' => 0, 'households' => 0, 'ministries' => 0, 'events_this_month' => 0, 'birthdays_today' => 0];
try {
    if (isset($pdo)) {
        $stats['members'] = (int) $pdo->query('SELECT COUNT(*) FROM members')->fetchColumn();
        $stmt = $pdo->query('SELECT COUNT(*) FROM households');
        $stats['households'] = $stmt ? (int) $stmt->fetchColumn() : 0;
        $stmt = $pdo->query('SELECT COUNT(*) FROM ministries');
        $stats['ministries'] = $stmt ? (int) $stmt->fetchColumn() : 0;
        $monthStart = date('Y-m-01');
        $monthEnd = date('Y-m-t');
        $stmt = $pdo->prepare('SELECT COUNT(*) FROM events WHERE event_date BETWEEN ? AND ?');
        $stmt->execute([$monthStart, $monthEnd]);
        $stats['events_this_month'] = (int) $stmt->fetchColumn();
        $todayMonth = (int) date('n');
        $todayDay = (int) date('j');
        $birthdaysToday = getMembersWithBirthdayOn($pdo, $todayMonth, $todayDay);
        $stats['birthdays_today'] = count($birthdaysToday);
    }
} catch (Exception $e) {}
$birthdaysToday = $birthdaysToday ?? [];

$upcomingBirthdays = [];
try {
    if (isset($pdo)) {
        $allUpcoming = getUpcomingBirthdays($pdo, 7);
        $todayMonth = (int) date('n');
        $todayDay = (int) date('j');
        foreach ($allUpcoming as $b) {
            $bMonth = (int) date('n', strtotime($b['date_of_birth']));
            $bDay = (int) date('j', strtotime($b['date_of_birth']));
            if ($bMonth === $todayMonth && $bDay === $todayDay) continue;
            if (($b['days_until'] ?? 0) > 0 && ($b['days_until'] ?? 0) <= 7) $upcomingBirthdays[] = $b;
        }
        // Deduplicate by member id and limit
        $seen = [];
        $upcomingBirthdays = array_values(array_filter($upcomingBirthdays, function ($b) use (&$seen) {
            $id = (int) ($b['id'] ?? 0);
            if ($id && isset($seen[$id])) return false;
            if ($id) $seen[$id] = true;
            return true;
        }));
        $upcomingBirthdays = array_slice($upcomingBirthdays, 0, 3);
    }
} catch (Exception $e) {}

$upcomingEvents = [];
try {
    if (isset($pdo)) {
        $stmt = $pdo->prepare('SELECT id, title, event_date, event_time FROM events WHERE event_date >= ? ORDER BY event_date, event_time LIMIT 3');
        $stmt->execute([date('Y-m-d')]);
        $upcomingEvents = $stmt->fetchAll();
    }
} catch (Exception $e) {}

$offeringsThisMonth = null;
try {
    if (isset($pdo)) {
        $stmt = $pdo->prepare('SELECT COALESCE(SUM(amount), 0) AS total FROM transactions WHERE transaction_date BETWEEN ? AND ?');
        $stmt->execute([date('Y-m-01'), date('Y-m-t')]);
        $offeringsThisMonth = (float) $stmt->fetchColumn();
    }
} catch (Exception $e) {}

// Attendance vs target (latest session + last 4 sessions avg)
$attendanceLatest = null;
$attendanceTrend = null;
try {
    if (isset($pdo)) {
        $stmt = $pdo->query(
            "SELECT r.id, r.date, t.name AS service_type, t.target_total,
                    (r.male_count + r.female_count + r.children_count + r.visitors_count) AS total
             FROM attendance_records r
             JOIN service_types t ON t.id = r.service_type_id
             ORDER BY r.date DESC, r.id DESC
             LIMIT 1"
        );
        $attendanceLatest = $stmt ? $stmt->fetch(PDO::FETCH_ASSOC) : null;

        if ($attendanceLatest) {
            $sid = (int)$attendanceLatest['id'];
            $svc = (string)$attendanceLatest['service_type'];
            $target = $attendanceLatest['target_total'] !== null ? (int)$attendanceLatest['target_total'] : null;

            $stmt = $pdo->prepare(
                "SELECT r.date,
                        (r.male_count + r.female_count + r.children_count + r.visitors_count) AS total
                 FROM attendance_records r
                 WHERE r.service_type_id = (SELECT service_type_id FROM attendance_records WHERE id = ?)
                 ORDER BY r.date DESC, r.id DESC
                 LIMIT 4"
            );
            $stmt->execute([$sid]);
            $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
            $rows = array_reverse($rows);
            $avg = 0;
            if (!empty($rows)) {
                $avg = round(array_sum(array_map(fn($x) => (int)$x['total'], $rows)) / count($rows));
            }
            $attendanceTrend = [
                'service_type' => $svc,
                'target' => $target,
                'latest_total' => (int)$attendanceLatest['total'],
                'latest_date' => $attendanceLatest['date'],
                'last4' => $rows,
                'avg4' => (int)$avg,
            ];
        }
    }
} catch (Exception $e) {}

$upcomingPreaching = [];
try {
    if (isset($pdo)) {
        $today = date('Y-m-d');
        $firstSunday = date('w') == 0 ? $today : date('Y-m-d', strtotime('next sunday', strtotime($today)));
        $endDate = date('Y-m-d', strtotime('+15 days', strtotime($firstSunday)));
        $stmt = $pdo->prepare("SELECT service_date, occasion, preacher FROM preaching_plan WHERE service_date >= ? AND service_date < ? ORDER BY service_date");
        $stmt->execute([$firstSunday, $endDate]);
        $raw = $stmt->fetchAll(PDO::FETCH_ASSOC);
        // Group by date so we show each date once (avoid duplicate lines for same Sunday)
        $byDate = [];
        foreach ($raw as $pp) {
            $d = $pp['service_date'];
            if (!isset($byDate[$d])) $byDate[$d] = [];
            $byDate[$d][] = $pp;
        }
        $upcomingPreaching = array_slice($byDate, 0, 3, true);
    }
} catch (Exception $e) {}

$recentTransactions = [];
$recentMembers = [];
$ministriesList = [];
try {
    if (isset($pdo)) {
        $stmt = $pdo->query("SELECT t.transaction_date, t.amount, f.name AS fund_name FROM transactions t JOIN funds f ON f.id = t.fund_id ORDER BY t.transaction_date DESC, t.id DESC LIMIT 3");
        $recentTransactions = $stmt ? $stmt->fetchAll(PDO::FETCH_ASSOC) : [];
        $stmt = $pdo->query("SELECT id, first_name, last_name, created_at FROM members ORDER BY created_at DESC LIMIT 5");
        $recentMembers = $stmt ? $stmt->fetchAll(PDO::FETCH_ASSOC) : [];
        $stmt = $pdo->query("SELECT id, name FROM ministries ORDER BY name LIMIT 10");
        $ministriesList = $stmt ? $stmt->fetchAll(PDO::FETCH_ASSOC) : [];
    }
} catch (Exception $e) {}

require_once __DIR__ . '/../includes/header.php';
?>

<div class="dash-page">
    <header class="dash-header">
        <div>
            <h1 class="dash-title">Dashboard</h1>
            <p class="dash-subtitle"><?= htmlspecialchars(SITE_FULL_NAME) ?></p>
        </div>
        <div class="dash-header-right">
            <span class="dash-period"><?= date('F Y') ?></span>
            <a href="<?= BASE_PATH ?>/members/add" class="btn">Add member</a>
            <a href="<?= BASE_PATH ?>/finance/record" class="btn btn-secondary">Record offering</a>
            <a href="<?= BASE_PATH ?>/events/add" class="btn btn-secondary">Add event</a>
            <span class="dash-user"><?= htmlspecialchars(currentUsername()) ?></span>
            <a href="<?= BASE_PATH ?>/logout" class="dash-logout">Logout</a>
        </div>
    </header>
    <section class="dash-stat-cards" aria-label="Key statistics">
        <a href="<?= BASE_PATH ?>/members" class="dash-stat-card dash-stat-card-1">
            <span class="dash-stat-icon"><i class="fas fa-users" aria-hidden="true"></i></span>
            <div class="dash-stat-inner">
                <span class="dash-stat-label">Total Members</span>
                <span class="dash-stat-number"><?= number_format($stats['members']) ?></span>
            </div>
        </a>
        <a href="<?= BASE_PATH ?>/households" class="dash-stat-card dash-stat-card-2">
            <span class="dash-stat-icon"><i class="fas fa-home" aria-hidden="true"></i></span>
            <div class="dash-stat-inner">
                <span class="dash-stat-label">Households</span>
                <span class="dash-stat-number"><?= number_format($stats['households']) ?></span>
            </div>
        </a>
        <a href="<?= BASE_PATH ?>/ministries" class="dash-stat-card dash-stat-card-3">
            <span class="dash-stat-icon"><i class="fas fa-layer-group" aria-hidden="true"></i></span>
            <div class="dash-stat-inner">
                <span class="dash-stat-label">Service groups</span>
                <span class="dash-stat-number"><?= number_format($stats['ministries']) ?></span>
            </div>
        </a>
        <a href="<?= BASE_PATH ?>/events" class="dash-stat-card dash-stat-card-4">
            <span class="dash-stat-icon"><i class="fas fa-calendar-alt" aria-hidden="true"></i></span>
            <div class="dash-stat-inner">
                <span class="dash-stat-label">Events this month</span>
                <span class="dash-stat-number"><?= number_format($stats['events_this_month']) ?></span>
            </div>
        </a>
        <a href="<?= BASE_PATH ?>/birthdays" class="dash-stat-card dash-stat-card-5">
            <span class="dash-stat-icon"><i class="fas fa-birthday-cake" aria-hidden="true"></i></span>
            <div class="dash-stat-inner">
                <span class="dash-stat-label">Birthdays today</span>
                <span class="dash-stat-number"><?= number_format($stats['birthdays_today']) ?></span>
            </div>
        </a>
    </section>

    <div class="dash-content">
        <div class="dash-main">
            <?php if (!empty($attendanceTrend)): ?>
            <div class="dash-box">
                <div class="dash-box-head">
                    <h2 class="dash-box-title">Attendance</h2>
                    <a href="<?= BASE_PATH ?>/attendance/analytics" class="dash-box-action">Analytics →</a>
                </div>
                <div class="dash-box-body">
                    <?php
                        $target = $attendanceTrend['target'];
                        $latest = (int)$attendanceTrend['latest_total'];
                        $avg4 = (int)$attendanceTrend['avg4'];
                        $pct = ($target && $target > 0) ? round($latest / $target * 100) : null;
                        $statusColor = '#6366f1';
                        if ($pct !== null) {
                            if ($pct >= 100) $statusColor = '#22c55e';
                            elseif ($pct >= 80) $statusColor = '#f59e0b';
                            else $statusColor = '#ef4444';
                        }
                    ?>
                    <p class="dash-amount"><?= number_format($latest) ?></p>
                    <p class="dash-box-muted">
                        Latest: <?= htmlspecialchars($attendanceTrend['service_type']) ?> · <?= date('D, M j, Y', strtotime($attendanceTrend['latest_date'])) ?>
                        <?php if ($pct !== null): ?>
                            · <span style="color:<?= $statusColor ?>; font-weight:600;"><?= $pct ?>% of target (<?= (int)$target ?>)</span>
                        <?php endif; ?>
                    </p>
                    <p class="dash-box-muted">4-session avg: <?= number_format($avg4) ?></p>
                    <div style="display:flex; gap:0.5rem; flex-wrap:wrap; margin-top:0.75rem;">
                        <a href="<?= BASE_PATH ?>/attendance/record" class="btn btn-sm">Record attendance</a>
                        <a href="<?= BASE_PATH ?>/attendance" class="btn btn-sm btn-secondary">View sessions</a>
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <?php if ($offeringsThisMonth !== null): ?>
            <div class="dash-box">
                <div class="dash-box-head">
                    <h2 class="dash-box-title">Offerings</h2>
                    <a href="<?= BASE_PATH ?>/finance/reports" class="dash-box-action">View Report →</a>
                </div>
                <div class="dash-box-body">
                    <p class="dash-amount">GH¢ <?= number_format($offeringsThisMonth, 2) ?></p>
                    <p class="dash-box-muted">Offerings received this month</p>
                    <p><a href="<?= BASE_PATH ?>/finance/record" class="btn btn-sm">Record offering</a></p>
                </div>
            </div>
            <?php endif; ?>

            <div class="dash-box">
                <div class="dash-box-head">
                    <h2 class="dash-box-title">New members</h2>
                    <a href="<?= BASE_PATH ?>/members" class="dash-box-action">View All →</a>
                </div>
                <div class="dash-box-body">
                    <?php if (empty($recentMembers)): ?>
                    <p class="dash-empty">No members added yet.</p>
                    <?php else: ?>
                    <ul class="dash-members-list">
                        <?php foreach ($recentMembers as $m):
                            $name = trim(($m['first_name'] ?? '') . ' ' . ($m['last_name'] ?? ''));
                            if ($name === '') $name = 'Member #' . (int)$m['id'];
                            $initial = mb_substr(trim($m['first_name'] ?? ''), 0, 1) ?: '?';
                        ?>
                        <li>
                            <span class="dash-member-avatar" aria-hidden="true"><?= htmlspecialchars($initial) ?></span>
                            <div class="dash-member-info">
                                <a href="<?= BASE_PATH ?>/members/view/<?= (int)$m['id'] ?>"><?= htmlspecialchars($name) ?></a>
                                <span class="dash-member-meta">Added <?= !empty($m['created_at']) ? date('M j, Y', strtotime($m['created_at'])) : '—' ?></span>
                            </div>
                        </li>
                        <?php endforeach; ?>
                    </ul>
                    <?php endif; ?>
                </div>
            </div>

            <div class="dash-box dash-activity-box">
                <h2 class="dash-box-title">Recent activity</h2>
                <div class="dash-box-body">
                    <?php
                    $hasBirthdays = !empty($birthdaysToday) || !empty($upcomingBirthdays);
                    $hasEvents = !empty($upcomingEvents) || !empty($upcomingPreaching);
                    $hasFinance = !empty($recentTransactions);
                    ?>
                    <?php if (!$hasBirthdays && !$hasEvents && !$hasFinance): ?>
                    <p class="dash-empty">No recent activity.</p>
                    <?php else: ?>
                    <div class="dash-activity-grid">
                    <?php if ($hasBirthdays): ?>
                    <section class="dash-activity-section" aria-labelledby="dash-activity-birthdays">
                        <h3 id="dash-activity-birthdays" class="dash-activity-section-title">Upcoming birthdays</h3>
                        <ul class="dash-activity-list">
                            <?php foreach ($birthdaysToday as $m):
                                $name = trim(($m['first_name'] ?? '') . ' ' . ($m['last_name'] ?? ''));
                                if ($name === '') $name = 'Member #' . (int)$m['id'];
                            ?>
                            <li><a href="<?= BASE_PATH ?>/members/view/<?= (int)$m['id'] ?>"><?= htmlspecialchars($name) ?></a> <span class="dash-activity-meta">Today</span></li>
                            <?php endforeach; ?>
                            <?php foreach ($upcomingBirthdays as $m):
                                $name = trim(($m['first_name'] ?? '') . ' ' . ($m['last_name'] ?? ''));
                                if ($name === '') $name = 'Member #' . (int)$m['id'];
                                $daysText = ($m['days_until'] ?? 0) === 1 ? 'Tomorrow' : 'In ' . ($m['days_until'] ?? 0) . ' days';
                                $nextDate = new DateTime($m['next_birthday'] ?? 'now');
                            ?>
                            <li><a href="<?= BASE_PATH ?>/members/view/<?= (int)$m['id'] ?>"><?= htmlspecialchars($name) ?></a> <span class="dash-activity-meta"><?= $daysText ?> · <?= date('M j', $nextDate->getTimestamp()) ?></span></li>
                            <?php endforeach; ?>
                        </ul>
                        <p class="dash-activity-more"><a href="<?= BASE_PATH ?>/birthdays">View all birthdays →</a></p>
                    </section>
                    <?php endif; ?>

                    <?php if ($hasEvents): ?>
                    <section class="dash-activity-section" aria-labelledby="dash-activity-events">
                        <h3 id="dash-activity-events" class="dash-activity-section-title">Upcoming events &amp; preaching</h3>
                        <ul class="dash-activity-list">
                            <?php foreach ($upcomingEvents as $e): ?>
                            <li><a href="<?= BASE_PATH ?>/events"><?= htmlspecialchars($e['title']) ?></a> <span class="dash-activity-meta"><?= date('D, M j', strtotime($e['event_date'])) ?></span></li>
                            <?php endforeach; ?>
                            <?php foreach ($upcomingPreaching as $date => $rows):
                                $first = $rows[0];
                                $occasion = $first['occasion'] ? ucwords(strtolower($first['occasion'])) : 'Service';
                                $preacher = $first['preacher'] ?? '';
                                $dateLabel = date('D, M j', strtotime($date));
                            ?>
                            <li><a href="<?= BASE_PATH ?>/events"><?= htmlspecialchars($occasion) ?></a><?= $preacher ? ' — ' . htmlspecialchars($preacher) : '' ?> <span class="dash-activity-meta"><?= $dateLabel ?></span></li>
                            <?php endforeach; ?>
                        </ul>
                        <p class="dash-activity-more"><a href="<?= BASE_PATH ?>/events">View calendar →</a></p>
                    </section>
                    <?php endif; ?>

                    <?php if ($hasFinance): ?>
                    <section class="dash-activity-section" aria-labelledby="dash-activity-finance">
                        <h3 id="dash-activity-finance" class="dash-activity-section-title">Recent offerings</h3>
                        <ul class="dash-activity-list">
                            <?php foreach ($recentTransactions as $t): ?>
                            <li><a href="<?= BASE_PATH ?>/finance">GH¢ <?= number_format($t['amount'], 2) ?></a> <span class="dash-activity-meta"><?= htmlspecialchars($t['fund_name']) ?> · <?= date('M j', strtotime($t['transaction_date'])) ?></span></li>
                            <?php endforeach; ?>
                        </ul>
                        <p class="dash-activity-more"><a href="<?= BASE_PATH ?>/finance">View finance →</a></p>
                    </section>
                    <?php endif; ?>
                    </div>

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

        <aside class="dash-aside">
            <div class="dash-box">
                <h2 class="dash-box-title">Upcoming</h2>
                <div class="dash-box-body p-0">
                    <?php
                    $upcomingItems = [];
                    foreach ($birthdaysToday as $m) {
                        $name = trim(($m['first_name'] ?? '') . ' ' . ($m['last_name'] ?? ''));
                        if ($name === '') $name = 'Member #' . (int)$m['id'];
                        $upcomingItems[] = ['type' => 'birthday', 'url' => BASE_PATH . '/members/view/' . (int)$m['id'], 'title' => $name . "'s Birthday", 'action' => 'Send a message', 'date' => 'Today'];
                    }
                    foreach (array_slice($upcomingBirthdays, 0, 3) as $m) {
                        $name = trim(($m['first_name'] ?? '') . ' ' . ($m['last_name'] ?? ''));
                        if ($name === '') $name = 'Member #' . (int)$m['id'];
                        $nextDate = $m['next_birthday'] ?? '';
                        $upcomingItems[] = ['type' => 'birthday', 'url' => BASE_PATH . '/members/view/' . (int)$m['id'], 'title' => $name . "'s Birthday", 'action' => 'Send a message', 'date' => $nextDate ? date('M j', strtotime($nextDate)) : ''];
                    }
                    foreach (array_slice($upcomingEvents, 0, 3) as $e) {
                        $upcomingItems[] = ['type' => 'event', 'url' => BASE_PATH . '/events', 'title' => $e['title'], 'action' => 'View event', 'date' => date('M j', strtotime($e['event_date']))];
                    }
                    foreach (array_slice($upcomingPreaching, 0, 2) as $pp) {
                        $occasion = $pp['occasion'] ? ucwords(strtolower($pp['occasion'])) : 'Service';
                        $upcomingItems[] = ['type' => 'preaching', 'url' => BASE_PATH . '/events', 'title' => $occasion, 'action' => 'View schedule', 'date' => date('M j', strtotime($pp['service_date']))];
                    }
                    $upcomingItems = array_slice($upcomingItems, 0, 6);
                    ?>
                    <?php if (empty($upcomingItems)): ?>
                    <p class="dash-empty" style="padding: 1rem;">Nothing upcoming.</p>
                    <?php else: ?>
                    <ul class="dash-upcoming-list">
                        <?php foreach ($upcomingItems as $item): ?>
                        <li class="dash-upcoming-item dash-upcoming-<?= $item['type'] ?>">
                            <span class="dash-upcoming-icon" aria-hidden="true"></span>
                            <div class="dash-upcoming-body">
                                <a href="<?= htmlspecialchars($item['url']) ?>"><?= htmlspecialchars($item['title']) ?></a>
                                <?php if (!empty($item['action'])): ?> <span class="dash-upcoming-action"><?= htmlspecialchars($item['action']) ?></span><?php endif; ?>
                                <?php if (!empty($item['date'])): ?> <span class="dash-upcoming-date"><?= htmlspecialchars($item['date']) ?></span><?php endif; ?>
                            </div>
                        </li>
                        <?php endforeach; ?>
                    </ul>
                    <?php endif; ?>
                </div>
            </div>

            <div class="dash-box">
                <h2 class="dash-box-title">Groups</h2>
                <div class="dash-box-body p-0">
                    <?php if (empty($ministriesList)): ?>
                    <p class="dash-empty" style="padding: 1rem;">No service groups yet. <a href="<?= BASE_PATH ?>/ministries/add">Add one</a>.</p>
                    <?php else: ?>
                    <ul class="dash-groups-list">
                        <?php foreach ($ministriesList as $min): ?>
                        <li class="dash-group-item">
                            <span class="dash-group-name"><?= htmlspecialchars($min['name']) ?></span>
                            <a href="<?= BASE_PATH ?>/ministries" class="dash-group-view">View ▸</a>
                        </li>
                        <?php endforeach; ?>
                    </ul>
                    <?php endif; ?>
                </div>
            </div>
        </aside>
    </div>
</div>

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