<?php
require_once 'config/database.php';
secureSessionStart();
requireLogin();

$conn = getConnection();
$admin_user = $_SESSION['admin_user'];

// Get real statistics from your database
$stats = [];

// Total users
$result = mysqli_query($conn, "SELECT COUNT(*) as total FROM users");
$stats['total_users'] = mysqli_fetch_assoc($result)['total'];

// Active users (status = 1)
$result = mysqli_query($conn, "SELECT COUNT(*) as total FROM users WHERE status = 1");
$stats['active_users'] = mysqli_fetch_assoc($result)['total'];

// Inactive users (status = 0)
$result = mysqli_query($conn, "SELECT COUNT(*) as total FROM users WHERE status = 0");
$stats['inactive_users'] = mysqli_fetch_assoc($result)['total'];

// Total wallet balance
$result = mysqli_query($conn, "SELECT SUM(wallet) as total FROM users");
$stats['total_wallet'] = mysqli_fetch_assoc($result)['total'] ?? 0;

// Total pins
$result = mysqli_query($conn, "SELECT COUNT(*) as total FROM pin");
$stats['total_pins'] = mysqli_fetch_assoc($result)['total'];

// Used pins
$result = mysqli_query($conn, "SELECT COUNT(*) as total FROM pin WHERE status = 1");
$stats['used_pins'] = mysqli_fetch_assoc($result)['total'];

// Unused pins
$result = mysqli_query($conn, "SELECT COUNT(*) as total FROM pin WHERE status = 0");
$stats['unused_pins'] = mysqli_fetch_assoc($result)['total'];

// Total income
$result = mysqli_query($conn, "SELECT SUM(amount) as total FROM income_history WHERE credit_debit = 1");
$stats['total_income'] = mysqli_fetch_assoc($result)['total'] ?? 0;

// Pending withdrawals
$result = mysqli_query($conn, "SELECT COUNT(*) as total FROM witdrawl WHERE status = 0");
$stats['pending_withdrawals'] = mysqli_fetch_assoc($result)['total'];

// Recent users
$recent_users = mysqli_query($conn, "SELECT * FROM users ORDER BY id DESC LIMIT 10");

// Company details
$company = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM com_details WHERE id = 1"));

// Get today's registrations
$today = date('Y-m-d');
$result = mysqli_query($conn, "SELECT COUNT(*) as total FROM users WHERE DATE(created_at) = '$today'");
$stats['today_registrations'] = mysqli_fetch_assoc($result)['total'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <title>Admin Dashboard - MLM System</title>
    
    <!-- Google Fonts -->
    <link href="https://fonts.gstatic.com" rel="preconnect">
    <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Nunito:300,300i,400,400i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i" rel="stylesheet">

    <!-- Vendor CSS Files -->
    <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
    <link href="assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet">
    <link href="assets/vendor/remixicon/remixicon.css" rel="stylesheet">
    <link href="assets/vendor/simple-datatables/style.css" rel="stylesheet">

    <!-- Template Main CSS File -->
    <link href="assets/css/style.css" rel="stylesheet">
</head>

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

    <main id="main" class="main">
        <div class="pagetitle">
            <h1>Dashboard</h1>
            <nav>
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="index.php">Home</a></li>
                    <li class="breadcrumb-item active">Dashboard</li>
                </ol>
            </nav>
        </div>

        <section class="section dashboard">
            <div class="row">
                <!-- Statistics Cards -->
                <div class="col-xxl-3 col-md-6">
                    <div class="card info-card sales-card">
                        <div class="card-body">
                            <h5 class="card-title">Total Users</h5>
                            <div class="d-flex align-items-center">
                                <div class="card-icon rounded-circle d-flex align-items-center justify-content-center">
                                    <i class="bi bi-people"></i>
                                </div>
                                <div class="ps-3">
                                    <h6><?php echo number_format($stats['total_users']); ?></h6>
                                    <span class="text-success small pt-1 fw-bold">+<?php echo $stats['today_registrations']; ?></span> <span class="text-muted small pt-2 ps-1">today</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-xxl-3 col-md-6">
                    <div class="card info-card revenue-card">
                        <div class="card-body">
                            <h5 class="card-title">Active Users</h5>
                            <div class="d-flex align-items-center">
                                <div class="card-icon rounded-circle d-flex align-items-center justify-content-center">
                                    <i class="bi bi-person-check"></i>
                                </div>
                                <div class="ps-3">
                                    <h6><?php echo number_format($stats['active_users']); ?></h6>
                                    <span class="text-success small pt-1 fw-bold"><?php echo round(($stats['active_users']/$stats['total_users'])*100, 1); ?>%</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-xxl-3 col-md-6">
                    <div class="card info-card customers-card">
                        <div class="card-body">
                            <h5 class="card-title">Total Wallet</h5>
                            <div class="d-flex align-items-center">
                                <div class="card-icon rounded-circle d-flex align-items-center justify-content-center">
                                    <i class="bi bi-wallet2"></i>
                                </div>
                                <div class="ps-3">
                                    <h6>₹<?php echo number_format($stats['total_wallet'], 2); ?></h6>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-xxl-3 col-md-6">
                    <div class="card info-card">
                        <div class="card-body">
                            <h5 class="card-title">Total Income</h5>
                            <div class="d-flex align-items-center">
                                <div class="card-icon rounded-circle d-flex align-items-center justify-content-center">
                                    <i class="bi bi-cash-stack"></i>
                                </div>
                                <div class="ps-3">
                                    <h6>₹<?php echo number_format($stats['total_income'], 2); ?></h6>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Second Row -->
                <div class="col-xxl-3 col-md-6">
                    <div class="card info-card">
                        <div class="card-body">
                            <h5 class="card-title">Total Pins</h5>
                            <div class="d-flex align-items-center">
                                <div class="card-icon rounded-circle d-flex align-items-center justify-content-center">
                                    <i class="bi bi-key"></i>
                                </div>
                                <div class="ps-3">
                                    <h6><?php echo number_format($stats['total_pins']); ?></h6>
                                    <span class="text-success small"><?php echo $stats['used_pins']; ?> used</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-xxl-3 col-md-6">
                    <div class="card info-card">
                        <div class="card-body">
                            <h5 class="card-title">Available Pins</h5>
                            <div class="d-flex align-items-center">
                                <div class="card-icon rounded-circle d-flex align-items-center justify-content-center">
                                    <i class="bi bi-key-fill"></i>
                                </div>
                                <div class="ps-3">
                                    <h6><?php echo number_format($stats['unused_pins']); ?></h6>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-xxl-3 col-md-6">
                    <div class="card info-card">
                        <div class="card-body">
                            <h5 class="card-title">Pending Withdrawals</h5>
                            <div class="d-flex align-items-center">
                                <div class="card-icon rounded-circle d-flex align-items-center justify-content-center">
                                    <i class="bi bi-clock-history"></i>
                                </div>
                                <div class="ps-3">
                                    <h6><?php echo number_format($stats['pending_withdrawals']); ?></h6>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-xxl-3 col-md-6">
                    <div class="card info-card">
                        <div class="card-body">
                            <h5 class="card-title">Inactive Users</h5>
                            <div class="d-flex align-items-center">
                                <div class="card-icon rounded-circle d-flex align-items-center justify-content-center">
                                    <i class="bi bi-person-x"></i>
                                </div>
                                <div class="ps-3">
                                    <h6><?php echo number_format($stats['inactive_users']); ?></h6>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Recent Users Table -->
                <div class="col-12">
                    <div class="card recent-sales overflow-auto">
                        <div class="card-body">
                            <h5 class="card-title">Recent Registrations</h5>
                            <table class="table table-borderless datatable">
                                <thead>
                                    <tr>
                                        <th scope="col">#</th>
                                        <th scope="col">User ID</th>
                                        <th scope="col">Name</th>
                                        <th scope="col">Mobile</th>
                                        <th scope="col">Sponsor</th>
                                        <th scope="col">Package</th>
                                        <th scope="col">Status</th>
                                        <th scope="col">Joined</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php 
                                    $i = 1;
                                    while ($user = mysqli_fetch_assoc($recent_users)): 
                                    ?>
                                    <tr>
                                        <th scope="row"><?php echo $i++; ?></th>
                                        <td><?php echo $user['user_id']; ?></td>
                                        <td><?php echo htmlspecialchars($user['name']); ?></td>
                                        <td><?php echo $user['mobile']; ?></td>
                                        <td><?php echo $user['sponsor_id'] ?: 'N/A'; ?></td>
                                        <td>
                                            <?php 
                                            if ($user['package_id'] == 2500) echo 'Basic';
                                            elseif ($user['package_id'] == 3500) echo 'Premium';
                                            else echo 'N/A';
                                            ?>
                                        </td>
                                        <td>
                                            <?php if ($user['status'] == 1): ?>
                                                <span class="badge bg-success">Active</span>
                                            <?php else: ?>
                                                <span class="badge bg-warning">Inactive</span>
                                            <?php endif; ?>
                                        </td>
                                        <td><?php echo date('d M Y', strtotime($user['joining_date'])); ?></td>
                                    </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Income Chart and Stats -->
                <div class="col-12">
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title">Income Overview</h5>
                            <div id="incomeChart" style="min-height: 300px;"></div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </main>

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

    <!-- Vendor JS Files -->
    <script src="assets/vendor/apexcharts/apexcharts.min.js"></script>
    <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="assets/vendor/simple-datatables/simple-datatables.js"></script>

    <!-- Template Main JS File -->
    <script src="assets/js/main.js"></script>

    <script>
    // Income Chart
    document.addEventListener("DOMContentLoaded", () => {
        new ApexCharts(document.querySelector("#incomeChart"), {
            series: [{
                name: 'Income',
                data: [30, 40, 35, 50, 49, 60, 70, 91, 125, 100, 110, 130]
            }],
            chart: {
                height: 350,
                type: 'area',
                toolbar: { show: false }
            },
            markers: { size: 4 },
            colors: ['#4154f1'],
            fill: {
                type: "gradient",
                gradient: {
                    shadeIntensity: 1,
                    opacityFrom: 0.3,
                    opacityTo: 0.4
                }
            },
            dataLabels: { enabled: false },
            stroke: { curve: 'smooth', width: 2 },
            xaxis: {
                categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
            }
        }).render();
    });
    </script>
</body>
</html>
<?php mysqli_close($conn); ?>