<?php
session_start();

// Check if super admin is logged in
if (!isset($_SESSION['super_admin_id'])) {
    header("Location: login.php");
    exit();
}

// Database connection
require_once __DIR__ . '/../config/database.php';
$database = new Database();
$db = $database->getConnection();

// Get gym statistics
try {
    // Total gyms count
    $total_gyms_stmt = $db->query("SELECT COUNT(*) as total FROM gyms");
    $total_gyms = $total_gyms_stmt->fetch(PDO::FETCH_ASSOC)['total'];
    
    // Active gyms count
    $active_gyms_stmt = $db->query("SELECT COUNT(*) as total FROM gyms WHERE status = 'active'");
    $active_gyms = $active_gyms_stmt->fetch(PDO::FETCH_ASSOC)['total'];
    
    // Pending gyms count
    $pending_gyms_stmt = $db->query("SELECT COUNT(*) as total FROM gyms WHERE status = 'pending'");
    $pending_gyms = $pending_gyms_stmt->fetch(PDO::FETCH_ASSOC)['total'];
    
    // Inactive gyms count
    $inactive_gyms_stmt = $db->query("SELECT COUNT(*) as total FROM gyms WHERE status = 'inactive'");
    $inactive_gyms = $inactive_gyms_stmt->fetch(PDO::FETCH_ASSOC)['total'];
    
    // Get recent gyms for the table
    $recent_gyms_stmt = $db->query("
        SELECT id, name, owner_name, email, status, created_at 
        FROM gyms 
        ORDER BY created_at DESC 
        LIMIT 5
    ");
    $recent_gyms = $recent_gyms_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get subscription plans statistics
    $total_plans_stmt = $db->query("SELECT COUNT(*) as total FROM subscription_plans");
    $total_plans = $total_plans_stmt->fetch(PDO::FETCH_ASSOC)['total'];
    
    // Active plans count
    $active_plans_stmt = $db->query("SELECT COUNT(*) as total FROM subscription_plans WHERE status = 'active'");
    $active_plans = $active_plans_stmt->fetch(PDO::FETCH_ASSOC)['total'];
    
    // Inactive plans count
    $inactive_plans_stmt = $db->query("SELECT COUNT(*) as total FROM subscription_plans WHERE status = 'inactive'");
    $inactive_plans = $inactive_plans_stmt->fetch(PDO::FETCH_ASSOC)['total'];
    
    // Popular plans count (is_popular = 1)
    $popular_plans_stmt = $db->query("SELECT COUNT(*) as total FROM subscription_plans WHERE is_popular = 1");
    $popular_plans = $popular_plans_stmt->fetch(PDO::FETCH_ASSOC)['total'];
    
    // Get recent plans for the table
    $recent_plans_stmt = $db->query("
        SELECT id, name, price_monthly, price_yearly, status, is_popular, created_at 
        FROM subscription_plans 
        ORDER BY created_at DESC 
        LIMIT 5
    ");
    $recent_plans = $recent_plans_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get monthly gym registrations for chart
    $monthly_gyms_stmt = $db->query("
        SELECT 
            DATE_FORMAT(created_at, '%Y-%m') as month,
            COUNT(*) as count
        FROM gyms 
        WHERE created_at >= DATE_SUB(NOW(), INTERVAL 6 MONTH)
        GROUP BY DATE_FORMAT(created_at, '%Y-%m')
        ORDER BY month ASC
    ");
    $monthly_gyms = $monthly_gyms_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // If no data for monthly gyms, create default data
    if (empty($monthly_gyms)) {
        $current_month = date('Y-m');
        $monthly_gyms = [
            ['month' => $current_month, 'count' => 0]
        ];
    }
    
} catch (Exception $e) {
    // Handle errors gracefully
    $total_gyms = 0;
    $active_gyms = 0;
    $pending_gyms = 0;
    $inactive_gyms = 0;
    $total_plans = 0;
    $active_plans = 0;
    $inactive_plans = 0;
    $popular_plans = 0;
    $recent_gyms = [];
    $recent_plans = [];
    $monthly_gyms = [];
}
?>

<?php include 'includes/header.php'; ?>
<?php include 'includes/sidebar.php'; ?>
<?php include 'includes/navbar.php'; ?>

<div class="main-panel">
    <div class="content-wrapper pb-0">
        <div class="page-header flex-wrap">
            <div class="header-left">
                <h3 class="page-title">Super Admin Dashboard</h3>
                <p class="text-muted">Welcome back, <?php echo $_SESSION['super_admin_name']; ?>!</p>
            </div>
            <div class="header-right d-flex flex-wrap mt-2 mt-sm-0">
                <div class="d-flex align-items-center">
                    <a href="#">
                        <p class="m-0 pe-3"><i class="mdi mdi-home-outline"></i> Dashboard</p>
                    </a>
                </div>
            </div>
        </div>

        <!-- Quick Actions -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-body">
                        <h4 class="card-title mb-4">Quick Actions</h4>
                        <div class="row">
                            <div class="col-md-3 col-sm-6 mb-3">
                                <a href="gyms.php" class="card quick-action-card text-center p-4 text-decoration-none">
                                    <div class="icon-box bg-primary text-white mb-3">
                                        <i class="mdi mdi-dumbbell"></i>
                                    </div>
                                    <h6 class="mb-0">Manage Gyms</h6>
                                    <small class="text-muted">View all gym accounts</small>
                                </a>
                            </div>
                            <div class="col-md-3 col-sm-6 mb-3">
                                <a href="gyms.php" class="card quick-action-card text-center p-4 text-decoration-none" data-bs-toggle="modal" data-bs-target="#addGymModal">
                                    <div class="icon-box bg-success text-white mb-3">
                                        <i class="mdi mdi-plus-circle"></i>
                                    </div>
                                    <h6 class="mb-0">Add New Gym</h6>
                                    <small class="text-muted">Create gym account</small>
                                </a>
                            </div>
                            <div class="col-md-3 col-sm-6 mb-3">
                                <a href="plans.php" class="card quick-action-card text-center p-4 text-decoration-none">
                                    <div class="icon-box bg-info text-white mb-3">
                                        <i class="mdi mdi-currency-usd"></i>
                                    </div>
                                    <h6 class="mb-0">Subscription Plans</h6>
                                    <small class="text-muted">Manage pricing</small>
                                </a>
                            </div>
                            <div class="col-md-3 col-sm-6 mb-3">
                                <a href="plans.php" class="card quick-action-card text-center p-4 text-decoration-none" data-bs-toggle="modal" data-bs-target="#addPlanModal">
                                    <div class="icon-box bg-warning text-white mb-3">
                                        <i class="mdi mdi-plus-box"></i>
                                    </div>
                                    <h6 class="mb-0">Add New Plan</h6>
                                    <small class="text-muted">Create pricing plan</small>
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Gym Statistics -->
        <div class="row">
            <h4 class="mb-3">Gym Statistics</h4>
            
            <!-- Total Gyms -->
            <div class="col-xl-3 col-sm-6 grid-margin stretch-card">
                <div class="card">
                    <div class="card-body">
                        <div class="row">
                            <div class="col-9">
                                <div class="d-flex align-items-center align-self-start">
                                    <h3 class="mb-0"><?php echo $total_gyms; ?></h3>
                                </div>
                            </div>
                            <div class="col-3">
                                <div class="icon icon-box-primary">
                                    <span class="mdi mdi-dumbbell icon-item"></span>
                                </div>
                            </div>
                        </div>
                        <h6 class="text-muted font-weight-normal">Total Gyms</h6>
                    </div>
                </div>
            </div>

            <!-- Active Gyms -->
            <div class="col-xl-3 col-sm-6 grid-margin stretch-card">
                <div class="card">
                    <div class="card-body">
                        <div class="row">
                            <div class="col-9">
                                <div class="d-flex align-items-center align-self-start">
                                    <h3 class="mb-0"><?php echo $active_gyms; ?></h3>
                                </div>
                            </div>
                            <div class="col-3">
                                <div class="icon icon-box-success">
                                    <span class="mdi mdi-check-circle icon-item"></span>
                                </div>
                            </div>
                        </div>
                        <h6 class="text-muted font-weight-normal">Active Gyms</h6>
                    </div>
                </div>
            </div>

            <!-- Pending Gyms -->
            <div class="col-xl-3 col-sm-6 grid-margin stretch-card">
                <div class="card">
                    <div class="card-body">
                        <div class="row">
                            <div class="col-9">
                                <div class="d-flex align-items-center align-self-start">
                                    <h3 class="mb-0"><?php echo $pending_gyms; ?></h3>
                                </div>
                            </div>
                            <div class="col-3">
                                <div class="icon icon-box-warning">
                                    <span class="mdi mdi-clock icon-item"></span>
                                </div>
                            </div>
                        </div>
                        <h6 class="text-muted font-weight-normal">Pending Gyms</h6>
                    </div>
                </div>
            </div>

            <!-- Inactive Gyms -->
            <div class="col-xl-3 col-sm-6 grid-margin stretch-card">
                <div class="card">
                    <div class="card-body">
                        <div class="row">
                            <div class="col-9">
                                <div class="d-flex align-items-center align-self-start">
                                    <h3 class="mb-0"><?php echo $inactive_gyms; ?></h3>
                                </div>
                            </div>
                            <div class="col-3">
                                <div class="icon icon-box-danger">
                                    <span class="mdi mdi-close-circle icon-item"></span>
                                </div>
                            </div>
                        </div>
                        <h6 class="text-muted font-weight-normal">Inactive Gyms</h6>
                    </div>
                </div>
            </div>
        </div>

        <!-- Plans Statistics -->
        <div class="row mt-4">
            <h4 class="mb-3">Subscription Plans Statistics</h4>
            
            <!-- Total Plans -->
            <div class="col-xl-3 col-sm-6 grid-margin stretch-card">
                <div class="card">
                    <div class="card-body">
                        <div class="row">
                            <div class="col-9">
                                <div class="d-flex align-items-center align-self-start">
                                    <h3 class="mb-0"><?php echo $total_plans; ?></h3>
                                </div>
                            </div>
                            <div class="col-3">
                                <div class="icon icon-box-info">
                                    <span class="mdi mdi-package-variant icon-item"></span>
                                </div>
                            </div>
                        </div>
                        <h6 class="text-muted font-weight-normal">Total Plans</h6>
                    </div>
                </div>
            </div>

            <!-- Active Plans -->
            <div class="col-xl-3 col-sm-6 grid-margin stretch-card">
                <div class="card">
                    <div class="card-body">
                        <div class="row">
                            <div class="col-9">
                                <div class="d-flex align-items-center align-self-start">
                                    <h3 class="mb-0"><?php echo $active_plans; ?></h3>
                                </div>
                            </div>
                            <div class="col-3">
                                <div class="icon icon-box-success">
                                    <span class="mdi mdi-check-circle-outline icon-item"></span>
                                </div>
                            </div>
                        </div>
                        <h6 class="text-muted font-weight-normal">Active Plans</h6>
                    </div>
                </div>
            </div>

            <!-- Inactive Plans -->
            <div class="col-xl-3 col-sm-6 grid-margin stretch-card">
                <div class="card">
                    <div class="card-body">
                        <div class="row">
                            <div class="col-9">
                                <div class="d-flex align-items-center align-self-start">
                                    <h3 class="mb-0"><?php echo $inactive_plans; ?></h3>
                                </div>
                            </div>
                            <div class="col-3">
                                <div class="icon icon-box-warning">
                                    <span class="mdi mdi-pause-circle icon-item"></span>
                                </div>
                            </div>
                        </div>
                        <h6 class="text-muted font-weight-normal">Inactive Plans</h6>
                    </div>
                </div>
            </div>

            <!-- Popular Plans -->
            <div class="col-xl-3 col-sm-6 grid-margin stretch-card">
                <div class="card">
                    <div class="card-body">
                        <div class="row">
                            <div class="col-9">
                                <div class="d-flex align-items-center align-self-start">
                                    <h3 class="mb-0"><?php echo $popular_plans; ?></h3>
                                </div>
                            </div>
                            <div class="col-3">
                                <div class="icon icon-box-danger">
                                    <span class="mdi mdi-star-circle icon-item"></span>
                                </div>
                            </div>
                        </div>
                        <h6 class="text-muted font-weight-normal">Popular Plans</h6>
                    </div>
                </div>
            </div>
        </div>

        <!-- Charts Row -->
    <div class="row mt-4">
    <!-- Gyms Status Chart -->
    <div class="col-md-6 grid-margin stretch-card">
        <div class="card">
            <div class="card-body">
                <h4 class="card-title mb-2">Gyms Status Distribution</h4>
                <div class="chart-container" style="height: 250px;">
                    <canvas id="gymsChart"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- Plans Status Chart -->
    <div class="col-md-6 grid-margin stretch-card">
        <div class="card">
            <div class="card-body">
                <h4 class="card-title mb-2">Plans Status Distribution</h4>
                <div class="chart-container" style="height: 250px;">
                    <canvas id="plansChart"></canvas>
                </div>
            </div>
        </div>
    </div>
</div>
        <!-- Recent Items Row -->
        <div class="row mt-4">
            <!-- Recent Gyms Table -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center mb-4">
                            <h4 class="card-title mb-0">Recently Added Gyms</h4>
                            <a href="gyms.php" class="btn btn-primary btn-sm">View All</a>
                        </div>
                        
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Gym Name</th>
                                        <th>Owner</th>
                                        <th>Status</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (empty($recent_gyms)): ?>
                                        <tr>
                                            <td colspan="4" class="text-center py-4">
                                                <div class="text-muted">
                                                    <i class="mdi mdi-database-remove mdi-24px mb-2"></i><br>
                                                    No gyms found.
                                                </div>
                                            </td>
                                        </tr>
                                    <?php else: ?>
                                        <?php foreach ($recent_gyms as $gym): 
                                            $status_class = $gym['status'] == 'active' ? 'badge-success' : 
                                                          ($gym['status'] == 'pending' ? 'badge-warning' : 'badge-danger');
                                        ?>
                                        <tr>
                                            <td>
                                                <strong><?php echo htmlspecialchars($gym['name']); ?></strong>
                                            </td>
                                            <td><?php echo htmlspecialchars($gym['owner_name']); ?></td>
                                            <td>
                                                <span class="badge <?php echo $status_class; ?>">
                                                    <?php echo ucfirst($gym['status']); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <a href="gyms.php?edit_id=<?php echo $gym['id']; ?>" class="btn btn-primary btn-icon">
                                                    <i class="mdi mdi-eye"></i>
                                                </a>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Recent Plans Table -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center mb-4">
                            <h4 class="card-title mb-0">Recent Subscription Plans</h4>
                            <a href="plans.php" class="btn btn-primary btn-sm">View All</a>
                        </div>
                        
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Plan Name</th>
                                        <th>Monthly Price</th>
                                        <th>Status</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (empty($recent_plans)): ?>
                                        <tr>
                                            <td colspan="4" class="text-center py-4">
                                                <div class="text-muted">
                                                    <i class="mdi mdi-package-variant-remove mdi-24px mb-2"></i><br>
                                                    No plans found.
                                                </div>
                                            </td>
                                        </tr>
                                    <?php else: ?>
                                        <?php foreach ($recent_plans as $plan): 
                                            $status_class = $plan['status'] == 'active' ? 'badge-success' : 'badge-danger';
                                            $popular_badge = $plan['is_popular'] ? '<span class="badge bg-warning ms-1">Popular</span>' : '';
                                        ?>
                                        <tr>
                                            <td>
                                                <strong><?php echo htmlspecialchars($plan['name']); ?></strong>
                                                <?php echo $popular_badge; ?>
                                            </td>
                                            <td>$<?php echo number_format($plan['price_monthly'], 2); ?></td>
                                            <td>
                                                <span class="badge <?php echo $status_class; ?>">
                                                    <?php echo ucfirst($plan['status']); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <a href="plans.php?edit_id=<?php echo $plan['id']; ?>" class="btn btn-primary btn-icon">
                                                    <i class="mdi mdi-eye"></i>
                                                </a>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <?php include 'includes/footer.php'; ?>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Gyms Status Chart (Doughnut)
    const gymsCtx = document.getElementById('gymsChart').getContext('2d');
    const gymsChart = new Chart(gymsCtx, {
        type: 'doughnut',
        data: {
            labels: ['Active Gyms', 'Pending Gyms', 'Inactive Gyms'],
            datasets: [{
                data: [<?php echo $active_gyms; ?>, <?php echo $pending_gyms; ?>, <?php echo $inactive_gyms; ?>],
                backgroundColor: ['#4CAF50', '#FFC107', '#F44336'],
                borderWidth: 2,
                borderColor: '#fff',
                hoverOffset: 10
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: {
                        padding: 8,
                        usePointStyle: true,
                        boxWidth: 6,
                        font: {
                            size: 10
                        }
                    }
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            const label = context.label || '';
                            const value = context.raw || 0;
                            const total = context.dataset.data.reduce((a, b) => a + b, 0);
                            const percentage = Math.round((value / total) * 100);
                            return `${label}: ${value} (${percentage}%)`;
                        }
                    }
                }
            },
            cutout: '65%'
        }
    });

    // Plans Status Chart (Pie)
    const plansCtx = document.getElementById('plansChart').getContext('2d');
    const plansChart = new Chart(plansCtx, {
        type: 'pie',
        data: {
            labels: ['Active Plans', 'Inactive Plans', 'Popular Plans'],
            datasets: [{
                data: [<?php echo $active_plans; ?>, <?php echo $inactive_plans; ?>, <?php echo $popular_plans; ?>],
                backgroundColor: ['#4CAF50', '#F44336', '#FF9800'],
                borderWidth: 2,
                borderColor: '#fff',
                hoverOffset: 10
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: {
                        padding: 8,
                        usePointStyle: true,
                        boxWidth: 6,
                        font: {
                            size: 10
                        }
                    }
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            const label = context.label || '';
                            const value = context.raw || 0;
                            const total = context.dataset.data.reduce((a, b) => a + b, 0);
                            const percentage = Math.round((value / total) * 100);
                            return `${label}: ${value} (${percentage}%)`;
                        }
                    }
                }
            }
        }
    });
});
</script>

<style>
.quick-action-card {
    transition: transform 0.3s ease, box-shadow 0.3s ease;
    border: 1px solid #e0e0e0;
}

.quick-action-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 5px 15px rgba(0,0,0,0.1);
    text-decoration: none;
}

.icon-box {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto;
}

.icon-box i {
    font-size: 24px;
}

.btn-icon {
    width: 32px;
    height: 32px;
    padding: 0;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    margin: 2px;
}

.icon-box-info {
    background: rgba(33, 150, 243, 0.2);
    color: #2196F3;
}

.icon-box-success {
    background: rgba(76, 175, 80, 0.2);
    color: #4CAF50;
}

.icon-box-warning {
    background: rgba(255, 193, 7, 0.2);
    color: #FFC107;
}

.icon-box-danger {
    background: rgba(244, 67, 54, 0.2);
    color: #F44336;
}

.card {
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    border: 1px solid #e0e0e0;
}

.card-title {
    color: #333;
    font-weight: 600;
    font-size: 1.1rem;
}

/* Compact chart styling */
.chart-container {
    position: relative;
    margin: 0 auto;
}

.card .card-body {
    padding: 1rem;
}
</style>