<?php 
// Include session handling
include 'services/session.php'; 

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

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

// Get user details
$user_role = $_SESSION['role_name'] ?? 'Customer';
$user_id = $_SESSION['user_id'] ?? 0;
$user_name = $_SESSION['full_name'] ?? $_SESSION['user'];

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

// Redirect admin users to admin dashboard
if (in_array($user_role, ['Administrator', 'Support Agent', 'Sales Manager', 'Developer'])) {
    error_log("→ Redirecting admin user to admin dashboard");
    header('Location: index.php');
    exit();
}

// Include database connection for customer 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 customer-specific metrics
$metrics = [
    'total_licenses' => 0,
    'active_licenses' => 0,
    'expired_licenses' => 0,
    'total_spent' => 0,
    'wallet_balance_usd' => 0,
    'wallet_balance_ssp' => 0,
    'wallet_balance_kes' => 0,
    'wallet_balance_ugx' => 0,
    'total_orders' => 0,
    'completed_orders' => 0,
    'pending_orders' => 0,
    'open_tickets' => 0,
    'total_downloads' => 0,
    'api_requests_today' => 0,
    'last_login' => null,
    'days_since_signup' => 0
];

// 1. Get license information
$result = safeQuery($conn, "
    SELECT 
        COUNT(*) as total,
        SUM(CASE WHEN status = 'ACTIVE' THEN 1 ELSE 0 END) as active,
        SUM(CASE WHEN status = 'EXPIRED' THEN 1 ELSE 0 END) as expired
    FROM licenses 
    WHERE user_id = ?
", [$user_id]);

if ($result) {
    $metrics['total_licenses'] = $result['total'] ?? 0;
    $metrics['active_licenses'] = $result['active'] ?? 0;
    $metrics['expired_licenses'] = $result['expired'] ?? 0;
}

// 2. Get wallet balances
$result = safeQuery($conn, "
    SELECT balance_usd, balance_ssp, balance_kes, balance_ugx
    FROM wallets 
    WHERE user_id = ? AND status = 'ACTIVE'
", [$user_id]);

if ($result) {
    $metrics['wallet_balance_usd'] = $result['balance_usd'] ?? 0;
    $metrics['wallet_balance_ssp'] = $result['balance_ssp'] ?? 0;
    $metrics['wallet_balance_kes'] = $result['balance_kes'] ?? 0;
    $metrics['wallet_balance_ugx'] = $result['balance_ugx'] ?? 0;
}

// 3. Get order information
$result = safeQuery($conn, "
    SELECT 
        COUNT(*) as total,
        SUM(CASE WHEN order_status = 'COMPLETED' THEN 1 ELSE 0 END) as completed,
        SUM(CASE WHEN order_status = 'PENDING' THEN 1 ELSE 0 END) as pending,
        SUM(CASE WHEN order_status = 'COMPLETED' THEN total_amount ELSE 0 END) as total_spent
    FROM orders 
    WHERE user_id = ?
", [$user_id]);

if ($result) {
    $metrics['total_orders'] = $result['total'] ?? 0;
    $metrics['completed_orders'] = $result['completed'] ?? 0;
    $metrics['pending_orders'] = $result['pending'] ?? 0;
    $metrics['total_spent'] = $result['total_spent'] ?? 0;
}

// 4. Get support tickets
$result = safeQuery($conn, "
    SELECT COUNT(*) as count
    FROM support_tickets 
    WHERE user_id = ? AND status IN ('OPEN', 'IN_PROGRESS')
", [$user_id]);

$metrics['open_tickets'] = $result['count'] ?? 0;

// 5. Get download count
$result = safeQuery($conn, "
    SELECT SUM(downloads_used) as count
    FROM download_links dl
    JOIN licenses l ON dl.license_id = l.license_id
    WHERE l.user_id = ?
", [$user_id]);

$metrics['total_downloads'] = $result['count'] ?? 0;

// 6. Get API requests today (if user has API access)
$result = safeQuery($conn, "
    SELECT COUNT(*) as count
    FROM api_requests ar
    JOIN api_keys ak ON ar.api_key_id = ak.api_key_id
    WHERE ak.user_id = ? AND DATE(ar.created_at) = CURDATE()
", [$user_id]);

$metrics['api_requests_today'] = $result['count'] ?? 0;

// 7. Get user signup date and last login
$result = safeQuery($conn, "
    SELECT created_at, last_login
    FROM users 
    WHERE user_id = ?
", [$user_id]);

if ($result) {
    $metrics['last_login'] = $result['last_login'];
    $signup_date = new DateTime($result['created_at']);
    $now = new DateTime();
    $metrics['days_since_signup'] = $now->diff($signup_date)->days;
}

// Get recent activities for this user
$recent_activities = safeQueryAll($conn, "
    SELECT 
        action,
        module,
        logged_at,
        additional_info
    FROM activity_log 
    WHERE user_id = ?
    ORDER BY logged_at DESC 
    LIMIT 8
", [$user_id]);

// Get user's licenses with product details
$user_licenses = safeQueryAll($conn, "
    SELECT 
        l.license_key,
        l.status,
        l.sites_allowed,
        l.sites_used,
        l.issued_at,
        l.expires_at,
        p.name as product_name,
        pp.tier_name,
        pp.price_usd,
        l.last_checked
    FROM licenses l
    JOIN products p ON l.product_id = p.product_id
    JOIN product_pricing pp ON l.pricing_tier_id = pp.pricing_id
    WHERE l.user_id = ?
    ORDER BY l.issued_at DESC
    LIMIT 5
", [$user_id]);

// Get user's recent orders
$recent_orders = safeQueryAll($conn, "
    SELECT 
        o.order_number,
        o.total_amount,
        o.currency,
        o.order_status,
        o.created_at,
        o.completed_at,
        COUNT(oi.item_id) as item_count
    FROM orders o
    LEFT JOIN order_items oi ON o.order_id = oi.order_id
    WHERE o.user_id = ?
    GROUP BY o.order_id
    ORDER BY o.created_at DESC
    LIMIT 5
", [$user_id]);

// Get wallet transactions
$wallet_transactions = safeQueryAll($conn, "
    SELECT 
        wt.transaction_type,
        wt.amount,
        wt.currency,
        wt.category,
        wt.description,
        wt.created_at,
        wt.status
    FROM wallet_transactions wt
    JOIN wallets w ON wt.wallet_id = w.wallet_id
    WHERE w.user_id = ?
    ORDER BY wt.created_at DESC
    LIMIT 8
", [$user_id]);

// Get available products for customer
$available_products = safeQueryAll($conn, "
    SELECT 
        p.product_id,
        p.name,
        p.short_description,
        p.features,
        p.supported_providers,
        pp.tier_name,
        pp.price_usd,
        pp.sites_allowed,
        pc.name as category_name
    FROM products p
    JOIN product_pricing pp ON p.product_id = pp.product_id
    JOIN product_categories pc ON p.category_id = pc.category_id
    WHERE p.is_active = 1 AND pp.is_active = 1
    ORDER BY p.is_featured DESC, pp.price_usd ASC
    LIMIT 6
");

// Get user's API keys if they have API access
$api_keys = [];
if ($metrics['api_requests_today'] > 0) {
    $api_keys = safeQueryAll($conn, "
        SELECT 
            name,
            api_key,
            permissions,
            rate_limit,
            requests_used,
            last_used_at,
            is_active
        FROM api_keys
        WHERE user_id = ? AND is_active = 1
        ORDER BY created_at DESC
        LIMIT 3
    ", [$user_id]);
}

// Get sandbox/demo information
$sandbox_apps = [
    [
        'name' => 'MTN MoMo Sandbox',
        'description' => 'Test MTN Mobile Money integration',
        'url' => 'mtn-momo-test.php',
        'status' => 'Available',
        'icon' => 'fas fa-mobile-alt',
        'color' => 'primary'
    ],
    [
        'name' => 'm-GURUSH Test Environment',
        'description' => 'Zain m-GURUSH payment testing',
        'url' => 'sandbox/mgurush-test.php',
        'status' => 'Available',
        'icon' => 'fas fa-credit-card',
        'color' => 'success'
    ],
    [
        'name' => 'Nilepay Demo',
        'description' => 'Test Nilepay integration',
        'url' => 'sandbox/nilepay-test.php',
        'status' => 'Maintenance',
        'icon' => 'fas fa-wallet',
        'color' => 'warning'
    ],
    [
        'name' => 'Plugin Customizer',
        'description' => 'Customize your downloaded plugins',
        'url' => 'tools/plugin-customizer.php',
        'status' => 'Available',
        'icon' => 'fas fa-cogs',
        'color' => 'info'
    ]
];

error_log("✓ Customer dashboard loaded successfully for user ID: $user_id");
?>

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

<head>
    <?php $title = "Customer Dashboard";
    include 'partials/title-meta.php'; ?>
    
    <?php include 'partials/head-css.php'; ?>
    
    <!-- Custom CSS for customer dashboard -->
    <style>
        .customer-welcome {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 2rem;
            margin-bottom: 2rem;
        }
        
        .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(-5px);
            box-shadow: 0 8px 30px rgba(0,0,0,0.12);
        }
        
        .license-card {
            border-left: 4px solid;
            margin-bottom: 1rem;
            padding: 1rem;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        
        .license-active { border-left-color: #28a745; }
        .license-expired { border-left-color: #dc3545; }
        .license-suspended { border-left-color: #ffc107; }
        
        .sandbox-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1rem;
            box-shadow: 0 3px 15px rgba(0,0,0,0.08);
            transition: all 0.3s ease;
            border: 1px solid #f0f0f0;
        }
        
        .sandbox-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 25px rgba(0,0,0,0.15);
        }
        
        .wallet-balance {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
            border-radius: 15px;
            padding: 1.5rem;
            margin-bottom: 1rem;
        }
        
        .currency-badge {
            background: rgba(255,255,255,0.2);
            padding: 0.3rem 0.8rem;
            border-radius: 20px;
            margin-right: 0.5rem;
            margin-bottom: 0.5rem;
            display: inline-block;
        }
        
        .activity-item {
            padding: 0.75rem 0;
            border-bottom: 1px solid #f1f3f4;
        }
        
        .activity-item:last-child {
            border-bottom: none;
        }
        
        .quick-action-btn {
            background: white;
            border: 2px solid #e9ecef;
            border-radius: 12px;
            padding: 1.5rem;
            text-decoration: none;
            color: #495057;
            display: block;
            transition: all 0.3s ease;
            margin-bottom: 1rem;
        }
        
        .quick-action-btn:hover {
            border-color: #007bff;
            color: #007bff;
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(0,123,255,0.15);
        }
        
        .stats-widget {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            border-radius: 15px;
            padding: 1.5rem;
            text-align: center;
            margin-bottom: 1rem;
        }
        
        .stats-widget h3 {
            margin-bottom: 0.5rem;
            font-weight: 700;
        }
        
        .stats-widget p {
            margin-bottom: 0;
            opacity: 0.9;
        }
        
        .product-card {
            border: 1px solid #e9ecef;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1rem;
            background: white;
            transition: all 0.3s ease;
        }
        
        .product-card:hover {
            border-color: #007bff;
            box-shadow: 0 4px 15px rgba(0,123,255,0.1);
        }
        
        .status-badge {
            padding: 0.3rem 0.8rem;
            border-radius: 15px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        
        .badge-success { background: #d4edda; color: #155724; }
        .badge-warning { background: #fff3cd; color: #856404; }
        .badge-danger { background: #f8d7da; color: #721c24; }
        .badge-info { background: #d1ecf1; color: #0c5460; }
    </style>
</head>

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

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

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

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

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

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

                <!-- Customer Welcome Section -->
                <div class="customer-welcome">
                    <div class="row align-items-center">
                        <div class="col-md-8">
                            <h2 class="mb-2">
                                <i class="fas fa-home me-2"></i>
                                Welcome back, <?php echo htmlspecialchars($user_name); ?>!
                            </h2>
                            <p class="mb-0 opacity-75">
                                Manage your plugins, monitor your licenses, and explore our sandbox environments
                            </p>
                        </div>
                        <div class="col-md-4 text-md-end">
                            <div class="text-white">
                                <h5 class="mb-1">
                                    <i class="fas fa-user-check me-2"></i>
                                    Account Status: Active
                                </h5>
                                <p class="mb-0">
                                    <i class="fas fa-calendar me-1"></i>
                                    Member for <?php echo $metrics['days_since_signup']; ?> days
                                </p>
                                <?php if ($metrics['last_login']): ?>
                                <small>Last login: <?php echo date('M j, Y g:i A', strtotime($metrics['last_login'])); ?></small>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Key Metrics Row -->
                <div class="row">
                    <!-- Active Licenses -->
                    <div class="col-xl-3 col-md-6">
                        <div class="metric-card">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h4 class="header-title">Active Licenses</h4>
                                        <h2 class="text-primary fw-bold"><?php echo $metrics['active_licenses']; ?></h2>
                                        <p class="text-muted mb-0">
                                            of <?php echo $metrics['total_licenses']; ?> total
                                            <?php if ($metrics['expired_licenses'] > 0): ?>
                                            <span class="badge bg-warning ms-1"><?php echo $metrics['expired_licenses']; ?> expired</span>
                                            <?php endif; ?>
                                        </p>
                                    </div>
                                    <div class="text-end">
                                        <i class="fas fa-key fa-2x text-primary opacity-50"></i>
                                    </div>
                                </div>
                                <div class="mt-3">
                                    <div class="progress" style="height: 5px;">
                                        <div class="progress-bar bg-primary" style="width: <?php echo $metrics['total_licenses'] > 0 ? ($metrics['active_licenses'] / $metrics['total_licenses'] * 100) : 0; ?>%"></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Total Spent -->
                    <div class="col-xl-3 col-md-6">
                        <div class="metric-card">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h4 class="header-title">Total Spent</h4>
                                        <h2 class="text-success fw-bold">$<?php echo number_format($metrics['total_spent'], 2); ?></h2>
                                        <p class="text-muted mb-0">
                                            <?php echo $metrics['completed_orders']; ?> completed orders
                                        </p>
                                    </div>
                                    <div class="text-end">
                                        <i class="fas fa-dollar-sign fa-2x text-success opacity-50"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Wallet Balance -->
                    <div class="col-xl-3 col-md-6">
                        <div class="metric-card">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h4 class="header-title">Wallet Balance</h4>
                                        <h2 class="text-info fw-bold">$<?php echo number_format($metrics['wallet_balance_usd'], 2); ?></h2>
                                        <p class="text-muted mb-0">
                                            <?php if ($metrics['wallet_balance_ssp'] > 0): ?>
                                            SSP <?php echo number_format($metrics['wallet_balance_ssp'], 0); ?>
                                            <?php endif; ?>
                                        </p>
                                    </div>
                                    <div class="text-end">
                                        <i class="fas fa-wallet fa-2x text-info opacity-50"></i>
                                    </div>
                                </div>
                                <div class="mt-2">
                                    <a href="topup-wallet.php" class="btn btn-sm btn-outline-info">Top Up</a>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Downloads -->
                    <div class="col-xl-3 col-md-6">
                        <div class="metric-card">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h4 class="header-title">Downloads</h4>
                                        <h2 class="text-warning fw-bold"><?php echo $metrics['total_downloads']; ?></h2>
                                        <p class="text-muted mb-0">
                                            <?php if ($metrics['open_tickets'] > 0): ?>
                                            <span class="badge bg-danger"><?php echo $metrics['open_tickets']; ?> open tickets</span>
                                            <?php else: ?>
                                            All systems operational
                                            <?php endif; ?>
                                        </p>
                                    </div>
                                    <div class="text-end">
                                        <i class="fas fa-download fa-2x text-warning opacity-50"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- end key metrics row -->

                <!-- Quick Stats Row -->
                <div class="row">
                    <div class="col-xl-2 col-md-4">
                        <div class="stats-widget" style="background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);">
                            <h3><?php echo $metrics['total_orders']; ?></h3>
                            <p>Total Orders</p>
                        </div>
                    </div>
                    <div class="col-xl-2 col-md-4">
                        <div class="stats-widget" style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);">
                            <h3><?php echo $metrics['pending_orders']; ?></h3>
                            <p>Pending Orders</p>
                        </div>
                    </div>
                    <div class="col-xl-2 col-md-4">
                        <div class="stats-widget" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
                            <h3><?php echo $metrics['api_requests_today']; ?></h3>
                            <p>API Requests Today</p>
                        </div>
                    </div>
                    <div class="col-xl-2 col-md-4">
                        <div class="stats-widget" style="background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);">
                            <h3><?php echo count($user_licenses); ?></h3>
                            <p>Plugin Products</p>
                        </div>
                    </div>
                    <div class="col-xl-2 col-md-4">
                        <div class="stats-widget" style="background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);">
                            <h3><?php echo count($api_keys); ?></h3>
                            <p>API Keys</p>
                        </div>
                    </div>
                    <div class="col-xl-2 col-md-4">
                        <div class="stats-widget" style="background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);">
                            <h3>4</h3>
                            <p>Sandbox Apps</p>
                        </div>
                    </div>
                </div>
                <!-- end quick stats row -->

                <!-- Main Content Row -->
                <div class="row">
                    <!-- Sandbox Applications -->
                    <div class="col-xl-6">
                        <div class="card">
                            <div class="card-body">
                                <h4 class="header-title mb-3">
                                    <i class="fas fa-flask me-2"></i>
                                    Sandbox & Testing Environment
                                </h4>
                                
                                <?php foreach ($sandbox_apps as $app): ?>
                                <div class="sandbox-card">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div class="flex-grow-1">
                                            <div class="d-flex align-items-center mb-2">
                                                <i class="<?php echo $app['icon']; ?> fa-lg text-<?php echo $app['color']; ?> me-3"></i>
                                                <h6 class="mb-0"><?php echo $app['name']; ?></h6>
                                                <span class="status-badge badge-<?php echo $app['status'] === 'Available' ? 'success' : ($app['status'] === 'Maintenance' ? 'warning' : 'danger'); ?> ms-auto">
                                                    <?php echo $app['status']; ?>
                                                </span>
                                            </div>
                                            <p class="text-muted mb-2"><?php echo $app['description']; ?></p>
                                            <div>
                                                <?php if ($app['status'] === 'Available'): ?>
                                                <a href="<?php echo $app['url']; ?>" class="btn btn-sm btn-outline-<?php echo $app['color']; ?>">
                                                    <i class="fas fa-play me-1"></i>
                                                    Launch
                                                </a>
                                                <?php else: ?>
                                                <button class="btn btn-sm btn-outline-secondary" disabled>
                                                    <i class="fas fa-pause me-1"></i>
                                                    <?php echo $app['status']; ?>
                                                </button>
                                                <?php endif; ?>
                                                <a href="docs/<?php echo strtolower(str_replace(' ', '-', $app['name'])); ?>.php" class="btn btn-sm btn-outline-info ms-1">
                                                    <i class="fas fa-book me-1"></i>
                                                    Docs
                                                </a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                                
                                <div class="text-center mt-3">
                                    <a href="sandbox-playground.php" class="btn btn-primary">
                                        <i class="fas fa-cogs me-2"></i>
                                        Advanced Sandbox Playground
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- My Licenses -->
                    <div class="col-xl-6">
                        <div class="card">
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-center mb-3">
                                    <h4 class="header-title mb-0">
                                        <i class="fas fa-key me-2"></i>
                                        My Licenses
                                    </h4>
                                    <a href="my-licenses.php" class="btn btn-sm btn-outline-primary">View All</a>
                                </div>

                                <?php if (empty($user_licenses)): ?>
                                <div class="text-center py-4">
                                    <i class="fas fa-key fa-3x mb-3 text-muted"></i>
                                    <h5>No licenses yet</h5>
                                    <p class="text-muted">Purchase your first plugin to get started</p>
                                    <a href="browse-plugins.php" class="btn btn-primary">
                                        <i class="fas fa-shopping-cart me-1"></i>
                                        Browse Plugins
                                    </a>
                                </div>
                                <?php else: ?>
                                    <?php foreach (array_slice($user_licenses, 0, 3) as $license): ?>
                                    <div class="license-card license-<?php echo strtolower($license['status']); ?>">
                                        <div class="d-flex justify-content-between align-items-start">
                                            <div class="flex-grow-1">
                                                <h6 class="mb-1"><?php echo htmlspecialchars($license['product_name']); ?></h6>
                                                <p class="text-muted mb-2 small">
                                                    <?php echo $license['tier_name']; ?> - $<?php echo number_format($license['price_usd'], 2); ?>
                                                </p>
                                                <div class="d-flex align-items-center">
                                                    <span class="badge bg-<?php echo $license['status'] === 'ACTIVE' ? 'success' : ($license['status'] === 'EXPIRED' ? 'danger' : 'warning'); ?> me-2">
                                                        <?php echo ucfirst(strtolower($license['status'])); ?>
                                                    </span>
                                                    <small class="text-muted">
                                                        <?php echo $license['sites_used']; ?>/<?php echo $license['sites_allowed']; ?> sites used
                                                    </small>
                                                </div>
                                            </div>
                                            <div class="text-end">
                                                <small class="text-muted d-block">
                                                    <?php echo date('M j, Y', strtotime($license['issued_at'])); ?>
                                                </small>
                                                <?php if ($license['expires_at']): ?>
                                                <small class="text-muted d-block">
                                                    Expires: <?php echo date('M j, Y', strtotime($license['expires_at'])); ?>
                                                </small>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        <div class="mt-2">
                                            <a href="download-plugins.php?license=<?php echo $license['license_key']; ?>" class="btn btn-sm btn-outline-primary me-1">
                                                <i class="fas fa-download"></i> Download
                                            </a>
                                            <a href="license-details.php?key=<?php echo $license['license_key']; ?>" class="btn btn-sm btn-outline-info">
                                                <i class="fas fa-info-circle"></i> Details
                                            </a>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- end main content row -->

                <!-- Secondary Content Row -->
                <div class="row">
                    <!-- Recent Activity -->
                    <div class="col-xl-4">
                        <div class="card">
                            <div class="card-body">
                                <h4 class="header-title mb-3">
                                    <i class="fas fa-history me-2"></i>
                                    Recent Activity
                                </h4>

                                <?php if (empty($recent_activities)): ?>
                                <div class="text-center py-3">
                                    <i class="fas fa-clock fa-2x mb-2 text-muted"></i>
                                    <p class="text-muted">No recent activity</p>
                                </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: 30px; height: 30px;">
                                                    <i class="fas fa-<?php 
                                                    switch($activity['action']) {
                                                        case 'PURCHASE': echo 'shopping-cart';
                                                            break;
                                                        case 'DOWNLOAD': echo 'download';
                                                            break;
                                                        case 'LOGIN': echo 'sign-in-alt';
                                                            break;
                                                        case 'UPDATE': echo 'edit';
                                                            break;
                                                        default: echo 'user';
                                                    }
                                                    ?> fa-xs"></i>
                                                </div>
                                            </div>
                                            <div class="flex-grow-1 ms-2">
                                                <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 text-muted font-11">
                                                    <?php echo date('M j, Y g:i A', strtotime($activity['logged_at'])); ?>
                                                </p>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                    <!-- Wallet Overview -->
                    <div class="col-xl-4">
                        <div class="card">
                            <div class="card-body">
                                <h4 class="header-title mb-3">
                                    <i class="fas fa-wallet me-2"></i>
                                    Wallet Overview
                                </h4>
                                
                                <div class="wallet-balance mb-3">
                                    <h5 class="mb-2">Total Balance</h5>
                                    <h3 class="mb-3">$<?php echo number_format($metrics['wallet_balance_usd'], 2); ?> USD</h3>
                                    
                                    <?php if ($metrics['wallet_balance_ssp'] > 0): ?>
                                    <div class="currency-badge">
                                        SSP <?php echo number_format($metrics['wallet_balance_ssp'], 0); ?>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <?php if ($metrics['wallet_balance_kes'] > 0): ?>
                                    <div class="currency-badge">
                                        KES <?php echo number_format($metrics['wallet_balance_kes'], 0); ?>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <?php if ($metrics['wallet_balance_ugx'] > 0): ?>
                                    <div class="currency-badge">
                                        UGX <?php echo number_format($metrics['wallet_balance_ugx'], 0); ?>
                                    </div>
                                    <?php endif; ?>
                                </div>

                                <div class="d-grid gap-2">
                                    <a href="topup-wallet.php" class="btn btn-primary">
                                        <i class="fas fa-plus me-2"></i>
                                        Top Up Wallet
                                    </a>
                                    <a href="wallet-overview.php" class="btn btn-outline-primary">
                                        <i class="fas fa-eye me-2"></i>
                                        View Transactions
                                    </a>
                                </div>

                                <?php if (!empty($wallet_transactions)): ?>
                                <hr>
                                <h6>Recent Transactions</h6>
                                    <?php foreach (array_slice($wallet_transactions, 0, 3) as $transaction): ?>
                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                        <div>
                                            <small class="fw-bold text-<?php echo $transaction['transaction_type'] === 'CREDIT' ? 'success' : 'danger'; ?>">
                                                <?php echo $transaction['transaction_type'] === 'CREDIT' ? '+' : '-'; ?>
                                                <?php echo $transaction['currency']; ?> <?php echo number_format($transaction['amount'], 2); ?>
                                            </small>
                                            <small class="d-block text-muted"><?php echo ucfirst(strtolower($transaction['category'])); ?></small>
                                        </div>
                                        <small class="text-muted">
                                            <?php echo date('M j', strtotime($transaction['created_at'])); ?>
                                        </small>
                                    </div>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                    <!-- Quick Actions -->
                    <div class="col-xl-4">
                        <div class="card">
                            <div class="card-body">
                                <h4 class="header-title mb-3">
                                    <i class="fas fa-bolt me-2"></i>
                                    Quick Actions
                                </h4>
                                
                                <a href="browse-plugins.php" class="quick-action-btn">
                                    <div class="d-flex align-items-center">
                                        <i class="fas fa-shopping-cart fa-lg text-primary me-3"></i>
                                        <div>
                                            <h6 class="mb-1">Browse Plugins</h6>
                                            <small class="text-muted">Explore our plugin marketplace</small>
                                        </div>
                                    </div>
                                </a>

                                <a href="download-plugins.php" class="quick-action-btn">
                                    <div class="d-flex align-items-center">
                                        <i class="fas fa-download fa-lg text-success me-3"></i>
                                        <div>
                                            <h6 class="mb-1">Download Plugins</h6>
                                            <small class="text-muted">Get your purchased plugins</small>
                                        </div>
                                    </div>
                                </a>

                                <a href="create-ticket.php" class="quick-action-btn">
                                    <div class="d-flex align-items-center">
                                        <i class="fas fa-headphones fa-lg text-info me-3"></i>
                                        <div>
                                            <h6 class="mb-1">Get Support</h6>
                                            <small class="text-muted">Create a support ticket</small>
                                        </div>
                                    </div>
                                </a>

                                <a href="documentation.php" class="quick-action-btn">
                                    <div class="d-flex align-items-center">
                                        <i class="fas fa-book fa-lg text-warning me-3"></i>
                                        <div>
                                            <h6 class="mb-1">Documentation</h6>
                                            <small class="text-muted">Plugin guides and tutorials</small>
                                        </div>
                                    </div>
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- end secondary content row -->

                <!-- Recent Orders & Available Products -->
                <div class="row">
                    <!-- Recent Orders -->
                    <div class="col-xl-6">
                        <div class="card">
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-center mb-3">
                                    <h4 class="header-title mb-0">
                                        <i class="fas fa-shopping-bag me-2"></i>
                                        Recent Orders
                                    </h4>
                                    <a href="my-orders.php" class="btn btn-sm btn-outline-primary">View All</a>
                                </div>

                                <?php if (empty($recent_orders)): ?>
                                <div class="text-center py-4">
                                    <i class="fas fa-shopping-cart fa-3x mb-3 text-muted"></i>
                                    <h5>No orders yet</h5>
                                    <p class="text-muted">Start by purchasing your first plugin</p>
                                    <a href="browse-plugins.php" class="btn btn-primary">
                                        <i class="fas fa-shopping-cart me-1"></i>
                                        Browse Plugins
                                    </a>
                                </div>
                                <?php else: ?>
                                <div class="table-responsive">
                                    <table class="table table-sm mb-0">
                                        <thead>
                                            <tr>
                                                <th>Order #</th>
                                                <th>Amount</th>
                                                <th>Status</th>
                                                <th>Date</th>
                                                <th>Action</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($recent_orders as $order): ?>
                                            <tr>
                                                <td>
                                                    <strong><?php echo htmlspecialchars($order['order_number']); ?></strong>
                                                    <small class="d-block text-muted"><?php echo $order['item_count']; ?> item(s)</small>
                                                </td>
                                                <td>
                                                    <strong><?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;
                                                        default:
                                                            $statusClass = 'bg-secondary';
                                                    }
                                                    ?>
                                                    <span class="badge <?php echo $statusClass; ?>">
                                                        <?php echo ucfirst(strtolower($order['order_status'])); ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <small><?php echo date('M j, Y', strtotime($order['created_at'])); ?></small>
                                                </td>
                                                <td>
                                                    <a href="view-order.php?order=<?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>

                    <!-- Available Products -->
                    <div class="col-xl-6">
                        <div class="card">
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-center mb-3">
                                    <h4 class="header-title mb-0">
                                        <i class="fas fa-store me-2"></i>
                                        Featured Products
                                    </h4>
                                    <a href="browse-plugins.php" class="btn btn-sm btn-outline-primary">Browse All</a>
                                </div>

                                <?php if (empty($available_products)): ?>
                                <div class="text-center py-4">
                                    <i class="fas fa-box fa-3x mb-3 text-muted"></i>
                                    <h5>No products available</h5>
                                    <p class="text-muted">Products will be available soon</p>
                                </div>
                                <?php else: ?>
                                    <?php foreach (array_slice($available_products, 0, 3) as $product): ?>
                                    <div class="product-card">
                                        <div class="d-flex justify-content-between align-items-start">
                                            <div class="flex-grow-1">
                                                <h6 class="mb-1"><?php echo htmlspecialchars($product['name']); ?></h6>
                                                <p class="text-muted mb-2 small">
                                                    <?php echo htmlspecialchars($product['short_description']); ?>
                                                </p>
                                                <div class="d-flex align-items-center justify-content-between">
                                                    <span class="badge bg-light text-dark">
                                                        <?php echo htmlspecialchars($product['category_name']); ?>
                                                    </span>
                                                    <div>
                                                        <strong class="text-primary">$<?php echo number_format($product['price_usd'], 2); ?></strong>
                                                        <small class="text-muted">/ <?php echo $product['tier_name']; ?></small>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="mt-2">
                                            <a href="product-details.php?id=<?php echo $product['product_id']; ?>" class="btn btn-sm btn-outline-primary me-1">
                                                <i class="fas fa-info-circle"></i> Details
                                            </a>
                                            <a href="purchase.php?product=<?php echo $product['product_id']; ?>&tier=<?php echo $product['tier_name']; ?>" class="btn btn-sm btn-primary">
                                                <i class="fas fa-shopping-cart"></i> Buy Now
                                            </a>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- end orders and products row -->

                <!-- API Access Section (if user has API keys) -->
                <?php if (!empty($api_keys)): ?>
                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-center mb-3">
                                    <h4 class="header-title mb-0">
                                        <i class="fas fa-code me-2"></i>
                                        API Access
                                    </h4>
                                    <a href="api-access.php" class="btn btn-sm btn-outline-primary">Manage APIs</a>
                                </div>

                                <div class="row">
                                    <?php foreach ($api_keys as $api): ?>
                                    <div class="col-md-4">
                                        <div class="card border">
                                            <div class="card-body">
                                                <h6 class="card-title"><?php echo htmlspecialchars($api['name']); ?></h6>
                                                <p class="card-text">
                                                    <small class="text-muted">API Key: <?php echo substr($api['api_key'], 0, 8); ?>...</small>
                                                </p>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <small class="text-muted">
                                                        <?php echo $api['requests_used']; ?>/<?php echo $api['rate_limit']; ?> requests
                                                    </small>
                                                    <span class="badge bg-<?php echo $api['is_active'] ? 'success' : 'secondary'; ?>">
                                                        <?php echo $api['is_active'] ? 'Active' : 'Inactive'; ?>
                                                    </span>
                                                </div>
                                                <div class="progress mt-2" style="height: 4px;">
                                                    <div class="progress-bar" style="width: <?php echo ($api['requests_used'] / $api['rate_limit']) * 100; ?>%"></div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
                <!-- end API access 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'; ?>

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

<!-- Custom Customer Dashboard JS -->
<script>
    console.log('🎉 Customer Dashboard loaded successfully!');
    console.log('Customer Metrics:', {
        user_id: <?php echo $user_id; ?>,
        active_licenses: <?php echo $metrics['active_licenses']; ?>,
        total_spent: <?php echo $metrics['total_spent']; ?>,
        wallet_balance: <?php echo $metrics['wallet_balance_usd']; ?>,
        total_downloads: <?php echo $metrics['total_downloads']; ?>,
        user: '<?php echo $_SESSION['user'] ?? ''; ?>',
        role: '<?php echo $user_role; ?>'
    });
    
    // Animate cards on load
    document.addEventListener('DOMContentLoaded', function() {
        // Animate metric cards
        const metricCards = document.querySelectorAll('.metric-card');
        metricCards.forEach(function(card, index) {
            card.style.opacity = '0';
            card.style.transform = 'translateY(20px)';
            
            setTimeout(function() {
                card.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
                card.style.opacity = '1';
                card.style.transform = 'translateY(0)';
            }, 100 + (index * 150));
        });
        
        // Animate sandbox cards
        const sandboxCards = document.querySelectorAll('.sandbox-card');
        sandboxCards.forEach(function(card, index) {
            card.style.opacity = '0';
            card.style.transform = 'scale(0.95)';
            
            setTimeout(function() {
                card.style.transition = 'opacity 0.5s ease, transform 0.5s ease';
                card.style.opacity = '1';
                card.style.transform = 'scale(1)';
            }, 300 + (index * 100));
        });
        
        // Animate stats widgets
        const statsWidgets = document.querySelectorAll('.stats-widget');
        statsWidgets.forEach(function(widget, index) {
            widget.style.opacity = '0';
            widget.style.transform = 'translateX(-20px)';
            
            setTimeout(function() {
                widget.style.transition = 'opacity 0.4s ease, transform 0.4s ease';
                widget.style.opacity = '1';
                widget.style.transform = 'translateX(0)';
            }, 500 + (index * 80));
        });
        
        // Initialize tooltips if Bootstrap is available
        if (typeof bootstrap !== 'undefined') {
            const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
            const tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
                return new bootstrap.Tooltip(tooltipTriggerEl);
            });
        }
        
        // Auto-refresh wallet balance every 30 seconds
        setInterval(function() {
            refreshWalletBalance();
        }, 30000);
    });
    
    // Function to refresh wallet balance via AJAX
    function refreshWalletBalance() {
        fetch('api/get-wallet-balance.php')
            .then(function(response) { return response.json(); })
            .then(function(data) {
                if (data.success) {
                    // Update wallet balance display
                    const balanceElements = document.querySelectorAll('.wallet-balance h3');
                    balanceElements.forEach(function(el) {
                        el.textContent = '
                                     + parseFloat(data.balance_usd).toFixed(2) + ' USD';
                    });
                }
            })
            .catch(function(error) {
                console.error('Error refreshing wallet balance:', error);
            });
    }
    
    // Handle sandbox app launches
    function launchSandboxApp(appUrl, appName) {
        console.log('Launching ' + appName + '...');
        window.open(appUrl, '_blank');
    }
    
    // Show success message for new customers
    <?php if ($metrics['days_since_signup'] <= 7): ?>
    setTimeout(function() {
        if (<?php echo $metrics['total_licenses']; ?> === 0) {
            if (typeof Swal !== 'undefined') {
                Swal.fire({
                    title: 'Welcome to ConnectPay!',
                    text: 'Ready to integrate mobile money payments? Browse our plugin marketplace to get started.',
                    icon: 'info',
                    confirmButtonText: 'Browse Plugins',
                    showCancelButton: true,
                    cancelButtonText: 'Later'
                }).then(function(result) {
                    if (result.isConfirmed) {
                        window.location.href = 'browse-plugins.php';
                    }
                });
            }
        }
    }, 2000);
    <?php endif; ?>
    
    // Alert for low wallet balance
    <?php if ($metrics['wallet_balance_usd'] < 10 && $metrics['total_licenses'] > 0): ?>
    console.warn('💰 Low wallet balance detected');
    <?php endif; ?>
    
    // Alert for expired licenses
    <?php if ($metrics['expired_licenses'] > 0): ?>
    console.warn('⚠️ Expired licenses detected: <?php echo $metrics['expired_licenses']; ?>');
    <?php endif; ?>
</script>

</body>

</html>