<?php
session_start();
include_once('includes/config.php');

if (!isset($_SESSION['uid'])) {
    header('location:login.php');
    exit();
}

$userId = $_SESSION['uid'];
$userType = $_SESSION['usertype'] ?? 'admin';

// Initialize statistics arrays
$userStats = ['TotalUsers' => 0, 'ActiveUsers' => 0, 'InactiveUsers' => 0];
$roleStats = ['TotalRoles' => 0, 'ActiveRoles' => 0];
$permissionStats = ['TotalPermissions' => 0, 'AssignedPermissions' => 0];
$adminStats = ['TotalAdmins' => 0];
$inventoryStats = ['TotalItems' => 0, 'ActiveItems' => 0, 'LowStockItems' => 0, 'OutOfStockItems' => 0];
$salesStats = ['TodaySales' => 0, 'TotalSales' => 0, 'TotalRevenue' => 0, 'MonthSales' => 0, 'MonthRevenue' => 0];
$recentActivities = [];

// Get real data from database
if (isset($con) && $con) {
    // Determine available user columns to stay compatible with older schemas
    $userStatusColumnExists = false;
    $userCreatedDateColumnExists = false;

    $statusCheck = mysqli_query($con, "SHOW COLUMNS FROM tblusers LIKE 'Status'");
    if ($statusCheck) {
        $userStatusColumnExists = mysqli_num_rows($statusCheck) > 0;
        mysqli_free_result($statusCheck);
    }

    $createdDateCheck = mysqli_query($con, "SHOW COLUMNS FROM tblusers LIKE 'CreatedDate'");
    if ($createdDateCheck) {
        $userCreatedDateColumnExists = mysqli_num_rows($createdDateCheck) > 0;
        mysqli_free_result($createdDateCheck);
    }

    $recentDateColumn = $userCreatedDateColumnExists ? 'CreatedDate' : 'RegDate';
    $recentStatusSelect = $userStatusColumnExists ? 'u.Status' : "'Active'";

    // Get user statistics
    $result = mysqli_query($con, "SELECT COUNT(*) as total FROM tblusers");
    if ($result) {
        $data = mysqli_fetch_assoc($result);
        $userStats['TotalUsers'] = $data['total'];
        mysqli_free_result($result);
    }
    
    if ($userStatusColumnExists) {
        $result = mysqli_query($con, "SELECT COUNT(*) as total FROM tblusers WHERE Status = 'Active'");
        if ($result) {
            $data = mysqli_fetch_assoc($result);
            $userStats['ActiveUsers'] = $data['total'];
            mysqli_free_result($result);
        }
        $userStats['InactiveUsers'] = max($userStats['TotalUsers'] - $userStats['ActiveUsers'], 0);
    } else {
        $userStats['ActiveUsers'] = $userStats['TotalUsers'];
        $userStats['InactiveUsers'] = 0;
    }
    
    // Get role statistics
    $result = mysqli_query($con, "SELECT COUNT(*) as total FROM tblroles");
    if ($result) {
        $data = mysqli_fetch_assoc($result);
        $roleStats['TotalRoles'] = $data['total'];
        mysqli_free_result($result);
    }

    $result = mysqli_query($con, "SELECT COUNT(*) as total FROM tblroles WHERE Status = 'Active'");
    if ($result) {
        $data = mysqli_fetch_assoc($result);
        $roleStats['ActiveRoles'] = $data['total'];
        mysqli_free_result($result);
    }
    
    // Get permission statistics
    $result = mysqli_query($con, "SELECT COUNT(*) as total FROM tblpermissions");
    if ($result) {
        $data = mysqli_fetch_assoc($result);
        $permissionStats['TotalPermissions'] = $data['total'];
        mysqli_free_result($result);
    }

    $result = mysqli_query($con, "SELECT COUNT(DISTINCT PermissionID) as total FROM tblrolepermissions");
    if ($result) {
        $data = mysqli_fetch_assoc($result);
        $permissionStats['AssignedPermissions'] = $data['total'];
        mysqli_free_result($result);
    }
    
    // Get admin count
    $result = mysqli_query($con, "SELECT COUNT(*) as total FROM tbladmin");
    if ($result) {
        $data = mysqli_fetch_assoc($result);
        $adminStats['TotalAdmins'] = $data['total'];
        mysqli_free_result($result);
    }
    
    // Get inventory statistics
    $result = mysqli_query($con, "SELECT COUNT(*) as total FROM tblitems");
    if ($result) {
        $data = mysqli_fetch_assoc($result);
        $inventoryStats['TotalItems'] = $data['total'];
        mysqli_free_result($result);
    }

    $result = mysqli_query($con, "SELECT COUNT(*) as total FROM tblitems WHERE Status = 'Active'");
    if ($result) {
        $data = mysqli_fetch_assoc($result);
        $inventoryStats['ActiveItems'] = $data['total'];
        mysqli_free_result($result);
    }

    $result = mysqli_query($con, "SELECT COUNT(*) as total FROM tblitems WHERE Status = 'Active' AND CurrentStock <= AlertQuantity AND CurrentStock > 0");
    if ($result) {
        $data = mysqli_fetch_assoc($result);
        $inventoryStats['LowStockItems'] = $data['total'];
        mysqli_free_result($result);
    }

    $result = mysqli_query($con, "SELECT COUNT(*) as total FROM tblitems WHERE Status = 'Active' AND CurrentStock <= 0");
    if ($result) {
        $data = mysqli_fetch_assoc($result);
        $inventoryStats['OutOfStockItems'] = $data['total'];
        mysqli_free_result($result);
    }
    
    // Get sales statistics
    $result = mysqli_query($con, "SELECT 
        COUNT(*) as TotalSales,
        COALESCE(SUM(FinalAmount), 0) as TotalRevenue,
        COALESCE(SUM(CASE WHEN SaleDate = CURDATE() THEN FinalAmount ELSE 0 END), 0) as TodaySales,
        COALESCE(SUM(CASE WHEN MONTH(SaleDate) = MONTH(CURDATE()) AND YEAR(SaleDate) = YEAR(CURDATE()) THEN 1 ELSE 0 END), 0) as MonthSalesCount,
        COALESCE(SUM(CASE WHEN MONTH(SaleDate) = MONTH(CURDATE()) AND YEAR(SaleDate) = YEAR(CURDATE()) THEN FinalAmount ELSE 0 END), 0) as MonthRevenue
        FROM tblsales");
    if ($result) {
        $data = mysqli_fetch_assoc($result);
        $salesStats['TotalSales'] = $data['TotalSales'];
        $salesStats['TotalRevenue'] = $data['TotalRevenue'];
        $salesStats['TodaySales'] = $data['TodaySales'];
        $salesStats['MonthSales'] = $data['MonthSalesCount'];
        $salesStats['MonthRevenue'] = $data['MonthRevenue'];
        mysqli_free_result($result);
    }
    
    // Get recent user registrations (limit 5)
    $recentUsersQuery = "SELECT u.FullName, u.Email, r.RoleName, u.$recentDateColumn AS CreatedDate, $recentStatusSelect AS Status
                                   FROM tblusers u 
                                   LEFT JOIN tblroles r ON u.RoleID = r.ID 
                                   ORDER BY u.$recentDateColumn DESC LIMIT 5";
    $result = mysqli_query($con, $recentUsersQuery);
    if ($result) {
        while ($row = mysqli_fetch_assoc($result)) {
            $recentActivities[] = $row;
        }
        mysqli_free_result($result);
    }
}

// Calculate metrics
$userActivityRate = $userStats['TotalUsers'] > 0 ? round(($userStats['ActiveUsers'] / $userStats['TotalUsers']) * 100) : 0;
$permissionUtilization = $permissionStats['TotalPermissions'] > 0 ? round(($permissionStats['AssignedPermissions'] / $permissionStats['TotalPermissions']) * 100) : 0;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Dashboard | PetrolBunk Management System</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link href="css/sb-admin-2.min.css" rel="stylesheet">
    <link href="css/modern-messagebox.css" rel="stylesheet">
    <link href="css/mobile-dashboard.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        /* Compact dashboard design */
        .dashboard-card {
            background: #ffffff;
            border: 1px solid #e3e6f0;
            border-radius: 8px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
            transition: all 0.2s ease;
            overflow: hidden;
            margin-bottom: 0.75rem;
        }
        
        .dashboard-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 3px 8px rgba(0, 0, 0, 0.1);
        }
        
        .metric-card {
            position: relative;
            overflow: hidden;
        }
        
        .metric-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 3px;
            background: var(--accent-color, #4e73df);
        }
        
        .metric-value {
            font-size: 1.5rem;
            font-weight: 700;
            color: #2c3e50;
            margin-bottom: 0;
            display: flex;
            align-items: center;
            gap: 0.25rem;
        }
        
        .metric-label {
            font-size: 0.7rem;
            color: #858796;
            text-transform: uppercase;
            letter-spacing: 0.3px;
            font-weight: 600;
            margin-bottom: 0.25rem;
        }
        
        .metric-change {
            font-size: 0.65rem;
            padding: 1px 6px;
            border-radius: 8px;
            font-weight: 600;
        }
        
        .metric-change.positive {
            background: #d4edda;
            color: #155724;
        }
        
        .metric-change.negative {
            background: #f8d7da;
            color: #721c24;
        }
        
        .metric-icon {
            width: 36px;
            height: 36px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.1rem;
            color: white;
        }
        
        .icon-revenue { background: linear-gradient(135deg, #28a745, #20c997); }
        .icon-bookings { background: linear-gradient(135deg, #007bff, #6610f2); }
        .icon-occupancy { background: linear-gradient(135deg, #fd7e14, #dc3545); }
        .icon-expenses { background: linear-gradient(135deg, #6c757d, #495057); }
        
        .quick-stats {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 8px;
            padding: 0.75rem;
            margin-bottom: 0.75rem;
        }
        
        .stat-item {
            text-align: center;
            padding: 0.5rem 0;
        }
        
        .stat-number {
            font-size: 1.3rem;
            font-weight: 700;
            margin-bottom: 0.15rem;
        }
        
        .stat-label {
            font-size: 0.65rem;
            opacity: 0.9;
            text-transform: uppercase;
            letter-spacing: 0.3px;
        }
        
        .chart-container {
            position: relative;
            height: 180px;
            margin: 0.5rem 0;
        }
        
        .recent-activity {
            max-height: 300px;
            overflow-y: auto;
        }
        
        .activity-item {
            display: flex;
            align-items: center;
            padding: 0.5rem;
            border-bottom: 1px solid #eee;
            transition: background 0.2s;
        }
        
        .activity-item:hover {
            background: #f8f9fc;
        }
        
        .activity-icon {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 0.75rem;
            color: white;
            font-size: 0.75rem;
        }
        
        .activity-confirmed { background: #28a745; }
        .activity-checkin { background: #007bff; }
        .activity-checkout { background: #6c757d; }
        
        .page-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 0.75rem 1rem;
            border-radius: 8px;
            margin-bottom: 0.75rem;
            text-align: left;
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 0.75rem;
            flex-wrap: wrap;
        }
        
        .page-header-content {
            flex: 1 1 auto;
            min-width: 180px;
        }
        
        .quick-menu {
            position: relative;
            flex: 0 0 auto;
        }
        
        .quick-menu-toggle {
            display: inline-flex;
            align-items: center;
            gap: 0.35rem;
            background: rgba(255, 255, 255, 0.15);
            color: #fff;
            border: 1px solid rgba(255, 255, 255, 0.3);
            border-radius: 50px;
            padding: 0.35rem 0.75rem;
            font-weight: 600;
            font-size: 0.8rem;
            transition: all 0.2s ease;
        }
        
        .quick-menu-toggle:hover,
        .quick-menu-toggle:focus {
            background: rgba(255, 255, 255, 0.25);
            color: #fff;
            text-decoration: none;
            outline: none;
        }

        .quick-menu-dropdown {
            position: absolute;
            top: calc(100% + 8px);
            right: 0;
            background: #ffffff;
            color: #2c3e50;
            border-radius: 8px;
            min-width: 200px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
            padding: 0.5rem 0;
            display: none;
            z-index: 1050;
        }

        .quick-menu-dropdown.show {
            display: block;
            animation: fadeInUp 0.2s ease forwards;
        }

        .quick-menu-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .quick-menu-list li a {
            display: flex;
            align-items: center;
            gap: 0.6rem;
            padding: 0.4rem 0.75rem;
            color: inherit;
            text-decoration: none;
            font-weight: 600;
            font-size: 0.8rem;
            transition: background 0.2s ease;
        }

        .quick-menu-list li a:hover,
        .quick-menu-list li a:focus {
            background: #f1f5f9;
            color: inherit;
        }

        .quick-menu-list li a i {
            width: 16px;
            text-align: center;
            font-size: 0.75rem;
        }

        .quick-menu-empty {
            padding: 0.4rem 0.75rem;
            font-size: 0.75rem;
        }

        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(8px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .welcome-text {
            font-size: 0.8rem;
            opacity: 0.9;
            margin-bottom: 0;
        }
        
        .dashboard-title {
            font-size: 1.3rem;
            font-weight: 700;
            margin-bottom: 0.25rem;
        }
        
        /* Mobile optimizations */
        @media (max-width: 768px) {
            .container-fluid {
                padding: 0.5rem;
            }
            
            .dashboard-card {
                margin-bottom: 0.5rem;
            }
            
            .metric-value {
                font-size: 1.2rem;
            }
            
            .page-header {
                padding: 0.75rem;
                margin-bottom: 0.75rem;
                flex-direction: column;
                align-items: stretch;
            }
            
            .quick-menu {
                width: 100%;
            }

            .quick-menu-toggle {
                justify-content: center;
                width: 100%;
            }

            .quick-menu-dropdown {
                position: static;
                margin-top: 0.5rem;
                box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12);
            }

            .dashboard-title {
                font-size: 1.1rem;
            }
            
            .chart-container {
                height: 150px;
            }
            
            .stat-number {
                font-size: 1.1rem;
            }
            
            .metric-icon {
                width: 30px;
                height: 30px;
                font-size: 0.9rem;
            }
        }
        
        /* Status badges */
        .status-badge {
            padding: 3px 8px;
            border-radius: 12px;
            font-size: 0.65rem;
            font-weight: 600;
            text-transform: uppercase;
        }
        
        .status-confirmed { background: #d1ecf1; color: #0c5460; }
        .status-checkedin { background: #d4edda; color: #155724; }
        .status-checkedout { background: #f8d7da; color: #721c24; }
        
        /* Sidebar mobile optimization */
        @media (max-width: 768px) {
            body.sidebar-toggled .sidebar {
                transform: translateX(-100%);
            }
            
            #content-wrapper {
                margin-left: 0 !important;
            }
        }
        
        /* Compact card body */
        .dashboard-card .card-body {
            padding: 0.75rem !important;
        }
        
        .dashboard-card .card-header {
            padding: 0.5rem 0.75rem !important;
        }
        
        .dashboard-card .card-footer {
            padding: 0.5rem 0.75rem !important;
        }
        
        /* Compact list group */
        .list-group-item {
            padding: 0.5rem 0.75rem !important;
            margin-bottom: 0.4rem !important;
        }
        
        .list-group-item strong {
            font-size: 0.85rem;
        }
        
        .list-group-item small {
            font-size: 0.7rem;
        }
        
        /* Compact activity items */
        .activity-item h6 {
            font-size: 0.85rem;
            margin-bottom: 0.25rem !important;
        }
        
        .activity-item p {
            font-size: 0.7rem;
            margin-bottom: 0.15rem !important;
        }
        
        .activity-item small {
            font-size: 0.65rem;
        }

    </style>
</head>
<body id="page-top">
    <div id="wrapper">
        <?php include_once('includes/sidebar.php');?>
        <div id="content-wrapper" class="d-flex flex-column">
            <div id="content">
                <?php include_once('includes/topbar.php');?>
                
                <!-- Begin Page Content -->
                <div class="container-fluid">
                    
                    <!-- Page Header -->
                    <div class="page-header">
                        <div class="page-header-content">
                            <h1 class="dashboard-title">
                                <i class="fas fa-tachometer-alt mr-2"></i>Dashboard
                            </h1>
                            <p class="welcome-text mb-0">
                                Welcome back! Here's your system overview
                            </p>
                        </div>
                        <!-- Database Backup Buttons -->
                        <div style="display: flex; gap: 0.5rem; flex-wrap: wrap;">
                            <a href="api/backup-database-dual.php?source=local" class="btn btn-sm" style="background: #28a745; color: white; border: none; border-radius: 20px; padding: 0.4rem 0.9rem; font-weight: 600; font-size: 0.75rem;" title="Download Local Database Backup">
                                <i class="fas fa-download mr-1"></i>Local Backup
                            </a>
                            <a href="api/backup-database-dual.php?source=cloud" class="btn btn-sm" style="background: #17a2b8; color: white; border: none; border-radius: 20px; padding: 0.4rem 0.9rem; font-weight: 600; font-size: 0.75rem;" title="Download Cloud Database Backup">
                                <i class="fas fa-cloud-download-alt mr-1"></i>Cloud Backup
                            </a>
                        </div>
                    </div>

                    <!-- Today's Quick Stats -->
                    <div class="quick-stats">
                        <div class="row text-center">
                            <div class="col-6 col-md-3 stat-item">
                                <div class="stat-number">₹<?php echo number_format($salesStats['TodaySales'], 2); ?></div>
                                <div class="stat-label">Today's Sales</div>
                            </div>
                            <div class="col-6 col-md-3 stat-item">
                                <div class="stat-number">₹<?php echo number_format($salesStats['MonthRevenue'], 2); ?></div>
                                <div class="stat-label">This Month</div>
                            </div>
                            <div class="col-6 col-md-3 stat-item">
                                <div class="stat-number" style="color: #ffc107;"><?php echo $inventoryStats['LowStockItems']; ?></div>
                                <div class="stat-label">Low Stock</div>
                            </div>
                            <div class="col-6 col-md-3 stat-item">
                                <div class="stat-number" style="color: #dc3545;"><?php echo $inventoryStats['OutOfStockItems']; ?></div>
                                <div class="stat-label">Out of Stock</div>
                            </div>
                        </div>
                    </div>

                    <!-- Key Metrics Cards -->
                    <div class="row">
                        <!-- Total Revenue -->
                        <div class="col-lg-3 col-md-6 mb-3">
                            <div class="dashboard-card metric-card" style="--accent-color: #1cc88a;">
                                <div class="card-body p-3">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <div class="metric-label">Total Revenue</div>
                                            <div class="metric-value">
                                                ₹<?php echo number_format($salesStats['TotalRevenue'], 2); ?>
                                            </div>
                                            <small class="metric-change positive">
                                                <i class="fas fa-shopping-cart"></i> <?php echo $salesStats['TotalSales']; ?> Sales
                                            </small>
                                        </div>
                                        <div class="metric-icon icon-revenue">
                                            <i class="fas fa-rupee-sign"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- This Month Sales -->
                        <div class="col-lg-3 col-md-6 mb-3">
                            <div class="dashboard-card metric-card" style="--accent-color: #4e73df;">
                                <div class="card-body p-3">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <div class="metric-label">This Month</div>
                                            <div class="metric-value">
                                                ₹<?php echo number_format($salesStats['MonthRevenue'], 2); ?>
                                            </div>
                                            <small class="metric-change positive">
                                                <i class="fas fa-chart-line"></i> <?php echo $salesStats['MonthSales']; ?> Sales
                                            </small>
                                        </div>
                                        <div class="metric-icon icon-bookings">
                                            <i class="fas fa-calendar-alt"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Inventory Overview -->
                        <div class="col-lg-3 col-md-6 mb-3">
                            <div class="dashboard-card metric-card" style="--accent-color: #f6c23e;">
                                <div class="card-body p-3">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <div class="metric-label">Inventory Items</div>
                                            <div class="metric-value">
                                                <?php echo $inventoryStats['TotalItems']; ?>
                                            </div>
                                            <small class="metric-change <?php echo $inventoryStats['ActiveItems'] > 0 ? 'positive' : 'negative'; ?>">
                                                <i class="fas fa-box"></i> 
                                                <?php echo $inventoryStats['ActiveItems']; ?> Active
                                            </small>
                                        </div>
                                        <div class="metric-icon icon-occupancy">
                                            <i class="fas fa-boxes"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Total Users -->
                        <div class="col-lg-3 col-md-6 mb-3">
                            <div class="dashboard-card metric-card" style="--accent-color: #e74a3b;">
                                <div class="card-body p-3">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <div class="metric-label">System Users</div>
                                            <div class="metric-value">
                                                <?php echo $userStats['TotalUsers']; ?>
                                            </div>
                                            <small class="metric-change positive">
                                                <i class="fas fa-users"></i> <?php echo $userStats['ActiveUsers']; ?> Active
                                            </small>
                                        </div>
                                        <div class="metric-icon icon-expenses">
                                            <i class="fas fa-users"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Charts and Data Visualizations -->
                    <div class="row">
                        <!-- User Activity Chart -->
                        <div class="col-lg-8 mb-3">
                            <div class="dashboard-card">
                                <div class="card-header bg-transparent border-0">
                                    <h6 class="m-0 font-weight-bold text-primary" style="font-size: 0.85rem;">
                                        <i class="fas fa-chart-line mr-1"></i>Sales & Inventory Overview
                                    </h6>
                                </div>
                                <div class="card-body" style="padding: 0.5rem 0.75rem !important;">
                                    <div class="chart-container">
                                        <canvas id="userActivityChart"></canvas>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- User Status Pie Chart -->
                        <div class="col-lg-4 mb-3">
                            <div class="dashboard-card">
                                <div class="card-header bg-transparent border-0">
                                    <h6 class="m-0 font-weight-bold text-primary" style="font-size: 0.85rem;">
                                        <i class="fas fa-chart-pie mr-1"></i>Inventory Status
                                    </h6>
                                </div>
                                <div class="card-body" style="padding: 0.5rem 0.75rem !important;">
                                    <div class="chart-container">
                                        <canvas id="userStatusChart"></canvas>
                                    </div>
                                    <div class="mt-2">
                                        <div class="d-flex justify-content-between" style="font-size: 0.7rem;">
                                            <span><i class="fas fa-circle text-success mr-1"></i>Active: <?php echo $inventoryStats['ActiveItems']; ?></span>
                                            <span><i class="fas fa-circle text-warning mr-1"></i>Low Stock: <?php echo $inventoryStats['LowStockItems']; ?></span>
                                        </div>
                                    </div>
                                    <div class="mt-2 text-center">
                                        <h6 class="mb-0" style="font-size: 0.95rem;">₹<?php echo number_format($salesStats['TotalRevenue'], 2); ?></h6>
                                        <small class="text-muted" style="font-size: 0.65rem;">Total Revenue</small>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Recent Activity and Quick Actions -->
                    <div class="row">
                        <!-- Recent User Registrations -->
                        <div class="col-lg-8 mb-3">
                            <div class="dashboard-card">
                                <div class="card-header bg-transparent border-0">
                                    <h6 class="m-0 font-weight-bold text-primary" style="font-size: 0.85rem;">
                                        <i class="fas fa-user-plus mr-1"></i>Recent User Registrations
                                    </h6>
                                </div>
                                <div class="card-body p-0">
                                    <div class="recent-activity">
                                        <?php if (!empty($recentActivities)): ?>
                                            <?php foreach($recentActivities as $activity): ?>
                                            <?php
                                                $statusLabel = $activity['Status'] ?? 'Active';
                                                $statusKey = strtolower($statusLabel);
                                                $statusClassMap = [
                                                    'active' => ['icon' => 'activity-confirmed', 'badge' => 'status-confirmed'],
                                                    'inactive' => ['icon' => 'activity-checkout', 'badge' => 'status-checkedout'],
                                                    'pending' => ['icon' => 'activity-checkin', 'badge' => 'status-checkedin'],
                                                ];
                                                $iconClass = $statusClassMap[$statusKey]['icon'] ?? 'activity-confirmed';
                                                $badgeClass = $statusClassMap[$statusKey]['badge'] ?? 'status-confirmed';
                                                $activityDate = $activity['CreatedDate'] ?? null;
                                            ?>
                                            <div class="activity-item">
                                                <div class="activity-icon <?php echo $iconClass; ?>">
                                                    <i class="fas fa-user"></i>
                                                </div>
                                                <div class="flex-1">
                                                    <div class="d-flex justify-content-between align-items-start">
                                                        <div>
                                                            <h6 class="mb-1 font-weight-bold" style="font-size: 0.85rem;"><?php echo htmlspecialchars($activity['FullName'] ?? 'N/A'); ?></h6>
                                                            <p class="mb-1 text-muted" style="font-size: 0.7rem;">
                                                                <i class="fas fa-envelope mr-1"></i><?php echo htmlspecialchars($activity['Email'] ?? 'N/A'); ?>
                                                            </p>
                                                            <small class="text-muted" style="font-size: 0.65rem;">
                                                                <i class="fas fa-user-tag mr-1"></i>
                                                                Role: <?php echo htmlspecialchars($activity['RoleName'] ?? 'Not Assigned'); ?> • 
                                                                <?php echo $activityDate ? date('M d, Y h:i A', strtotime($activityDate)) : 'N/A'; ?>
                                                            </small>
                                                        </div>
                                                        <div class="text-right">
                                                            <span class="status-badge <?php echo $badgeClass; ?>">
                                                                <?php echo htmlspecialchars($statusLabel); ?>
                                                            </span>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            <?php endforeach; ?>
                                        <?php else: ?>
                                            <div class="text-center py-3 text-muted">
                                                <i class="fas fa-user-times fa-2x mb-2"></i>
                                                <p style="font-size: 0.75rem; margin: 0;">No recent user registrations found</p>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                    <div class="card-footer bg-transparent border-top-0 text-center" style="padding: 0.4rem 0.5rem !important;">
                                        <a href="user-management.php" class="btn btn-primary btn-sm" style="font-size: 0.75rem; padding: 0.25rem 0.75rem;">
                                            <i class="fas fa-eye mr-1"></i>View All Users
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Quick Actions -->
                        <div class="col-lg-4 mb-3">
                            <div class="dashboard-card">
                                <div class="card-header bg-transparent border-0">
                                    <h6 class="m-0 font-weight-bold text-primary" style="font-size: 0.85rem;">
                                        <i class="fas fa-bolt mr-1"></i>Quick Actions
                                    </h6>
                                </div>
                                <div class="card-body" style="padding: 0.5rem 0.75rem !important;">
                                    <div class="list-group list-group-flush">
                                        <a href="Sales/products.php" class="list-group-item list-group-item-action border-0 rounded mb-1" style="padding: 0.4rem 0.5rem !important;">
                                            <i class="fas fa-boxes text-primary mr-2" style="font-size: 0.8rem;"></i>
                                            <strong style="font-size: 0.8rem;">Products Overview</strong>
                                            <br><small class="text-muted" style="font-size: 0.65rem;">Browse and manage inventory items</small>
                                        </a>
                                        <a href="items/item-management.php" class="list-group-item list-group-item-action border-0 rounded mb-1" style="padding: 0.4rem 0.5rem !important;">
                                            <i class="fas fa-box text-success mr-2" style="font-size: 0.8rem;"></i>
                                            <strong style="font-size: 0.8rem;">Manage Items</strong>
                                            <br><small class="text-muted" style="font-size: 0.65rem;">Full item management and inventory</small>
                                        </a>
                                        <a href="Sales/index.php" class="list-group-item list-group-item-action border-0 rounded mb-1" style="padding: 0.4rem 0.5rem !important;">
                                            <i class="fas fa-cash-register text-info mr-2" style="font-size: 0.8rem;"></i>
                                            <strong style="font-size: 0.8rem;">Sales POS</strong>
                                            <br><small class="text-muted" style="font-size: 0.65rem;">Point of sale system</small>
                                        </a>
                                        <a href="customer-management.php" class="list-group-item list-group-item-action border-0 rounded mb-1" style="padding: 0.4rem 0.5rem !important;">
                                            <i class="fas fa-users text-warning mr-2" style="font-size: 0.8rem;"></i>
                                            <strong style="font-size: 0.8rem;">Customers</strong>
                                            <br><small class="text-muted" style="font-size: 0.65rem;">Manage customer information</small>
                                        </a>
                                    </div>
                                </div>
                            </div>

                            <!-- System Overview Card -->
                            <div class="dashboard-card mt-2">
                                <div class="card-header bg-transparent border-0">
                                    <h6 class="m-0 font-weight-bold text-primary" style="font-size: 0.85rem;">
                                        <i class="fas fa-info-circle mr-1"></i>System Overview
                                    </h6>
                                </div>
                                <div class="card-body" style="padding: 0.5rem 0.75rem !important;">
                                    <div class="row text-center">
                                        <div class="col-6">
                                            <div class="border-right">
                                                <div class="h5 font-weight-bold text-primary mb-0"><?php echo $roleStats['TotalRoles']; ?></div>
                                                <small class="text-muted" style="font-size: 0.65rem;">Total Roles</small>
                                            </div>
                                        </div>
                                        <div class="col-6">
                                            <div class="h5 font-weight-bold text-success mb-0"><?php echo $roleStats['ActiveRoles']; ?></div>
                                            <small class="text-muted" style="font-size: 0.65rem;">Active Roles</small>
                                        </div>
                                    </div>
                                    <div class="row text-center mt-2 pt-2 border-top">
                                        <div class="col-6">
                                            <div class="border-right">
                                                <div class="h5 font-weight-bold text-info mb-0"><?php echo $permissionStats['TotalPermissions']; ?></div>
                                                <small class="text-muted" style="font-size: 0.65rem;">Permissions</small>
                                            </div>
                                        </div>
                                        <div class="col-6">
                                            <div class="h5 font-weight-bold text-warning mb-0"><?php echo $adminStats['TotalAdmins']; ?></div>
                                            <small class="text-muted" style="font-size: 0.65rem;">Admins</small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include_once('includes/footer.php');?>
        </div>
    </div>

    <!-- Bootstrap core JavaScript-->
    <script src="vendor/jquery/jquery.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="js/sb-admin-2.min.js"></script>
    <script src="js/modern-messagebox.js"></script>
    <script src="js/messagebox-wrapper.js"></script>

    <script>
        // Dashboard initialization
        $(document).ready(function() {
            initializeCharts();
        });

        function initializeCharts() {
            // Sales & Inventory Overview Chart
            const activityCtx = document.getElementById('userActivityChart').getContext('2d');
            new Chart(activityCtx, {
                type: 'bar',
                data: {
                    labels: ['Total Sales', 'Month Sales', 'Total Items', 'Active Items', 'Low Stock'],
                    datasets: [{
                        label: 'Count',
                        data: [
                            <?php echo $salesStats['TotalSales']; ?>,
                            <?php echo $salesStats['MonthSales']; ?>,
                            <?php echo $inventoryStats['TotalItems']; ?>,
                            <?php echo $inventoryStats['ActiveItems']; ?>,
                            <?php echo $inventoryStats['LowStockItems']; ?>
                        ],
                        backgroundColor: [
                            'rgba(28, 200, 138, 0.8)',
                            'rgba(78, 115, 223, 0.8)',
                            'rgba(246, 194, 62, 0.8)',
                            'rgba(133, 135, 150, 0.8)',
                            'rgba(231, 74, 59, 0.8)'
                        ],
                        borderColor: [
                            'rgb(28, 200, 138)',
                            'rgb(78, 115, 223)',
                            'rgb(246, 194, 62)',
                            'rgb(133, 135, 150)',
                            'rgb(231, 74, 59)'
                        ],
                        borderWidth: 2
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            backgroundColor: 'rgba(0,0,0,0.8)',
                            padding: 12,
                            titleFont: {
                                size: 14
                            },
                            bodyFont: {
                                size: 13
                            }
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                stepSize: 1
                            }
                        }
                    }
                }
            });

            // User Status Pie Chart
            const statusCtx = document.getElementById('userStatusChart').getContext('2d');
            new Chart(statusCtx, {
                type: 'doughnut',
                data: {
                    labels: ['Active Items', 'Low Stock', 'Out of Stock'],
                    datasets: [{
                        data: [
                            <?php echo $inventoryStats['ActiveItems']; ?>, 
                            <?php echo $inventoryStats['LowStockItems']; ?>,
                            <?php echo $inventoryStats['OutOfStockItems']; ?>
                        ],
                        backgroundColor: ['#1cc88a', '#f6c23e', '#e74a3b'],
                        hoverBackgroundColor: ['#17a673', '#f4b619', '#e02d1b'],
                        borderWidth: 0
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: true,
                            position: 'bottom'
                        },
                        tooltip: {
                            backgroundColor: 'rgba(0,0,0,0.8)',
                            padding: 12
                        }
                    },
                    cutout: '70%'
                }
            });
        }

        // Auto-refresh dashboard data every 5 minutes
        setInterval(function() {
            location.reload();
        }, 300000);
    </script>

    <!-- Logout Modal-->
    <div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5>
                    <button class="close" type="button" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">Select "Logout" below if you are ready to end your current session.</div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
                    <a class="btn btn-primary" href="logout.php">Logout</a>
                </div>
            </div>
        </div>
    </div>

    <!-- Scroll to Top Button-->
    <a class="scroll-to-top rounded" href="#page-top">
        <i class="fas fa-angle-up"></i>
    </a>

</body>
</html>