<?php
// Include database connection
if (!isset($conn)) {
    include_once 'layouts/dbconn.php';
}

// Ensure session is started
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Get user information from session
$user_id = $_SESSION['user_id'] ?? 0;
$user_role_id = $_SESSION['role_id'] ?? 0;
$full_name = $_SESSION['full_name'] ?? 'Guest User';
$email = $_SESSION['email'] ?? '';
$avatar = $_SESSION['avatar'] ?? 'assets/images/users/default-avatar.jpg';

// Get user details and role information
$user_role = 'guest';
$user_permissions = [];

if ($user_id > 0 && $user_role_id > 0) {
    try {
        // Get user role name
        $stmt = $conn->prepare("SELECT role_name FROM user_roles WHERE role_id = ?");
        $stmt->bind_param("i", $user_role_id);
        $stmt->execute();
        $result = $stmt->get_result()->fetch_assoc();
        $user_role = $result['role_name'] ?? 'guest';
        $stmt->close();

        // Get user's permissions from database
        $stmt = $conn->prepare("
            SELECT p.name 
            FROM permissions p
            INNER JOIN role_permissions rp ON p.permission_id = rp.permission_id
            WHERE rp.role_id = ?
        ");
        $stmt->bind_param("i", $user_role_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        while ($row = $result->fetch_assoc()) {
            $user_permissions[] = $row['name'];
        }
        $stmt->close();
    } catch (Exception $e) {
        error_log("Error fetching user data: " . $e->getMessage());
    }
}

// Helper function to check if user has permission
function hasPermission($permission) {
    global $user_permissions;
    return in_array($permission, $user_permissions);
}

// Get various counts for badges
function getUnreadNotifications() {
    global $conn, $user_id;
    if ($user_id <= 0) return 0;
    try {
        $stmt = $conn->prepare("SELECT COUNT(*) as count FROM notifications WHERE user_id = ? AND is_read = 0");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $result = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        return $result['count'] ?? 0;
    } catch (Exception $e) {
        return 0;
    }
}

function getOpenTickets() {
    global $conn, $user_id, $user_role;
    if ($user_id <= 0) return 0;
    try {
        if ($user_role === 'Customer') {
            $stmt = $conn->prepare("SELECT COUNT(*) as count FROM support_tickets WHERE user_id = ? AND status IN ('OPEN', 'IN_PROGRESS')");
            $stmt->bind_param("i", $user_id);
        } else {
            $stmt = $conn->prepare("SELECT COUNT(*) as count FROM support_tickets WHERE status IN ('OPEN', 'IN_PROGRESS')");
        }
        $stmt->execute();
        $result = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        return $result['count'] ?? 0;
    } catch (Exception $e) {
        return 0;
    }
}

function getActiveLicensesCount() {
    global $conn, $user_id, $user_role;
    if ($user_role !== 'Customer' || $user_id <= 0) return 0;
    try {
        $stmt = $conn->prepare("SELECT COUNT(*) as count FROM licenses WHERE user_id = ? AND status = 'ACTIVE'");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $result = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        return $result['count'] ?? 0;
    } catch (Exception $e) {
        return 0;
    }
}

function getWalletBalance() {
    global $conn, $user_id, $user_role;
    if ($user_role !== 'Customer' || $user_id <= 0) return 0;
    try {
        $stmt = $conn->prepare("SELECT balance_usd FROM wallets WHERE user_id = ?");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $result = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        return $result['balance_usd'] ?? 0;
    } catch (Exception $e) {
        return 0;
    }
}

function getPendingOrders() {
    global $conn, $user_role;
    if (!hasPermission('manage_payments')) return 0;
    try {
        $stmt = $conn->prepare("SELECT COUNT(*) as count FROM orders WHERE order_status = 'PENDING' AND created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)");
        $stmt->execute();
        $result = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        return $result['count'] ?? 0;
    } catch (Exception $e) {
        return 0;
    }
}

function getPiracyViolations() {
    global $conn, $user_role;
    if (!in_array($user_role, ['Administrator', 'Support Agent'])) return 0;
    try {
        $stmt = $conn->prepare("SELECT COUNT(*) as count FROM piracy_violations WHERE status = 'PENDING' AND severity IN ('HIGH', 'CRITICAL')");
        $stmt->execute();
        $result = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        return $result['count'] ?? 0;
    } catch (Exception $e) {
        return 0;
    }
}
?>

<!-- ========== Left Sidebar Start ========== -->
<div class="left-side-menu">

    <div class="h-100" data-simplebar>

         <!-- User box -->
        <div class="user-box text-center">

            <img src="<?php echo htmlspecialchars($avatar); ?>" alt="user-img" title="<?php echo htmlspecialchars($full_name); ?>" class="rounded-circle img-thumbnail avatar-md">
                <div class="dropdown">
                    <a href="#" class="user-name dropdown-toggle h5 mt-2 mb-1 d-block" data-bs-toggle="dropdown" aria-expanded="false"><?php echo htmlspecialchars($full_name); ?></a>
                    <div class="dropdown-menu user-pro-dropdown">

                        <!-- item-->
                        <a href="profile.php" class="dropdown-item notify-item">
                            <i class="mdi mdi-account-circle me-1"></i>
                            <span>My Account</span>
                        </a>
        
                        <!-- item-->
                        <a href="settings.php" class="dropdown-item notify-item">
                            <i class="mdi mdi-cog me-1"></i>
                            <span>Settings</span>
                        </a>

                        <?php if ($user_role === 'Customer'): ?>
                        <!-- item-->
                        <a href="billing-info.php" class="dropdown-item notify-item">
                            <i class="mdi mdi-credit-card me-1"></i>
                            <span>Billing</span>
                        </a>
                        <?php endif; ?>
        
                        <!-- item-->
                        <a href="change-password.php" class="dropdown-item notify-item">
                            <i class="mdi mdi-lock me-1"></i>
                            <span>Change Password</span>
                        </a>
        
                        <!-- item-->
                        <a href="auth-logout.php" class="dropdown-item notify-item">
                            <i class="mdi mdi-power me-1"></i>
                            <span>Logout</span>
                        </a>
        
                    </div>
                </div>

            <p class="text-muted left-user-info"><?php echo htmlspecialchars($user_role); ?></p>

            <ul class="list-inline">
                <?php if ($user_role === 'Customer'): ?>
                <li class="list-inline-item">
                    <a href="notifications-settings.php" class="text-muted left-user-info" title="Notifications">
                        <i class="mdi mdi-bell"></i>
                        <?php 
                        $notifications = getUnreadNotifications();
                        if ($notifications > 0): 
                        ?>
                        <span class="badge badge-danger rounded-pill"><?php echo $notifications; ?></span>
                        <?php endif; ?>
                    </a>
                </li>
                <?php endif; ?>

                <li class="list-inline-item">
                    <a href="settings.php" class="text-muted left-user-info" title="Settings">
                        <i class="mdi mdi-cog"></i>
                    </a>
                </li>

                <li class="list-inline-item">
                    <a href="auth-logout.php" title="Logout">
                        <i class="mdi mdi-power"></i>
                    </a>
                </li>
            </ul>
        </div>

        <!--- Sidemenu -->
        <div id="sidebar-menu">

            <ul id="side-menu">

                <li class="menu-title">Main</li>
                
                <li>
                    <a href="<?php echo ($user_role === 'Customer') ? 'dashboard.php' : 'index.php'; ?>">
                        <i class="mdi mdi-view-dashboard-outline"></i>
                        <?php 
                        $dashboardBadge = 0;
                        if ($user_role === 'Customer') {
                            $dashboardBadge = getActiveLicensesCount();
                        } else {
                            $dashboardBadge = getPendingOrders();
                        }
                        if ($dashboardBadge > 0): 
                        ?>
                        <span class="badge bg-success rounded-pill float-end"><?php echo $dashboardBadge; ?></span>
                        <?php endif; ?>
                        <span> Dashboard </span>
                    </a>
                </li>

                <?php if ($user_role === 'Customer'): ?>
                <!-- Customer Menu Items -->
                <li class="menu-title mt-2">My Account</li>

                <li>
                    <a href="#licenses" data-bs-toggle="collapse">
                        <i class="mdi mdi-key-variant"></i>
                        <span> Licenses & Downloads </span>
                        <?php 
                        $activeLicenses = getActiveLicensesCount();
                        if ($activeLicenses > 0): 
                        ?>
                        <span class="badge bg-success rounded-pill float-end"><?php echo $activeLicenses; ?></span>
                        <?php endif; ?>
                        <span class="menu-arrow"></span>
                    </a>
                    <div class="collapse" id="licenses">
                        <ul class="nav-second-level">
                            <li><a href="my-licenses.php">My Licenses</a></li>
                            <li><a href="download-plugins.php">Download Plugins</a></li>
                            <li><a href="license-activation.php">Activate License</a></li>
                            <li><a href="customization-settings.php">Plugin Customization</a></li>
                        </ul>
                    </div>
                </li>

                <li>
                    <a href="#wallet" data-bs-toggle="collapse">
                        <i class="mdi mdi-wallet-outline"></i>
                        <span> Wallet & Payments </span>
                        <?php 
                        $walletBalance = getWalletBalance();
                        if ($walletBalance > 0): 
                        ?>
                        <span class="badge bg-info rounded-pill float-end">$<?php echo number_format($walletBalance, 0); ?></span>
                        <?php endif; ?>
                        <span class="menu-arrow"></span>
                    </a>
                    <div class="collapse" id="wallet">
                        <ul class="nav-second-level">
                            <li><a href="wallet-overview.php">Wallet Overview</a></li>
                            <li><a href="topup-wallet.php">Top Up Wallet</a></li>
                            <li><a href="payment-history.php">Payment History</a></li>
                            <li><a href="transaction-receipts.php">Receipts</a></li>
                        </ul>
                    </div>
                </li>

                <li>
                    <a href="#store" data-bs-toggle="collapse">
                        <i class="mdi mdi-shopping-outline"></i>
                        <span> Plugin Store </span>
                        <span class="menu-arrow"></span>
                    </a>
                    <div class="collapse" id="store">
                        <ul class="nav-second-level">
                            <li><a href="browse-plugins.php">Browse Plugins</a></li>
                            <li><a href="payment-gateways.php">Payment Gateways</a></li>
                            <li><a href="custom-solutions.php">Custom Solutions</a></li>
                            <li><a href="my-orders.php">My Orders</a></li>
                        </ul>
                    </div>
                </li>

                <li>
                    <a href="#momo-settings" data-bs-toggle="collapse">
                        <i class="mdi mdi-cellphone-cog"></i>
                        <span> MoMo Integration </span>
                        <span class="menu-arrow"></span>
                    </a>
                    <div class="collapse" id="momo-settings">
                        <ul class="nav-second-level">
                            <li><a href="mtn-credentials.php">MTN MoMo Setup</a></li>
                            <li><a href="provider-credentials.php">Other Providers</a></li>
                            <li><a href="test-integration.php">Test Integration</a></li>
                            <li><a href="webhook-settings.php">Webhook Settings</a></li>
                        </ul>
                    </div>
                </li>

                <li>
                    <a href="customer-analytics.php">
                        <i class="mdi mdi-chart-line"></i>
                        <span> My Analytics </span>
                    </a>
                </li>

                <li>
                    <a href="#support" data-bs-toggle="collapse">
                        <i class="mdi mdi-help-circle-outline"></i>
                        <span> Support </span>
                        <?php 
                        $openTickets = getOpenTickets();
                        if ($openTickets > 0): 
                        ?>
                        <span class="badge bg-danger rounded-pill float-end"><?php echo $openTickets; ?></span>
                        <?php endif; ?>
                        <span class="menu-arrow"></span>
                    </a>
                    <div class="collapse" id="support">
                        <ul class="nav-second-level">
                            <li><a href="my-tickets.php">My Tickets</a></li>
                            <li><a href="create-ticket.php">Create Ticket</a></li>
                            <li><a href="documentation.php">Documentation</a></li>
                            <li><a href="faqs.php">FAQs</a></li>
                        </ul>
                    </div>
                </li>

                <?php else: ?>
                <!-- Admin/Staff Menu Items -->
                <li class="menu-title mt-2">Management</li>

                <?php if (hasPermission('manage_users')): ?>
                <li>
                    <a href="#users" data-bs-toggle="collapse">
                        <i class="mdi mdi-account-multiple-outline"></i>
                        <span> Users & Customers </span>
                        <span class="menu-arrow"></span>
                    </a>
                    <div class="collapse" id="users">
                        <ul class="nav-second-level">
                            <li><a href="manage-customers.php">Customers</a></li>
                            <li><a href="manage-staff.php">Staff Users</a></li>
                            <li><a href="list_roles.php">Roles & Permissions</a></li>
                            <li><a href="user-activity.php">Activity Log</a></li>
                        </ul>
                    </div>
                </li>
                <?php endif; ?>

                <?php if (hasPermission('manage_products')): ?>
                <li>
                    <a href="#products" data-bs-toggle="collapse">
                        <i class="mdi mdi-package-variant-closed"></i>
                        <span> Products & Plugins </span>
                        <span class="menu-arrow"></span>
                    </a>
                    <div class="collapse" id="products">
                        <ul class="nav-second-level">
                            <li><a href="manage-products.php">All Products</a></li>
                            <li><a href="product-categories.php">Categories</a></li>
                            <li><a href="plugin-templates.php">Plugin Templates</a></li>
                            <li><a href="pricing-tiers.php">Pricing Tiers</a></li>
                            <li><a href="subscription-tiers.php">Subscription Plans</a></li>
                        </ul>
                    </div>
                </li>
                <?php endif; ?>

                <?php if (hasPermission('manage_licenses')): ?>
                <li>
                    <a href="#admin-licenses" data-bs-toggle="collapse">
                        <i class="mdi mdi-shield-check-outline"></i>
                        <span> License Management </span>
                        <?php 
                        $piracyViolations = getPiracyViolations();
                        if ($piracyViolations > 0): 
                        ?>
                        <span class="badge bg-warning rounded-pill float-end"><?php echo $piracyViolations; ?></span>
                        <?php endif; ?>
                        <span class="menu-arrow"></span>
                    </a>
                    <div class="collapse" id="admin-licenses">
                        <ul class="nav-second-level">
                            <li><a href="all-licenses.php">All Licenses</a></li>
                            <li><a href="license-activations.php">Activations</a></li>
                            <li><a href="piracy-violations.php">Piracy Violations</a></li>
                            <li><a href="license-analytics.php">License Analytics</a></li>
                        </ul>
                    </div>
                </li>
                <?php endif; ?>

                <?php if (hasPermission('manage_payments')): ?>
                <li>
                    <a href="#orders" data-bs-toggle="collapse">
                        <i class="mdi mdi-shopping-outline"></i>
                        <span> Orders & Payments </span>
                        <?php 
                        $pendingOrders = getPendingOrders();
                        if ($pendingOrders > 0): 
                        ?>
                        <span class="badge bg-info rounded-pill float-end"><?php echo $pendingOrders; ?></span>
                        <?php endif; ?>
                        <span class="menu-arrow"></span>
                    </a>
                    <div class="collapse" id="orders">
                        <ul class="nav-second-level">
                            <li><a href="all-orders.php">All Orders</a></li>
                            <li><a href="payment-transactions.php">Transactions</a></li>
                            <li><a href="wallet-management.php">Wallet Management</a></li>
                            <li><a href="refunds.php">Refunds</a></li>
                            <li><a href="discount-codes.php">Discount Codes</a></li>
                        </ul>
                    </div>
                </li>
                <?php endif; ?>

                <?php if (hasPermission('manage_companies')): ?>
                <li>
                    <a href="#companies" data-bs-toggle="collapse">
                        <i class="mdi mdi-office-building-outline"></i>
                        <span> Company Management </span>
                        <span class="menu-arrow"></span>
                    </a>
                    <div class="collapse" id="companies">
                        <ul class="nav-second-level">
                            <li><a href="all-companies.php">All Companies</a></li>
                            <li><a href="kyc-approvals.php">KYC Approvals</a></li>
                            <li><a href="compliance-reports.php">Compliance Reports</a></li>
                            <li><a href="risk-assessment.php">Risk Assessment</a></li>
                        </ul>
                    </div>
                </li>
                <?php endif; ?>

                <?php if (hasPermission('manage_support')): ?>
                <li>
                    <a href="#admin-support" data-bs-toggle="collapse">
                        <i class="mdi mdi-headphones"></i>
                        <span> Support Center </span>
                        <?php 
                        $allTickets = getOpenTickets();
                        if ($allTickets > 0): 
                        ?>
                        <span class="badge bg-danger rounded-pill float-end"><?php echo $allTickets; ?></span>
                        <?php endif; ?>
                        <span class="menu-arrow"></span>
                    </a>
                    <div class="collapse" id="admin-support">
                        <ul class="nav-second-level">
                            <li><a href="all-tickets.php">All Tickets</a></li>
                            <li><a href="ticket-queue.php">Ticket Queue</a></li>
                            <li><a href="knowledge-base.php">Knowledge Base</a></li>
                            <li><a href="canned-responses.php">Canned Responses</a></li>
                        </ul>
                    </div>
                </li>
                <?php endif; ?>

                <li class="menu-title mt-2">Analytics & Reports</li>

                <?php if (hasPermission('view_analytics')): ?>
                <li>
                    <a href="#analytics" data-bs-toggle="collapse">
                        <i class="mdi mdi-chart-areaspline"></i>
                        <span> Business Analytics </span>
                        <span class="menu-arrow"></span>
                    </a>
                    <div class="collapse" id="analytics">
                        <ul class="nav-second-level">
                            <li><a href="sales-analytics.php">Sales Analytics</a></li>
                            <li><a href="revenue-reports.php">Revenue Reports</a></li>
                            <li><a href="customer-analytics.php">Customer Insights</a></li>
                            <li><a href="plugin-performance.php">Plugin Performance</a></li>
                            <li><a href="market-analysis.php">Market Analysis</a></li>
                        </ul>
                    </div>
                </li>
                <?php endif; ?>

                <?php if (hasPermission('manage_api')): ?>
                <li>
                    <a href="#api" data-bs-toggle="collapse">
                        <i class="mdi mdi-api"></i>
                        <span> API Management </span>
                        <span class="menu-arrow"></span>
                    </a>
                    <div class="collapse" id="api">
                        <ul class="nav-second-level">
                            <li><a href="api-keys.php">API Keys</a></li>
                            <li><a href="api-logs.php">API Logs</a></li>
                            <li><a href="api-documentation.php">Documentation</a></li>
                            <li><a href="webhooks.php">Webhooks</a></li>
                            <li><a href="sandbox.php">Sandbox</a></li>
                        </ul>
                    </div>
                </li>
                <?php endif; ?>

                <li class="menu-title mt-2">System</li>

                <?php if (hasPermission('manage_settings')): ?>
                <li>
                    <a href="#settings" data-bs-toggle="collapse">
                        <i class="mdi mdi-cog-outline"></i>
                        <span> System Settings </span>
                        <span class="menu-arrow"></span>
                    </a>
                    <div class="collapse" id="settings">
                        <ul class="nav-second-level">
                            <li><a href="general-settings.php">General Settings</a></li>
                            <li><a href="payment-settings.php">Payment Settings</a></li>
                            <li><a href="email-settings.php">Email Settings</a></li>
                            <li><a href="security-settings.php">Security Settings</a></li>
                            <li><a href="exchange-rates.php">Exchange Rates</a></li>
                        </ul>
                    </div>
                </li>
                <?php endif; ?>

                <?php endif; ?>

                <li class="menu-title mt-2">Account</li>

                <li>
                    <a href="#account" data-bs-toggle="collapse">
                        <i class="mdi mdi-account-circle-outline"></i>
                        <span> My Profile </span>
                        <span class="menu-arrow"></span>
                    </a>
                    <div class="collapse" id="account">
                        <ul class="nav-second-level">
                            <li><a href="profile.php">Profile Settings</a></li>
                            <li><a href="change-password.php">Change Password</a></li>
                            <li><a href="notifications-settings.php">Notifications</a></li>
                            <?php if ($user_role === 'Customer'): ?>
                            <li><a href="billing-info.php">Billing Information</a></li>
                            <li><a href="api-access.php">API Access</a></li>
                            <?php endif; ?>
                        </ul>
                    </div>
                </li>

            </ul>

        </div>
        <!-- End Sidebar -->

        <div class="clearfix"></div>

    </div>
    <!-- Sidebar -left -->

</div>
<!-- Left Sidebar End -->

<style>
/* Custom styles for MoMo Platform */
.user-box {
    border-bottom: 2px solid <?php 
    if ($user_role === 'Customer') echo '#28a745';
    elseif ($user_role === 'Administrator') echo '#dc3545';
    elseif ($user_role === 'Support Agent') echo '#17a2b8';
    elseif ($user_role === 'Sales Manager') echo '#ffc107';
    elseif ($user_role === 'Developer') echo '#6f42c1';
    else echo '#6c757d';
    ?>;
}

.badge {
    font-size: 0.65rem;
    padding: 0.25em 0.5em;
}

.nav-second-level .badge {
    position: absolute;
    right: 10px;
    top: 50%;
    transform: translateY(-50%);
}

/* Badge animations */
.badge {
    animation: pulse 2s infinite;
}

@keyframes pulse {
    0% { transform: scale(1); }
    50% { transform: scale(1.05); }
    100% { transform: scale(1); }
}
</style>