<?php 
include 'admin-header.php';

// --- DATA FETCHING FOR NEW DASHBOARD WIDGETS ---

// 1. KPI Cards Data (Optimized)
$kpi_sql = "SELECT
    (SELECT COUNT(*) FROM transactions WHERE status = 'Pending') + 
    (SELECT COUNT(*) FROM withdrawals WHERE status = 'Pending') + 
    (SELECT COUNT(*) FROM users WHERE role LIKE '%_partner' AND status = 'pending') as pending_actions,
    (SELECT COUNT(*) FROM users WHERE role != 'admin') as total_users,
    (SELECT SUM(amount) FROM transactions WHERE status = 'Completed' AND transaction_type IN ('Top-up', 'Admin Credit')) as total_revenue
";
$kpis = $conn->query($kpi_sql)->fetch_assoc();

// 2. Data for the Action Center (Get latest 3 of each pending type)
$pending_topups = $conn->query("SELECT t.*, u.full_name FROM transactions t JOIN users u ON t.user_id = u.id WHERE t.status = 'Pending' ORDER BY t.created_at DESC LIMIT 3");
$pending_withdrawals = $conn->query("SELECT w.*, u.full_name FROM withdrawals w JOIN users u ON w.partner_id = u.id WHERE w.status = 'Pending' ORDER BY w.created_at DESC LIMIT 3");
$pending_partners = $conn->query("SELECT * FROM users WHERE role LIKE '%_partner' AND status = 'pending' ORDER BY created_at DESC LIMIT 3");

// 3. Data for the Live Activity Feed
$recent_activity_sql = "
    (SELECT 'New Booking' as type, b.created_at as activity_date, u.full_name, t.title as item_name FROM bookings b JOIN users u ON b.user_id = u.id JOIN tours t ON b.tour_id = t.id WHERE b.payment_status = 'Paid' ORDER BY b.created_at DESC LIMIT 3)
    UNION ALL
    (SELECT 'New User' as type, created_at as activity_date, full_name, NULL as item_name FROM users WHERE role = 'customer' ORDER BY created_at DESC LIMIT 3)
    ORDER BY activity_date DESC LIMIT 5
";
$recent_activity_result = $conn->query($recent_activity_sql);

?>
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <div>
        <h1 class="h2">Dashboard</h1>
        <p class="text-muted">Welcome back, Admin! Here's your business overview.</p>
    </div>
</div>

<div class="row row-deck">
    <div class="col-md-4 mb-4">
        <div class="card kpi-card shadow-sm" style="--bs-primary: #dc3545;">
            <div class="card-body"><div class="row align-items-center"><div class="col"><div class="card-title">Pending Actions</div><div class="card-text"><?php echo $kpis['pending_actions'] ?? 0; ?></div></div><div class="col-auto"><i class="bi bi-exclamation-triangle-fill kpi-icon"></i></div></div></div>
        </div>
    </div>
     <div class="col-md-4 mb-4">
        <div class="card kpi-card shadow-sm" style="--bs-primary: #198754;">
            <div class="card-body"><div class="row align-items-center"><div class="col"><div class="card-title">Gross Revenue (All Time)</div><div class="card-text">₱<?php echo number_format($kpis['total_revenue'] ?? 0, 2); ?></div></div><div class="col-auto"><i class="bi bi-cash-coin kpi-icon"></i></div></div></div>
        </div>
    </div>
    <div class="col-md-4 mb-4">
        <div class="card kpi-card shadow-sm" style="--bs-primary: #0d6efd;">
            <div class="card-body"><div class="row align-items-center"><div class="col"><div class="card-title">Total Users & Partners</div><div class="card-text"><?php echo $kpis['total_users'] ?? 0; ?></div></div><div class="col-auto"><i class="bi bi-people-fill kpi-icon"></i></div></div></div>
        </div>
    </div>
</div>

<div class="row mt-2">
    <div class="col-lg-7 mb-4">
        <div class="card shadow-sm h-100">
            <div class="card-header fw-bold"><i class="bi bi-list-check me-2"></i>Action Center</div>
            <div class="accordion accordion-flush" id="actionCenterAccordion">
                <div class="accordion-item">
                    <h2 class="accordion-header"><button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseTopups">Pending Top-Up Requests <span class="badge bg-danger ms-2"><?php echo $pending_topups->num_rows; ?></span></button></h2>
                    <div id="collapseTopups" class="accordion-collapse collapse" data-bs-parent="#actionCenterAccordion">
                        <div class="list-group list-group-flush"><?php while($item = $pending_topups->fetch_assoc()): ?><a href="top-up-requests.php" class="list-group-item list-group-item-action d-flex justify-content-between"><span><strong><?php echo htmlspecialchars($item['full_name']); ?></strong> - ₱<?php echo number_format($item['amount'],2); ?></span><span class="text-muted small"><?php echo date('M d', strtotime($item['created_at'])); ?></span></a><?php endwhile; ?></div>
                    </div>
                </div>
                <div class="accordion-item">
                    <h2 class="accordion-header"><button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseWithdrawals">Pending Partner Withdrawals <span class="badge bg-danger ms-2"><?php echo $pending_withdrawals->num_rows; ?></span></button></h2>
                    <div id="collapseWithdrawals" class="accordion-collapse collapse" data-bs-parent="#actionCenterAccordion">
                        <div class="list-group list-group-flush"><?php while($item = $pending_withdrawals->fetch_assoc()): ?><a href="manage-withdrawals.php" class="list-group-item list-group-item-action d-flex justify-content-between"><span><strong><?php echo htmlspecialchars($item['full_name']); ?></strong> - ₱<?php echo number_format($item['amount'],2); ?></span><span class="text-muted small"><?php echo date('M d', strtotime($item['created_at'])); ?></span></a><?php endwhile; ?></div>
                    </div>
                </div>
                <div class="accordion-item">
                    <h2 class="accordion-header"><button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapsePartners">Pending Partner Approvals <span class="badge bg-danger ms-2"><?php echo $pending_partners->num_rows; ?></span></button></h2>
                    <div id="collapsePartners" class="accordion-collapse collapse" data-bs-parent="#actionCenterAccordion">
                        <div class="list-group list-group-flush"><?php while($item = $pending_partners->fetch_assoc()): ?><a href="manage-users.php" class="list-group-item list-group-item-action d-flex justify-content-between"><span><strong><?php echo htmlspecialchars($item['full_name']); ?></strong> (<?php echo htmlspecialchars(str_replace('_', ' ', $item['role'])); ?>)</span><span class="text-muted small"><?php echo date('M d', strtotime($item['created_at'])); ?></span></a><?php endwhile; ?></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-lg-5 mb-4">
        <div class="card shadow-sm h-100">
            <div class="card-header fw-bold"><i class="bi-activity me-2"></i>Live Activity Feed</div>
            <div class="list-group list-group-flush">
                <?php if ($recent_activity_result && $recent_activity_result->num_rows > 0): while($activity = $recent_activity_result->fetch_assoc()): ?>
                <div class="list-group-item">
                    <?php if($activity['type'] == 'New User'): ?>
                        <i class="bi bi-person-plus-fill text-success"></i> <strong><?php echo htmlspecialchars($activity['full_name']); ?></strong> just registered.
                    <?php else: ?>
                        <i class="bi bi-bag-check-fill text-primary"></i> <strong><?php echo htmlspecialchars($activity['full_name']); ?></strong> booked <?php echo htmlspecialchars($activity['item_name']); ?>.
                    <?php endif; ?>
                    <div class="text-muted small ms-4"><?php echo date('M d, Y g:i A', strtotime($activity['activity_date'])); ?></div>
                </div>
                <?php endwhile; else: ?>
                    <div class="list-group-item text-center p-4">No recent activity.</div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<?php include 'admin-footer.php'; ?>
