<?php
require_once '../includes/config.php';

// Check if admin is logged in
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

require_once 'header.php';

// Get dashboard stats with error handling
$stats = [];
try {
    $stats = getDashboardStats($pdo);
} catch (PDOException $e) {
    $stats = [
        'total_members' => 0,
        'new_members' => 0,
        'total_revenue' => 0,
        'upcoming_events' => 0,
        'expiring_members' => 0
    ];
}

// Get recent members with error handling
$recentMembers = [];
try {
    $stmt = $pdo->query("SELECT m.*, mt.type as membership_type 
                        FROM members m 
                        LEFT JOIN membership_types mt ON m.membership_type_id = mt.id 
                        ORDER BY m.created_at DESC LIMIT 10");
    $recentMembers = $stmt->fetchAll();
} catch (PDOException $e) {
    $recentMembers = [];
}

// Get recent renewals with error handling
$recentRenewals = [];
try {
    $stmt = $pdo->query("SELECT r.*, m.fullname, m.membership_number 
                        FROM renewals r 
                        JOIN members m ON r.member_id = m.id 
                        ORDER BY r.renewal_date DESC LIMIT 10");
    $recentRenewals = $stmt->fetchAll();
} catch (PDOException $e) {
    $recentRenewals = [];
}

// Get membership distribution with error handling
$membershipDist = [];
try {
    $stmt = $pdo->query("SELECT mt.type, COUNT(m.id) as count 
                        FROM membership_types mt 
                        LEFT JOIN members m ON mt.id = m.membership_type_id 
                        GROUP BY mt.id");
    $membershipDist = $stmt->fetchAll();
} catch (PDOException $e) {
    $membershipDist = [];
}
?>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2"><i class="fas fa-tachometer-alt me-2"></i>Dashboard</h1>
    <div class="btn-toolbar">
        <button class="btn btn-sm btn-outline-secondary" onclick="window.location.reload()">
            <i class="fas fa-sync-alt"></i> Refresh
        </button>
    </div>
</div>

<!-- Statistics Cards -->
<div class="row">
    <div class="col-md-3 mb-4">
        <div class="card stat-card bg-primary text-white shadow">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h6 class="card-title mb-1">Total Members</h6>
                        <h2 class="mb-0"><?php echo number_format($stats['total_members'] ?? 0); ?></h2>
                    </div>
                    <i class="fas fa-users fa-2x opacity-50"></i>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3 mb-4">
        <div class="card stat-card bg-success text-white shadow">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h6 class="card-title mb-1">New Members</h6>
                        <h2 class="mb-0"><?php echo number_format($stats['new_members'] ?? 0); ?></h2>
                        <small>This Month</small>
                    </div>
                    <i class="fas fa-user-plus fa-2x opacity-50"></i>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3 mb-4">
        <div class="card stat-card bg-info text-white shadow">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h6 class="card-title mb-1">Total Revenue</h6>
                        <h2 class="mb-0"><?php echo formatCurrency($stats['total_revenue'] ?? 0); ?></h2>
                    </div>
                    <i class="fas fa-rupee-sign fa-2x opacity-50"></i>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3 mb-4">
        <div class="card stat-card bg-warning text-white shadow">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h6 class="card-title mb-1">Upcoming Events</h6>
                        <h2 class="mb-0"><?php echo number_format($stats['upcoming_events'] ?? 0); ?></h2>
                    </div>
                    <i class="fas fa-calendar-alt fa-2x opacity-50"></i>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Recent Members and Renewals -->
<div class="row">
    <div class="col-md-6">
        <div class="card shadow">
            <div class="card-header bg-white">
                <h5 class="mb-0"><i class="fas fa-users me-2 text-primary"></i>Recent Members</h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead class="table-light">
                            <tr>
                                <th>Name</th>
                                <th>Membership No</th>
                                <th>Type</th>
                                <th>Joined</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (count($recentMembers) > 0): ?>
                                <?php foreach ($recentMembers as $member): ?>
                                <tr>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <?php if (!empty($member['profile_photo']) && $member['profile_photo'] != 'default.jpg'): ?>
                                                <img src="<?php echo UPLOAD_URL . $member['profile_photo']; ?>" class="rounded-circle me-2" width="30" height="30" style="object-fit: cover;">
                                            <?php else: ?>
                                                <i class="fas fa-user-circle fa-2x me-2 text-muted"></i>
                                            <?php endif; ?>
                                            <?php echo htmlspecialchars($member['fullname']); ?>
                                        </div>
                                    </td>
                                    <td><code><?php echo $member['membership_number']; ?></code></td>
                                    <td><span class="badge bg-info"><?php echo $member['membership_type'] ?? 'N/A'; ?></span></td>
                                    <td><?php echo formatDate($member['created_at']); ?></td>
                                </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="4" class="text-center text-muted">No members found</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-6">
        <div class="card shadow">
            <div class="card-header bg-white">
                <h5 class="mb-0"><i class="fas fa-sync-alt me-2 text-success"></i>Recent Renewals</h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead class="table-light">
                            <tr>
                                <th>Member</th>
                                <th>Amount</th>
                                <th>Date</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (count($recentRenewals) > 0): ?>
                                <?php foreach ($recentRenewals as $renewal): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($renewal['fullname']); ?></td>
                                    <td><span class="fw-bold text-success"><?php echo formatCurrency($renewal['amount']); ?></span></td>
                                    <td><?php echo formatDate($renewal['renewal_date']); ?></td>
                                </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="3" class="text-center text-muted">No renewals found</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Charts and Expiring Members -->
<div class="row mt-4">
    <div class="col-md-6">
        <div class="card shadow">
            <div class="card-header bg-white">
                <h5 class="mb-0"><i class="fas fa-chart-pie me-2 text-info"></i>Membership Distribution</h5>
            </div>
            <div class="card-body">
                <?php if (count($membershipDist) > 0): ?>
                    <canvas id="membershipChart" height="200"></canvas>
                <?php else: ?>
                    <div class="text-center py-4 text-muted">
                        <i class="fas fa-chart-pie fa-3x mb-2"></i>
                        <p>No data available</p>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <div class="col-md-6">
        <div class="card shadow">
            <div class="card-header bg-white">
                <h5 class="mb-0"><i class="fas fa-exclamation-triangle me-2 text-warning"></i>Expiring Members</h5>
            </div>
            <div class="card-body text-center">
                <div class="py-3">
                    <i class="fas fa-clock fa-4x text-warning mb-3"></i>
                    <h2 class="text-warning"><?php echo number_format($stats['expiring_members'] ?? 0); ?> Members</h2>
                    <p class="text-muted">Expiring in next 30 days</p>
                    <a href="members.php?filter=expiring" class="btn btn-warning">
                        <i class="fas fa-eye me-2"></i>View Expiring Members
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Quick Actions -->
<div class="row mt-4">
    <div class="col-12">
        <div class="card shadow">
            <div class="card-header bg-white">
                <h5 class="mb-0"><i class="fas fa-bolt me-2 text-secondary"></i>Quick Actions</h5>
            </div>
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-md-3 col-6">
                        <a href="members.php?action=add" class="btn btn-outline-primary w-100 py-3">
                            <i class="fas fa-user-plus fa-2x d-block mb-2"></i>
                            <small>Add Member</small>
                        </a>
                    </div>
                    <div class="col-md-3 col-6">
                        <a href="membership_types.php" class="btn btn-outline-success w-100 py-3">
                            <i class="fas fa-tags fa-2x d-block mb-2"></i>
                            <small>Membership Types</small>
                        </a>
                    </div>
                    <div class="col-md-3 col-6">
                        <a href="renewals.php" class="btn btn-outline-warning w-100 py-3">
                            <i class="fas fa-sync-alt fa-2x d-block mb-2"></i>
                            <small>Add Renewal</small>
                        </a>
                    </div>
                    <div class="col-md-3 col-6">
                        <a href="events.php" class="btn btn-outline-info w-100 py-3">
                            <i class="fas fa-calendar-plus fa-2x d-block mb-2"></i>
                            <small>Create Event</small>
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    <?php if (count($membershipDist) > 0): ?>
    const ctx = document.getElementById('membershipChart').getContext('2d');
    new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: <?php echo json_encode(array_column($membershipDist, 'type')); ?>,
            datasets: [{
                data: <?php echo json_encode(array_column($membershipDist, 'count')); ?>,
                backgroundColor: ['#3498db', '#2ecc71', '#e74c3c', '#f39c12', '#9b59b6', '#1abc9c', '#e67e22'],
                borderWidth: 0
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: true,
            plugins: {
                legend: {
                    position: 'bottom'
                }
            }
        }
    });
    <?php endif; ?>
});
</script>

<style>
.stat-card {
    transition: transform 0.2s ease, box-shadow 0.2s ease;
    cursor: pointer;
    border: none;
    border-radius: 12px;
}

.stat-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 25px rgba(0,0,0,0.2);
}

.card {
    border: none;
    border-radius: 12px;
    overflow: hidden;
}

.card-header {
    border-bottom: 1px solid rgba(0,0,0,0.05);
    padding: 15px 20px;
}

.table th, .table td {
    padding: 12px;
    vertical-align: middle;
}

.opacity-50 {
    opacity: 0.5;
}

.btn-outline-primary, .btn-outline-success, .btn-outline-warning, .btn-outline-info {
    border-radius: 10px;
    transition: all 0.2s ease;
}

.btn-outline-primary:hover, .btn-outline-success:hover, .btn-outline-warning:hover, .btn-outline-info:hover {
    transform: translateY(-2px);
}

@media (max-width: 768px) {
    .stat-card h2 {
        font-size: 1.5rem;
    }
    .btn-outline-primary, .btn-outline-success, .btn-outline-warning, .btn-outline-info {
        padding: 8px;
    }
}
</style>

<?php require_once 'footer.php'; ?>