<?php 
// Include session handling - Using your structure
include 'services/session.php'; 

// Debug session information
error_log("=== INDEX.PHP ACCESS ATTEMPT ===");
error_log("Session data: " . print_r($_SESSION, true));

// Check if user is logged in - Using your session structure
if (!$_SESSION['user'] || !isset($_SESSION['user'])) {
    error_log("❌ Access denied: User not logged in");
    error_log("- user: " . ($_SESSION['user'] ?? 'not set'));
    header('Location: auth-login.php?error=session_expired');
    exit();
}

// Get user role for authorization
$user_role = $_SESSION['role_name'] ?? 'Customer';
$user_id = $_SESSION['user_id'] ?? 0;

error_log("✓ User logged in: Username={$_SESSION['user']}, Role={$user_role}");

// Check if user has admin privileges
if (!in_array($user_role, ['Administrator', 'Support Agent', 'Sales Manager', 'Developer'])) {
    error_log("❌ Access denied: User role '{$user_role}' not authorized for admin dashboard");
    header('Location: dashboard.php');
    exit();
}

error_log("✓ Admin access granted for role: {$user_role}");

// Include database connection for metrics
require_once 'layouts/dbconn.php';

// Function to safely execute queries and return results
function safeQuery($conn, $query, $params = []) {
    try {
        $stmt = $conn->prepare($query);
        if (!$stmt) {
            throw new Exception("Prepare failed: " . $conn->error);
        }
        
        if (!empty($params)) {
            $types = str_repeat('s', count($params));
            $stmt->bind_param($types, ...$params);
        }
        
        $stmt->execute();
        $result = $stmt->get_result();
        $data = $result->fetch_assoc();
        $stmt->close();
        
        return $data;
    } catch (Exception $e) {
        error_log("Query error: " . $e->getMessage());
        return null;
    }
}

// Function to safely execute queries and return multiple rows
function safeQueryAll($conn, $query, $params = []) {
    try {
        $stmt = $conn->prepare($query);
        if (!$stmt) {
            throw new Exception("Prepare failed: " . $conn->error);
        }
        
        if (!empty($params)) {
            $types = str_repeat('s', count($params));
            $stmt->bind_param($types, ...$params);
        }
        
        $stmt->execute();
        $result = $stmt->get_result();
        $data = $result->fetch_all(MYSQLI_ASSOC);
        $stmt->close();
        
        return $data;
    } catch (Exception $e) {
        error_log("Query error: " . $e->getMessage());
        return [];
    }
}

// Get comprehensive dashboard metrics
$metrics = [
    'total_customers' => 0,
    'active_licenses' => 0,
    'todays_orders' => 0,
    'todays_revenue' => 0,
    'monthly_revenue' => 0,
    'total_revenue' => 0,
    'open_tickets' => 0,
    'critical_tickets' => 0,
    'piracy_violations' => 0,
    'expired_licenses' => 0,
    'pending_orders' => 0,
    'wallet_balance_total' => 0,
    'download_count_today' => 0,
    'api_requests_today' => 0,
    'failed_payments' => 0,
    'plugin_sales_count' => 0
];

// 1. Total customers
$result = safeQuery($conn, "SELECT COUNT(*) as count FROM users WHERE role_id = (SELECT role_id FROM user_roles WHERE role_name = 'Customer')");
$metrics['total_customers'] = $result['count'] ?? 0;

// 2. Active licenses
$result = safeQuery($conn, "SELECT COUNT(*) as count FROM licenses WHERE status = 'ACTIVE'");
$metrics['active_licenses'] = $result['count'] ?? 0;

// 3. Expired licenses (need attention)
$result = safeQuery($conn, "SELECT COUNT(*) as count FROM licenses WHERE status = 'EXPIRED' OR (expires_at IS NOT NULL AND expires_at < NOW())");
$metrics['expired_licenses'] = $result['count'] ?? 0;

// 4. Today's orders
$result = safeQuery($conn, "SELECT COUNT(*) as count FROM orders WHERE order_status = 'COMPLETED' AND DATE(created_at) = CURDATE()");
$metrics['todays_orders'] = $result['count'] ?? 0;

// 5. Pending orders (need attention)
$result = safeQuery($conn, "SELECT COUNT(*) as count FROM orders WHERE order_status = 'PENDING' AND created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)");
$metrics['pending_orders'] = $result['count'] ?? 0;

// 6. Today's revenue
$result = safeQuery($conn, "SELECT COALESCE(SUM(total_amount), 0) as revenue FROM orders WHERE order_status = 'COMPLETED' AND DATE(created_at) = CURDATE()");
$metrics['todays_revenue'] = $result['revenue'] ?? 0;

// 7. This month's revenue
$result = safeQuery($conn, "SELECT COALESCE(SUM(total_amount), 0) as revenue FROM orders WHERE order_status = 'COMPLETED' AND MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE())");
$metrics['monthly_revenue'] = $result['revenue'] ?? 0;

// 8. Total all-time revenue
$result = safeQuery($conn, "SELECT COALESCE(SUM(total_amount), 0) as revenue FROM orders WHERE order_status = 'COMPLETED'");
$metrics['total_revenue'] = $result['revenue'] ?? 0;

// 9. Open support tickets
$result = safeQuery($conn, "SELECT COUNT(*) as count FROM support_tickets WHERE status IN ('OPEN', 'IN_PROGRESS')");
$metrics['open_tickets'] = $result['count'] ?? 0;

// 10. Critical support tickets
$result = safeQuery($conn, "SELECT COUNT(*) as count FROM support_tickets WHERE status IN ('OPEN', 'IN_PROGRESS') AND priority = 'CRITICAL'");
$metrics['critical_tickets'] = $result['count'] ?? 0;

// 11. Piracy violations
$result = safeQuery($conn, "SELECT COUNT(*) as count FROM piracy_violations WHERE status = 'PENDING'");
$metrics['piracy_violations'] = $result['count'] ?? 0;

// 12. Total wallet balances (platform liquidity)
$result = safeQuery($conn, "SELECT COALESCE(SUM(balance_usd), 0) as total FROM wallets WHERE status = 'ACTIVE'");
$metrics['wallet_balance_total'] = $result['total'] ?? 0;

// 13. Failed payments today
$result = safeQuery($conn, "SELECT COUNT(*) as count FROM payments WHERE status = 'FAILED' AND DATE(created_at) = CURDATE()");
$metrics['failed_payments'] = $result['count'] ?? 0;

// 14. Downloads today
$result = safeQuery($conn, "SELECT COALESCE(SUM(downloads_used), 0) as count FROM download_links WHERE DATE(last_downloaded) = CURDATE()");
$metrics['download_count_today'] = $result['count'] ?? 0;

// 15. API requests today
$result = safeQuery($conn, "SELECT COUNT(*) as count FROM api_requests WHERE DATE(created_at) = CURDATE()");
$metrics['api_requests_today'] = $result['count'] ?? 0;

// 16. Plugin sales count (total products sold)
$result = safeQuery($conn, "SELECT COUNT(*) as count FROM order_items oi JOIN orders o ON oi.order_id = o.order_id WHERE o.order_status = 'COMPLETED'");
$metrics['plugin_sales_count'] = $result['count'] ?? 0;

// Get recent activities for activity feed
$recent_activities = safeQueryAll($conn, "
    SELECT 
        al.action,
        al.module,
        al.logged_at,
        u.full_name,
        u.email,
        al.additional_info
    FROM activity_log al 
    JOIN users u ON al.user_id = u.user_id 
    ORDER BY al.logged_at DESC 
    LIMIT 10
");

// Get top selling products
$top_products = safeQueryAll($conn, "
    SELECT 
        p.name,
        COUNT(oi.item_id) as sales_count,
        SUM(oi.total_price) as total_revenue
    FROM products p
    JOIN order_items oi ON p.product_id = oi.product_id
    JOIN orders o ON oi.order_id = o.order_id
    WHERE o.order_status = 'COMPLETED'
    GROUP BY p.product_id, p.name
    ORDER BY sales_count DESC
    LIMIT 5
");

// Get recent orders
$recent_orders = safeQueryAll($conn, "
    SELECT 
        o.order_number,
        u.full_name,
        u.company_name,
        o.total_amount,
        o.currency,
        o.order_status,
        o.created_at
    FROM orders o
    JOIN users u ON o.user_id = u.user_id
    ORDER BY o.created_at DESC
    LIMIT 8
");

// Calculate growth percentages (compare with last month)
$last_month_revenue = safeQuery($conn, "
    SELECT COALESCE(SUM(total_amount), 0) as revenue 
    FROM orders 
    WHERE order_status = 'COMPLETED' 
    AND MONTH(created_at) = MONTH(DATE_SUB(CURDATE(), INTERVAL 1 MONTH))
    AND YEAR(created_at) = YEAR(DATE_SUB(CURDATE(), INTERVAL 1 MONTH))
");

$revenue_growth = 0;
if ($last_month_revenue && $last_month_revenue['revenue'] > 0) {
    $revenue_growth = (($metrics['monthly_revenue'] - $last_month_revenue['revenue']) / $last_month_revenue['revenue']) * 100;
}

// Get platform health status
$platform_status = [
    'database' => 'Connected',
    'mtn_momo' => 'Online',
    'mgurush' => 'Online', 
    'nilepay' => 'Maintenance',
    'license_server' => 'Active',
    'payment_gateway' => 'Active'
];

error_log("✓ Admin dashboard loaded successfully");
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <?php $title = "Admin Dashboard";
    include 'partials/title-meta.php'; ?>
    
    <?php include 'partials/head-css.php'; ?>
    
    <!-- Custom CSS for enhanced dashboard -->
    <style>
        .metric-card {
            border-radius: 15px;
            border: none;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            transition: all 0.3s ease;
            background: white;
            margin-bottom: 1.5rem;
            overflow: hidden;
        }
        
        .metric-card:hover {
            transform: translateY(-8px);
            box-shadow: 0 8px 30px rgba(0,0,0,0.12);
        }
        
        .metric-card .card-body {
            padding: 1.5rem;
        }
        
        .widget-chart-1 {
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .widget-detail-1 h2 {
            font-size: 2.2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
            color: #2c3e50;
        }
        
        .widget-detail-1 p {
            color: #6c757d;
            font-size: 0.9rem;
            margin-bottom: 0;
        }
        
        .growth-indicator {
            display: inline-flex;
            align-items: center;
            padding: 0.25rem 0.5rem;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
            margin-top: 0.5rem;
        }
        
        .growth-positive {
            background: rgba(40, 167, 69, 0.1);
            color: #28a745;
        }
        
        .growth-negative {
            background: rgba(220, 53, 69, 0.1);
            color: #dc3545;
        }
        
        .growth-neutral {
            background: rgba(108, 117, 125, 0.1);
            color: #6c757d;
        }
        
        .admin-welcome {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 2rem;
            margin-bottom: 2rem;
        }
        
        .status-indicator {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            margin-right: 8px;
            display: inline-block;
        }
        
        .status-online { background-color: #28a745; }
        .status-maintenance { background-color: #ffc107; }
        .status-offline { background-color: #dc3545; }
        
        .activity-item {
            padding: 0.75rem 0;
            border-bottom: 1px solid #f1f3f4;
        }
        
        .activity-item:last-child {
            border-bottom: none;
        }
        
        .activity-time {
            font-size: 0.75rem;
            color: #6c757d;
        }
        
        .table-recent {
            font-size: 0.9rem;
        }
        
        .table-recent th {
            border-top: none;
            font-weight: 600;
            color: #495057;
            background-color: #f8f9fa;
        }
        
        .alert-metric {
            position: relative;
        }
        
        .alert-badge {
            position: absolute;
            top: -5px;
            right: -5px;
            background: #dc3545;
            color: white;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            font-size: 0.7rem;
            display: flex;
            align-items: center;
            justify-content: center;
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.1); }
            100% { transform: scale(1); }
        }
        
        .provider-status {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0.5rem;
            margin-bottom: 0.5rem;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 8px;
        }
        
        .quick-stats {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
            border-radius: 15px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
        }
        
        .quick-stats h6 {
            opacity: 0.9;
            margin-bottom: 0.5rem;
        }
        
        .quick-stats h3 {
            margin-bottom: 0;
            font-weight: 700;
        }
    </style>
</head>

<?php include 'partials/body.php'; ?>

<!-- Begin page -->
<div id="wrapper">

    <?php $pagetitle = "Admin Dashboard"; include 'partials/menu.php'; ?>

    <!-- ============================================================== -->
    <!-- Start Page Content here -->
    <!-- ============================================================== -->

    <div class="content-page">
        <div class="content">

            <!-- Start Content-->
            <div class="container-fluid">

                <!-- Admin Welcome Section -->
                <div class="admin-welcome">
                    <div class="row align-items-center">
                        <div class="col-md-8">
                            <h2 class="mb-2">
                                <i class="fas fa-tachometer-alt me-2"></i>
                                ConnectPay Platform Administration
                            </h2>
                            <p class="mb-0 opacity-75">
                                Monitor platform performance, manage customers, and track revenue in real-time
                            </p>
                        </div>
                        <div class="col-md-4 text-md-end">
                            <div class="text-white">
                                <h5 class="mb-1">
                                    <i class="fas fa-shield-alt me-2"></i>
                                    Admin Panel
                                </h5>
                                <p class="mb-0">
                                    <i class="fas fa-user me-1"></i>
                                    <?php echo htmlspecialchars($_SESSION['full_name'] ?? $_SESSION['user']); ?>
                                </p>
                                <small>Role: <?php echo htmlspecialchars($user_role); ?></small>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Key Metrics Row -->
                <div class="row">
                    <!-- Today's Revenue -->
                    <div class="col-xl-3 col-md-6">
                        <div class="card metric-card">
                            <div class="card-body">
                                <div class="dropdown float-end">
                                    <a href="#" class="dropdown-toggle arrow-none card-drop" data-bs-toggle="dropdown" aria-expanded="false">
                                        <i class="mdi mdi-dots-vertical"></i>
                                    </a>
                                    <div class="dropdown-menu dropdown-menu-end">
                                        <a href="revenue-reports.php" class="dropdown-item">View Details</a>
                                        <a href="all-orders.php" class="dropdown-item">View Orders</a>
                                    </div>
                                </div>

                                <h4 class="header-title mt-0 mb-4">Today's Revenue</h4>

                                <div class="widget-chart-1">
                                    <div class="widget-chart-box-1 float-start" dir="ltr">
                                        <input data-plugin="knob" data-width="70" data-height="70" data-fgColor="#28a745" data-bgColor="#d4edda" value="<?php echo min(100, ($metrics['todays_revenue'] / max(1, $metrics['monthly_revenue']) * 100)); ?>" data-skin="tron" data-angleOffset="180" data-readOnly=true data-thickness=".15" />
                                    </div>

                                    <div class="widget-detail-1 text-end">
                                        <h2 class="fw-normal pt-2 mb-1">$<?php echo number_format($metrics['todays_revenue'], 0); ?></h2>
                                        <p class="text-muted mb-1">Today's earnings</p>
                                        <?php if ($revenue_growth != 0): ?>
                                        <span class="growth-indicator <?php echo $revenue_growth > 0 ? 'growth-positive' : 'growth-negative'; ?>">
                                            <i class="fas fa-<?php echo $revenue_growth > 0 ? 'arrow-up' : 'arrow-down'; ?> me-1"></i>
                                            <?php echo abs(round($revenue_growth, 1)); ?>%
                                        </span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Active Licenses -->
                    <div class="col-xl-3 col-md-6">
                        <div class="card metric-card">
                            <div class="card-body">
                                <div class="dropdown float-end">
                                    <a href="#" class="dropdown-toggle arrow-none card-drop" data-bs-toggle="dropdown" aria-expanded="false">
                                        <i class="mdi mdi-dots-vertical"></i>
                                    </a>
                                    <div class="dropdown-menu dropdown-menu-end">
                                        <a href="all-licenses.php" class="dropdown-item">View All Licenses</a>
                                        <a href="license-analytics.php" class="dropdown-item">License Analytics</a>
                                    </div>
                                </div>

                                <h4 class="header-title mt-0 mb-3">Active Licenses</h4>

                                <div class="widget-box-2 position-relative">
                                    <?php if ($metrics['expired_licenses'] > 0): ?>
                                    <span class="alert-badge"><?php echo $metrics['expired_licenses']; ?></span>
                                    <?php endif; ?>
                                    
                                    <div class="widget-detail-2 text-end">
                                        <span class="badge bg-success rounded-pill float-start mt-3">
                                            <i class="fas fa-key me-1"></i>Active
                                        </span>
                                        <h2 class="fw-normal mb-1"><?php echo number_format($metrics['active_licenses']); ?></h2>
                                        <p class="text-muted mb-3">Licensed users</p>
                                    </div>
                                    <div class="progress progress-bar-alt-success progress-sm">
                                        <div class="progress-bar bg-success" role="progressbar" 
                                             aria-valuenow="<?php echo $metrics['active_licenses']; ?>" 
                                             aria-valuemin="0" 
                                             aria-valuemax="<?php echo $metrics['active_licenses'] + $metrics['expired_licenses']; ?>" 
                                             style="width: <?php echo $metrics['active_licenses'] > 0 ? (($metrics['active_licenses'] / max(1, $metrics['active_licenses'] + $metrics['expired_licenses'])) * 100) : 0; ?>%;">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Total Customers -->
                    <div class="col-xl-3 col-md-6">
                        <div class="card metric-card">
                            <div class="card-body">
                                <div class="dropdown float-end">
                                    <a href="#" class="dropdown-toggle arrow-none card-drop" data-bs-toggle="dropdown" aria-expanded="false">
                                        <i class="mdi mdi-dots-vertical"></i>
                                    </a>
                                    <div class="dropdown-menu dropdown-menu-end">
                                        <a href="manage-customers.php" class="dropdown-item">Manage Customers</a>
                                        <a href="customer-analytics.php" class="dropdown-item">Customer Analytics</a>
                                    </div>
                                </div>

                                <h4 class="header-title mt-0 mb-4">Total Customers</h4>

                                <div class="widget-chart-1">
                                    <div class="widget-chart-box-1 float-start" dir="ltr">
                                        <input data-plugin="knob" data-width="70" data-height="70" data-fgColor="#17a2b8" data-bgColor="#bee5eb" value="<?php echo min(100, ($metrics['total_customers'] / 10) * 10); ?>" data-skin="tron" data-angleOffset="180" data-readOnly=true data-thickness=".15" />
                                    </div>
                                    <div class="widget-detail-1 text-end">
                                        <h2 class="fw-normal pt-2 mb-1"><?php echo number_format($metrics['total_customers']); ?></h2>
                                        <p class="text-muted mb-1">Registered users</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Support Tickets -->
                    <div class="col-xl-3 col-md-6">
                        <div class="card metric-card alert-metric">
                            <div class="card-body">
                                <?php if ($metrics['critical_tickets'] > 0): ?>
                                <span class="alert-badge"><?php echo $metrics['critical_tickets']; ?></span>
                                <?php endif; ?>
                                
                                <div class="dropdown float-end">
                                    <a href="#" class="dropdown-toggle arrow-none card-drop" data-bs-toggle="dropdown" aria-expanded="false">
                                        <i class="mdi mdi-dots-vertical"></i>
                                    </a>
                                    <div class="dropdown-menu dropdown-menu-end">
                                        <a href="all-tickets.php" class="dropdown-item">View All Tickets</a>
                                        <a href="ticket-queue.php" class="dropdown-item">Ticket Queue</a>
                                    </div>
                                </div>

                                <h4 class="header-title mt-0 mb-3">Support Tickets</h4>

                                <div class="widget-box-2">
                                    <div class="widget-detail-2 text-end">
                                        <span class="badge bg-<?php echo $metrics['open_tickets'] > 0 ? 'warning' : 'success'; ?> rounded-pill float-start mt-3">
                                            <?php echo $metrics['open_tickets']; ?> <i class="mdi mdi-trending-<?php echo $metrics['open_tickets'] > 5 ? 'up' : 'down'; ?>"></i>
                                        </span>
                                        <h2 class="fw-normal mb-1"><?php echo $metrics['open_tickets']; ?></h2>
                                        <p class="text-muted mb-3">Open tickets</p>
                                    </div>
                                    <div class="progress progress-bar-alt-warning progress-sm">
                                        <div class="progress-bar bg-<?php echo $metrics['open_tickets'] > 10 ? 'danger' : 'warning'; ?>" role="progressbar" 
                                             aria-valuenow="<?php echo min(100, $metrics['open_tickets'] * 10); ?>" 
                                             aria-valuemin="0" aria-valuemax="100" 
                                             style="width: <?php echo min(100, $metrics['open_tickets'] * 10); ?>%;">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- end key metrics row -->

                <!-- Secondary Metrics Row -->
                <div class="row">
                    <!-- Monthly Revenue -->
                    <div class="col-xl-2 col-md-4">
                        <div class="quick-stats text-center">
                            <h6>Monthly Revenue</h6>
                            <h3>$<?php echo number_format($metrics['monthly_revenue'], 0); ?></h3>
                        </div>
                    </div>
                    
                    <!-- Plugin Sales -->
                    <div class="col-xl-2 col-md-4">
                        <div class="quick-stats text-center" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
                            <h6>Plugin Sales</h6>
                            <h3><?php echo number_format($metrics['plugin_sales_count']); ?></h3>
                        </div>
                    </div>
                    
                    <!-- Downloads Today -->
                    <div class="col-xl-2 col-md-4">
                        <div class="quick-stats text-center" style="background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);">
                            <h6>Downloads Today</h6>
                            <h3><?php echo number_format($metrics['download_count_today']); ?></h3>
                        </div>
                    </div>
                    
                    <!-- API Requests -->
                    <div class="col-xl-2 col-md-4">
                        <div class="quick-stats text-center" style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);">
                            <h6>API Requests</h6>
                            <h3><?php echo number_format($metrics['api_requests_today']); ?></h3>
                        </div>
                    </div>
                    
                    <!-- Wallet Balance -->
                    <div class="col-xl-2 col-md-4">
                        <div class="quick-stats text-center" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
                            <h6>Platform Wallets</h6>
                            <h3>$<?php echo number_format($metrics['wallet_balance_total'], 0); ?></h3>
                        </div>
                    </div>
                    
                    <!-- Failed Payments -->
                    <div class="col-xl-2 col-md-4">
                        <div class="quick-stats text-center alert-metric" style="background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);">
                            <?php if ($metrics['failed_payments'] > 0): ?>
                            <span class="alert-badge"><?php echo $metrics['failed_payments']; ?></span>
                            <?php endif; ?>
                            <h6>Failed Payments</h6>
                            <h3><?php echo $metrics['failed_payments']; ?></h3>
                        </div>
                    </div>
                </div>
                <!-- end secondary metrics row -->

                <!-- Dashboard Content Row -->
                <div class="row">
                    <!-- System Status -->
                    <div class="col-xl-4">
                        <div class="card">
                            <div class="card-body">
                                <div class="dropdown float-end">
                                    <a href="#" class="dropdown-toggle arrow-none card-drop" data-bs-toggle="dropdown" aria-expanded="false">
                                        <i class="mdi mdi-dots-vertical"></i>
                                    </a>
                                    <div class="dropdown-menu dropdown-menu-end">
                                        <a href="general-settings.php" class="dropdown-item">System Settings</a>
                                        <a href="exchange-rates.php" class="dropdown-item">Exchange Rates</a>
                                    </div>
                                </div>

                                <h4 class="header-title mb-3">
                                    <i class="fas fa-server me-2"></i>
                                    System Status
                                </h4>
                                
                                <div class="mb-3">
                                    <h6 class="mb-2">MoMo Provider Status</h6>
                                    
                                    <div class="provider-status">
                                        <span><i class="fas fa-mobile-alt me-2"></i>MTN Mobile Money</span>
                                        <span class="badge bg-success">
                                            <span class="status-indicator status-online"></span>
                                            <?php echo $platform_status['mtn_momo']; ?>
                                        </span>
                                    </div>
                                    
                                    <div class="provider-status">
                                        <span><i class="fas fa-credit-card me-2"></i>m-GURUSH (Zain)</span>
                                        <span class="badge bg-success">
                                            <span class="status-indicator status-online"></span>
                                            <?php echo $platform_status['mgurush']; ?>
                                        </span>
                                    </div>
                                    
                                    <div class="provider-status">
                                        <span><i class="fas fa-wallet me-2"></i>Nilepay</span>
                                        <span class="badge bg-warning">
                                            <span class="status-indicator status-maintenance"></span>
                                            <?php echo $platform_status['nilepay']; ?>
                                        </span>
                                    </div>
                                </div>

                                <hr>

                                <div>
                                    <h6 class="mb-2">Platform Health</h6>
                                    <div class="d-flex justify-content-between mb-2">
                                        <span>Database Connection</span>
                                        <span class="badge bg-success"><?php echo $platform_status['database']; ?></span>
                                    </div>
                                    <div class="d-flex justify-content-between mb-2">
                                        <span>License Server</span>
                                        <span class="badge bg-success"><?php echo $platform_status['license_server']; ?></span>
                                    </div>
                                    <div class="d-flex justify-content-between mb-2">
                                        <span>Payment Gateway</span>
                                        <span class="badge bg-success"><?php echo $platform_status['payment_gateway']; ?></span>
                                    </div>
                                    <div class="d-flex justify-content-between mb-2">
                                        <span>Open Support Tickets</span>
                                        <span class="badge bg-<?php echo $metrics['open_tickets'] > 0 ? 'warning' : 'success'; ?>">
                                            <?php echo $metrics['open_tickets']; ?>
                                        </span>
                                    </div>
                                    <div class="d-flex justify-content-between mb-2">
                                        <span>Piracy Violations</span>
                                        <span class="badge bg-<?php echo $metrics['piracy_violations'] > 0 ? 'danger' : 'success'; ?>">
                                            <?php echo $metrics['piracy_violations']; ?>
                                        </span>
                                    </div>
                                    <div class="d-flex justify-content-between">
                                        <span>Pending Orders</span>
                                        <span class="badge bg-<?php echo $metrics['pending_orders'] > 0 ? 'info' : 'success'; ?>">
                                            <?php echo $metrics['pending_orders']; ?>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Recent Activity -->
                    <div class="col-xl-4">
                        <div class="card">
                            <div class="card-body">
                                <div class="dropdown float-end">
                                    <a href="#" class="dropdown-toggle arrow-none card-drop" data-bs-toggle="dropdown" aria-expanded="false">
                                        <i class="mdi mdi-dots-vertical"></i>
                                    </a>
                                    <div class="dropdown-menu dropdown-menu-end">
                                        <a href="user-activity.php" class="dropdown-item">View All Activity</a>
                                        <a href="audit-logs.php" class="dropdown-item">Audit Logs</a>
                                    </div>
                                </div>

                                <h4 class="header-title mb-3">
                                    <i class="fas fa-history me-2"></i>
                                    Recent Activity
                                </h4>

                                <div class="inbox-widget">
                                    <?php if (empty($recent_activities)): ?>
                                    <div class="text-center text-muted py-3">
                                        <i class="fas fa-inbox fa-2x mb-2 d-block"></i>
                                        No recent activity
                                    </div>
                                    <?php else: ?>
                                        <?php foreach (array_slice($recent_activities, 0, 5) as $activity): ?>
                                        <div class="activity-item">
                                            <div class="d-flex">
                                                <div class="flex-shrink-0">
                                                    <div class="bg-primary text-white rounded-circle d-flex align-items-center justify-content-center" style="width: 35px; height: 35px;">
                                                        <i class="fas fa-<?php 
                                                        switch($activity['action']) {
                                                            case 'CREATE': echo 'plus';
                                                                break;
                                                            case 'UPDATE': echo 'edit';
                                                                break;
                                                            case 'DELETE': echo 'trash';
                                                                break;
                                                            case 'LOGIN': echo 'sign-in-alt';
                                                                break;
                                                            case 'PURCHASE': echo 'shopping-cart';
                                                                break;
                                                            case 'DOWNLOAD': echo 'download';
                                                                break;
                                                            default: echo 'user';
                                                        }
                                                        ?> fa-sm"></i>
                                                    </div>
                                                </div>
                                                <div class="flex-grow-1 ms-2">
                                                    <h6 class="mb-1 font-14">
                                                        <?php echo htmlspecialchars($activity['full_name']); ?>
                                                    </h6>
                                                    <p class="mb-1 font-13">
                                                        <?php echo ucfirst(strtolower($activity['action'])); ?> 
                                                        <?php echo htmlspecialchars($activity['module']); ?>
                                                        <?php if ($activity['additional_info']): ?>
                                                        <small class="text-muted">- <?php echo htmlspecialchars($activity['additional_info']); ?></small>
                                                        <?php endif; ?>
                                                    </p>
                                                    <p class="mb-0 activity-time">
                                                        <?php echo date('M j, Y g:i A', strtotime($activity['logged_at'])); ?>
                                                    </p>
                                                </div>
                                            </div>
                                        </div>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Top Products -->
                    <div class="col-xl-4">
                        <div class="card">
                            <div class="card-body">
                                <div class="dropdown float-end">
                                    <a href="#" class="dropdown-toggle arrow-none card-drop" data-bs-toggle="dropdown" aria-expanded="false">
                                        <i class="mdi mdi-dots-vertical"></i>
                                    </a>
                                    <div class="dropdown-menu dropdown-menu-end">
                                        <a href="manage-products.php" class="dropdown-item">Manage Products</a>
                                        <a href="sales-analytics.php" class="dropdown-item">Sales Analytics</a>
                                    </div>
                                </div>

                                <h4 class="header-title mb-3">
                                    <i class="fas fa-trophy me-2"></i>
                                    Top Selling Products
                                </h4>

                                <?php if (empty($top_products)): ?>
                                <div class="text-center text-muted py-3">
                                    <i class="fas fa-chart-bar fa-2x mb-2 d-block"></i>
                                    No sales data available
                                </div>
                                <?php else: ?>
                                <div class="table-responsive">
                                    <table class="table table-sm mb-0">
                                        <thead>
                                            <tr>
                                                <th>Product</th>
                                                <th>Sales</th>
                                                <th>Revenue</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($top_products as $index => $product): ?>
                                            <tr>
                                                <td>
                                                    <span class="badge bg-primary me-1"><?php echo $index + 1; ?></span>
                                                    <?php echo htmlspecialchars(substr($product['name'], 0, 25)) . (strlen($product['name']) > 25 ? '...' : ''); ?>
                                                </td>
                                                <td>
                                                    <span class="text-success fw-bold"><?php echo $product['sales_count']; ?></span>
                                                </td>
                                                <td>
                                                    <span class="text-primary">$<?php echo number_format($product['total_revenue'], 0); ?></span>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- end dashboard content row -->

                <!-- Recent Orders Table -->
                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-body">
                                <div class="dropdown float-end">
                                    <a href="#" class="dropdown-toggle arrow-none card-drop" data-bs-toggle="dropdown" aria-expanded="false">
                                        <i class="mdi mdi-dots-vertical"></i>
                                    </a>
                                    <div class="dropdown-menu dropdown-menu-end">
                                        <a href="all-orders.php" class="dropdown-item">View All Orders</a>
                                        <a href="payment-transactions.php" class="dropdown-item">Payment Transactions</a>
                                        <a href="export-orders.php" class="dropdown-item">Export Data</a>
                                    </div>
                                </div>

                                <h4 class="header-title mt-0 mb-3">
                                    <i class="fas fa-shopping-bag me-2"></i>
                                    Recent Orders
                                </h4>

                                <?php if (empty($recent_orders)): ?>
                                <div class="text-center text-muted py-4">
                                    <i class="fas fa-shopping-cart fa-3x mb-3 d-block"></i>
                                    <h5>No orders yet</h5>
                                    <p>Orders will appear here once customers start purchasing</p>
                                </div>
                                <?php else: ?>
                                <div class="table-responsive">
                                    <table class="table table-recent table-hover mb-0">
                                        <thead>
                                            <tr>
                                                <th>Order #</th>
                                                <th>Customer</th>
                                                <th>Company</th>
                                                <th>Amount</th>
                                                <th>Status</th>
                                                <th>Date</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($recent_orders as $order): ?>
                                            <tr>
                                                <td>
                                                    <strong><?php echo htmlspecialchars($order['order_number']); ?></strong>
                                                </td>
                                                <td>
                                                    <div>
                                                        <?php echo htmlspecialchars($order['full_name']); ?>
                                                    </div>
                                                </td>
                                                <td>
                                                    <small class="text-muted">
                                                        <?php echo htmlspecialchars($order['company_name'] ?: 'Individual'); ?>
                                                    </small>
                                                </td>
                                                <td>
                                                    <strong class="text-success">
                                                        <?php echo $order['currency']; ?> <?php echo number_format($order['total_amount'], 2); ?>
                                                    </strong>
                                                </td>
                                                <td>
                                                    <?php
                                                    $statusClass = '';
                                                    switch($order['order_status']) {
                                                        case 'COMPLETED':
                                                            $statusClass = 'bg-success';
                                                            break;
                                                        case 'PENDING':
                                                            $statusClass = 'bg-warning';
                                                            break;
                                                        case 'PROCESSING':
                                                            $statusClass = 'bg-info';
                                                            break;
                                                        case 'CANCELLED':
                                                            $statusClass = 'bg-danger';
                                                            break;
                                                        default:
                                                            $statusClass = 'bg-secondary';
                                                    }
                                                    ?>
                                                    <span class="badge <?php echo $statusClass; ?>">
                                                        <?php echo ucfirst(strtolower($order['order_status'])); ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <small class="text-muted">
                                                        <?php echo date('M j, Y', strtotime($order['created_at'])); ?>
                                                    </small>
                                                </td>
                                                <td>
                                                    <a href="view-order.php?id=<?php echo $order['order_number']; ?>" class="btn btn-sm btn-outline-primary">
                                                        <i class="fas fa-eye"></i>
                                                    </a>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- end recent orders row -->

                <!-- Platform Analytics Summary -->
                <div class="row">
                    <div class="col-xl-6">
                        <div class="card">
                            <div class="card-body">
                                <h4 class="header-title mb-3">
                                    <i class="fas fa-chart-line me-2"></i>
                                    Platform Analytics Summary
                                </h4>
                                
                                <div class="row text-center">
                                    <div class="col-6 mb-3">
                                        <div class="p-3 bg-light rounded">
                                            <h3 class="mb-1 text-primary"><?php echo number_format($metrics['total_customers']); ?></h3>
                                            <small class="text-muted">Total Customers</small>
                                        </div>
                                    </div>
                                    <div class="col-6 mb-3">
                                        <div class="p-3 bg-light rounded">
                                            <h3 class="mb-1 text-success"><?php echo number_format($metrics['active_licenses']); ?></h3>
                                            <small class="text-muted">Active Licenses</small>
                                        </div>
                                    </div>
                                    <div class="col-6">
                                        <div class="p-3 bg-light rounded">
                                            <h3 class="mb-1 text-info"><?php echo number_format($metrics['todays_orders']); ?></h3>
                                            <small class="text-muted">Today's Orders</small>
                                        </div>
                                    </div>
                                    <div class="col-6">
                                        <div class="p-3 bg-light rounded">
                                            <h3 class="mb-1 text-warning">$<?php echo number_format($metrics['total_revenue'], 0); ?></h3>
                                            <small class="text-muted">Total Revenue</small>
                                        </div>
                                    </div>
                                </div>

                                <hr>

                                <div class="text-center">
                                    <p class="text-muted mb-2">
                                        <i class="fas fa-clock me-1"></i>
                                        Last updated: <?php echo date('Y-m-d H:i:s'); ?>
                                    </p>
                                    <button class="btn btn-sm btn-outline-primary" onclick="location.reload()">
                                        <i class="fas fa-sync-alt me-1"></i>
                                        Refresh Data
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Quick Actions -->
                    <div class="col-xl-6">
                        <div class="card">
                            <div class="card-body">
                                <h4 class="header-title mb-3">
                                    <i class="fas fa-bolt me-2"></i>
                                    Quick Actions
                                </h4>
                                
                                <div class="row">
                                    <div class="col-6 mb-3">
                                        <a href="manage-customers.php" class="btn btn-outline-primary w-100 text-start">
                                            <i class="fas fa-users fa-lg me-2"></i>
                                            <div>
                                                <strong>Manage Customers</strong>
                                                <small class="d-block text-muted">View customer accounts</small>
                                            </div>
                                        </a>
                                    </div>
                                    <div class="col-6 mb-3">
                                        <a href="all-licenses.php" class="btn btn-outline-info w-100 text-start">
                                            <i class="fas fa-key fa-lg me-2"></i>
                                            <div>
                                                <strong>License Overview</strong>
                                                <small class="d-block text-muted">Monitor licenses</small>
                                            </div>
                                        </a>
                                    </div>
                                    <div class="col-6 mb-3">
                                        <a href="revenue-reports.php" class="btn btn-outline-success w-100 text-start">
                                            <i class="fas fa-chart-bar fa-lg me-2"></i>
                                            <div>
                                                <strong>Revenue Reports</strong>
                                                <small class="d-block text-muted">Financial analytics</small>
                                            </div>
                                        </a>
                                    </div>
                                    <div class="col-6 mb-3">
                                        <a href="all-tickets.php" class="btn btn-outline-warning w-100 text-start">
                                            <i class="fas fa-headphones fa-lg me-2"></i>
                                            <div>
                                                <strong>Support Center</strong>
                                                <small class="d-block text-muted">Manage tickets</small>
                                            </div>
                                        </a>
                                    </div>
                                </div>

                                <?php if ($metrics['piracy_violations'] > 0 || $metrics['failed_payments'] > 0): ?>
                                <hr>
                                <div class="alert alert-warning">
                                    <h6 class="alert-heading">
                                        <i class="fas fa-exclamation-triangle me-2"></i>
                                        Attention Required
                                    </h6>
                                    <?php if ($metrics['piracy_violations'] > 0): ?>
                                    <p class="mb-1">
                                        <strong><?php echo $metrics['piracy_violations']; ?></strong> piracy violation(s) pending review
                                        <a href="piracy-violations.php" class="btn btn-sm btn-warning ms-2">Review</a>
                                    </p>
                                    <?php endif; ?>
                                    <?php if ($metrics['failed_payments'] > 0): ?>
                                    <p class="mb-0">
                                        <strong><?php echo $metrics['failed_payments']; ?></strong> failed payment(s) today
                                        <a href="payment-transactions.php" class="btn btn-sm btn-danger ms-2">Check</a>
                                    </p>
                                    <?php endif; ?>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- end analytics and quick actions row -->

            </div> <!-- container-fluid -->

        </div> <!-- content -->

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

    </div>
    <!-- ============================================================== -->
    <!-- End Page content -->
    <!-- ============================================================== -->

</div>
<!-- END wrapper -->

<?php include 'partials/right-sidebar.php'; ?>

<?php include 'partials/footer-scripts.php'; ?>

<!-- knob plugin -->
<script src="assets/libs/jquery-knob/jquery.knob.min.js"></script>

<!--Morris Chart-->
<script src="assets/libs/morris.js06/morris.min.js"></script>
<script src="assets/libs/raphael/raphael.min.js"></script>

<!-- Dashboard init js-->
<script src="assets/js/pages/dashboard.init.js"></script>

<!-- App js-->
<script src="assets/js/app.min.js"></script>

<!-- Custom Dashboard JS -->
<script>
    console.log('🎉 Admin Dashboard loaded successfully!');
    console.log('Platform Metrics:', {
        customers: <?php echo $metrics['total_customers']; ?>,
        active_licenses: <?php echo $metrics['active_licenses']; ?>,
        todays_revenue: <?php echo $metrics['todays_revenue']; ?>,
        monthly_revenue: <?php echo $metrics['monthly_revenue']; ?>,
        open_tickets: <?php echo $metrics['open_tickets']; ?>,
        user: '<?php echo $_SESSION['user'] ?? ''; ?>',
        role: '<?php echo $user_role; ?>'
    });
    
    // Animate metric cards on load
    document.addEventListener('DOMContentLoaded', function() {
        // Animate metric cards
        const metricCards = document.querySelectorAll('.metric-card');
        metricCards.forEach((card, index) => {
            card.style.opacity = '0';
            card.style.transform = 'translateY(20px)';
            
            setTimeout(() => {
                card.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
                card.style.opacity = '1';
                card.style.transform = 'translateY(0)';
            }, 200 + (index * 100));
        });
        
        // Animate quick stats
        const quickStats = document.querySelectorAll('.quick-stats');
        quickStats.forEach((stat, index) => {
            stat.style.opacity = '0';
            stat.style.transform = 'scale(0.9)';
            
            setTimeout(() => {
                stat.style.transition = 'opacity 0.5s ease, transform 0.5s ease';
                stat.style.opacity = '1';
                stat.style.transform = 'scale(1)';
            }, 500 + (index * 100));
        });
        
        // Auto-refresh every 5 minutes
        setInterval(function() {
            console.log('Auto-refreshing dashboard data...');
            // Could implement AJAX refresh here instead of full page reload
        }, 300000); // 5 minutes
        
        // Initialize tooltips for metric cards
        const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        const tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });
    });
    
    // Function to refresh specific metrics via AJAX (can be implemented later)
    function refreshMetrics() {
        // AJAX call to refresh metrics without page reload
        console.log('Refreshing metrics...');
    }
    
    // Alert for critical issues
    <?php if ($metrics['piracy_violations'] > 0): ?>
    console.warn('⚠️ Piracy violations detected: <?php echo $metrics['piracy_violations']; ?>');
    <?php endif; ?>
    
    <?php if ($metrics['failed_payments'] > 0): ?>
    console.warn('⚠️ Failed payments today: <?php echo $metrics['failed_payments']; ?>');
    <?php endif; ?>
    
    <?php if ($metrics['critical_tickets'] > 0): ?>
    console.error('🚨 Critical support tickets: <?php echo $metrics['critical_tickets']; ?>');
    <?php endif; ?>
</script>

</body>

</html>