<?php
// Start output buffering to catch any errors
ob_start();

session_start();

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: auth-login.php');
    exit();
}

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

// Check if database connection exists
if (!isset($conn)) {
    die('Database connection not available');
}

// Get user information
$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['role_name'] ?? 'Customer';

// Simple functions for orders page
function getUserOrdersSimple($conn, $user_id, $status_filter = '', $page = 1, $per_page = 10) {
    $offset = ($page - 1) * $per_page;
    
    // Base query
    $where_clause = "WHERE o.user_id = ?";
    $params = [$user_id];
    $types = "i";
    
    // Add status filter if provided
    if (!empty($status_filter)) {
        $where_clause .= " AND o.order_status = ?";
        $params[] = strtoupper($status_filter);
        $types .= "s";
    }
    
    $query = "
        SELECT 
            o.order_id,
            o.order_number,
            o.total_amount,
            o.currency,
            o.payment_method,
            o.payment_status,
            o.order_status,
            o.created_at,
            o.updated_at,
            o.completed_at
        FROM orders o 
        {$where_clause}
        ORDER BY o.created_at DESC 
        LIMIT ? OFFSET ?
    ";
    
    $params[] = $per_page;
    $params[] = $offset;
    $types .= "ii";
    
    try {
        $stmt = $conn->prepare($query);
        if (!$stmt) {
            error_log("Prepare failed: " . $conn->error);
            return [];
        }
        
        $stmt->bind_param($types, ...$params);
        $stmt->execute();
        $result = $stmt->get_result();
        
        $orders = [];
        while ($row = $result->fetch_assoc()) {
            // Get order items
            $items_query = "
                SELECT 
                    oi.quantity,
                    oi.unit_price,
                    oi.total_price,
                    COALESCE(p.name, 'Product') as product_name,
                    COALESCE(p.description, 'No description') as description,
                    COALESCE(p.logo_url, 'assets/images/plugin-default.png') as image,
                    COALESCE(pc.name, 'Plugin') as category
                FROM order_items oi
                LEFT JOIN products p ON oi.product_id = p.product_id
                LEFT JOIN product_categories pc ON p.category_id = pc.category_id
                WHERE oi.order_id = ?
            ";
            
            $items_stmt = $conn->prepare($items_query);
            if ($items_stmt) {
                $items_stmt->bind_param("i", $row['order_id']);
                $items_stmt->execute();
                $items_result = $items_stmt->get_result();
                
                $items = [];
                while ($item = $items_result->fetch_assoc()) {
                    $items[] = $item;
                }
                $items_stmt->close();
                $row['items'] = $items;
            } else {
                $row['items'] = [];
            }
            
            // Get licenses if order is completed
            if ($row['order_status'] === 'COMPLETED') {
                $license_query = "
                    SELECT 
                        l.license_key,
                        l.sites_allowed,
                        l.sites_used,
                        l.expires_at,
                        COALESCE(p.name, 'Product') as product_name
                    FROM licenses l
                    JOIN order_items oi ON l.license_id = oi.license_id
                    LEFT JOIN products p ON oi.product_id = p.product_id
                    WHERE oi.order_id = ?
                ";
                
                $license_stmt = $conn->prepare($license_query);
                if ($license_stmt) {
                    $license_stmt->bind_param("i", $row['order_id']);
                    $license_stmt->execute();
                    $license_result = $license_stmt->get_result();
                    
                    $licenses = [];
                    while ($license = $license_result->fetch_assoc()) {
                        $licenses[] = $license;
                    }
                    $license_stmt->close();
                    $row['licenses'] = $licenses;
                } else {
                    $row['licenses'] = [];
                }
            } else {
                $row['licenses'] = [];
            }
            
            $orders[] = $row;
        }
        
        $stmt->close();
        return $orders;
        
    } catch (Exception $e) {
        error_log("Error fetching orders: " . $e->getMessage());
        return [];
    }
}

function getOrdersCount($conn, $user_id, $status_filter = '') {
    $where_clause = "WHERE user_id = ?";
    $params = [$user_id];
    $types = "i";
    
    if (!empty($status_filter)) {
        $where_clause .= " AND order_status = ?";
        $params[] = strtoupper($status_filter);
        $types .= "s";
    }
    
    $query = "SELECT COUNT(*) as count FROM orders {$where_clause}";
    
    try {
        $stmt = $conn->prepare($query);
        if (!$stmt) {
            return 0;
        }
        
        $stmt->bind_param($types, ...$params);
        $stmt->execute();
        $result = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        return $result['count'] ?? 0;
    } catch (Exception $e) {
        error_log("Error counting orders: " . $e->getMessage());
        return 0;
    }
}

function getOrderStats($conn, $user_id) {
    try {
        // Get basic stats
        $query = "
            SELECT 
                COUNT(*) as total_orders,
                COALESCE(SUM(total_amount), 0) as total_spent,
                COUNT(CASE WHEN order_status = 'PENDING' THEN 1 END) as pending_orders,
                COUNT(CASE WHEN order_status = 'COMPLETED' THEN 1 END) as completed_orders
            FROM orders 
            WHERE user_id = ?
        ";
        
        $stmt = $conn->prepare($query);
        if (!$stmt) {
            return [
                'total_orders' => 0,
                'total_spent' => 0,
                'pending_orders' => 0,
                'completed_orders' => 0,
                'active_licenses' => 0
            ];
        }
        
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $result = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        
        // Get active licenses
        $license_query = "SELECT COUNT(*) as count FROM licenses WHERE user_id = ? AND status = 'ACTIVE'";
        $license_stmt = $conn->prepare($license_query);
        $active_licenses = 0;
        if ($license_stmt) {
            $license_stmt->bind_param("i", $user_id);
            $license_stmt->execute();
            $license_result = $license_stmt->get_result()->fetch_assoc();
            $license_stmt->close();
            $active_licenses = $license_result['count'] ?? 0;
        }
        
        return [
            'total_orders' => $result['total_orders'] ?? 0,
            'total_spent' => $result['total_spent'] ?? 0,
            'pending_orders' => $result['pending_orders'] ?? 0,
            'completed_orders' => $result['completed_orders'] ?? 0,
            'active_licenses' => $active_licenses
        ];
        
    } catch (Exception $e) {
        error_log("Error fetching order stats: " . $e->getMessage());
        return [
            'total_orders' => 0,
            'total_spent' => 0,
            'pending_orders' => 0,
            'completed_orders' => 0,
            'active_licenses' => 0
        ];
    }
}

// Handle filters and pagination
$status_filter = $_GET['status'] ?? '';
$page = max(1, intval($_GET['page'] ?? 1));
$per_page = 10;

// Get data
$orders = getUserOrdersSimple($conn, $user_id, $status_filter, $page, $per_page);
$total_orders = getOrdersCount($conn, $user_id, $status_filter);
$order_stats = getOrderStats($conn, $user_id);
$total_pages = ceil($total_orders / $per_page);

// Set title for the page
$title = "My Orders";

// End output buffering and check for errors
$buffer = ob_get_clean();
if (!empty($buffer)) {
    error_log("Output buffer content: " . $buffer);
}

// Start the page output
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title><?php echo $title; ?> | ConnectPay Platform</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta content="ConnectPay Plugin Platform" name="description" />
    <meta content="ConnectPay" name="author" />
    
    <!-- App favicon -->
    <link rel="shortcut icon" href="assets/images/favicon.ico">
    
    <!-- Bootstrap CSS -->
    <link href="assets/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
    
    <!-- Icons CSS -->
    <link href="assets/css/icons.min.css" rel="stylesheet" type="text/css" />
    
    <!-- App CSS -->
    <link href="assets/css/app.min.css" rel="stylesheet" type="text/css" />

<style>
    .orders-container {
        background: #f8fafc;
        min-height: 100vh;
        padding: 2rem 0;
    }
    
    .order-card {
        background: white;
        border: 1px solid #e2e8f0;
        border-radius: 12px;
        margin-bottom: 1.5rem;
        overflow: hidden;
        transition: all 0.2s ease;
    }
    
    .order-card:hover {
        border-color: #cbd5e1;
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    }
    
    .order-header {
        background: #f1f5f9;
        padding: 1.5rem;
        border-bottom: 1px solid #e2e8f0;
    }
    
    .order-number {
        font-size: 1.125rem;
        font-weight: 600;
        color: #1e293b;
        margin: 0;
    }
    
    .order-date {
        color: #64748b;
        font-size: 0.875rem;
        margin: 0.25rem 0 0 0;
    }
    
    .order-status {
        display: inline-flex;
        align-items: center;
        padding: 0.5rem 1rem;
        border-radius: 20px;
        font-size: 0.75rem;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.025em;
    }
    
    .status-completed {
        background: #dcfce7;
        color: #166534;
    }
    
    .status-pending {
        background: #fef3c7;
        color: #92400e;
    }
    
    .status-processing {
        background: #dbeafe;
        color: #1e40af;
    }
    
    .status-cancelled {
        background: #fee2e2;
        color: #dc2626;
    }
    
    .order-content {
        padding: 1.5rem;
    }
    
    .order-item {
        display: flex;
        align-items: center;
        padding: 1rem 0;
        border-bottom: 1px solid #f1f5f9;
        gap: 1rem;
    }
    
    .order-item:last-child {
        border-bottom: none;
        padding-bottom: 0;
    }
    
    .item-image {
        width: 48px;
        height: 48px;
        border-radius: 8px;
        background: #f1f5f9;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.5rem;
        color: #64748b;
    }
    
    .item-details {
        flex: 1;
    }
    
    .item-name {
        font-weight: 600;
        color: #1e293b;
        margin: 0 0 0.25rem 0;
    }
    
    .item-meta {
        color: #64748b;
        font-size: 0.875rem;
        margin: 0;
    }
    
    .item-price {
        font-weight: 600;
        color: #1e293b;
        font-size: 1.125rem;
    }
    
    .order-total {
        background: #f8fafc;
        border-radius: 8px;
        padding: 1rem;
        margin-top: 1rem;
        text-align: right;
    }
    
    .total-amount {
        font-size: 1.25rem;
        font-weight: 700;
        color: #1e293b;
    }
    
    .btn-primary {
        background: #3b82f6;
        border: 1px solid #3b82f6;
        color: white;
        padding: 0.625rem 1.25rem;
        border-radius: 8px;
        font-size: 0.875rem;
        font-weight: 500;
        text-decoration: none;
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
        transition: all 0.2s ease;
    }
    
    .btn-primary:hover {
        background: #2563eb;
        color: white;
        transform: translateY(-1px);
    }
    
    .btn-outline {
        background: white;
        border: 1px solid #d1d5db;
        color: #374151;
        padding: 0.625rem 1.25rem;
        border-radius: 8px;
        font-size: 0.875rem;
        font-weight: 500;
        text-decoration: none;
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
        transition: all 0.2s ease;
        margin-right: 0.75rem;
    }
    
    .btn-outline:hover {
        background: #f9fafb;
        color: #374151;
        border-color: #9ca3af;
    }
    
    .stats-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 1rem;
        margin-bottom: 2rem;
    }
    
    .stat-card {
        background: white;
        border: 1px solid #e2e8f0;
        border-radius: 12px;
        padding: 1.5rem;
        text-align: center;
    }
    
    .stat-number {
        font-size: 2rem;
        font-weight: 700;
        color: #1e293b;
        display: block;
        margin-bottom: 0.5rem;
    }
    
    .stat-label {
        color: #64748b;
        font-size: 0.875rem;
        margin: 0;
    }
    
    .filters-section {
        background: white;
        border: 1px solid #e2e8f0;
        border-radius: 12px;
        padding: 1.5rem;
        margin-bottom: 2rem;
    }
    
    .filter-select {
        background: white;
        border: 1px solid #d1d5db;
        border-radius: 8px;
        padding: 0.625rem 1rem;
        font-size: 0.875rem;
        min-width: 150px;
        margin-right: 1rem;
    }
    
    .filter-select:focus {
        outline: none;
        border-color: #3b82f6;
        box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
    }
    
    .empty-state {
        background: white;
        border: 1px solid #e2e8f0;
        border-radius: 12px;
        padding: 3rem;
        text-align: center;
    }
    
    .empty-icon {
        font-size: 4rem;
        color: #cbd5e1;
        margin-bottom: 1rem;
    }
    
    .empty-title {
        font-size: 1.5rem;
        font-weight: 600;
        color: #374151;
        margin-bottom: 0.5rem;
    }
    
    .empty-text {
        color: #64748b;
        margin-bottom: 2rem;
    }
    
    .license-info {
        background: #f0f9ff;
        border: 1px solid #bae6fd;
        border-radius: 8px;
        padding: 1rem;
        margin-top: 1rem;
        font-size: 0.875rem;
    }
    
    .license-key {
        font-family: 'Courier New', monospace;
        background: white;
        border: 1px solid #cbd5e1;
        border-radius: 4px;
        padding: 0.5rem;
        margin: 0.5rem 0;
        font-size: 0.75rem;
        word-break: break-all;
        cursor: pointer;
        transition: background 0.2s ease;
    }
    
    .license-key:hover {
        background: #f8fafc;
    }
    
    .order-actions {
        display: flex;
        flex-wrap: wrap;
        gap: 0.75rem;
        margin-top: 1rem;
    }
</style>
</head>

<body class="loading">

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

    <!-- Topbar Start -->
    <?php 
    $pagetitle = "My Orders"; 
    if (file_exists('partials/menu.php')) {
        include 'partials/menu.php'; 
    } else {
        // Simple fallback header
        echo '<div class="navbar-custom"><div class="container-fluid"><h4 class="page-title">My Orders</h4></div></div>';
    }
    ?>
    <!-- end Topbar -->

    <div class="content-page">
        <div class="content">
            <div class="container-fluid orders-container">

                <!-- Page Title -->
                <div class="row">
                    <div class="col-12">
                        <div class="page-title-box">
                            <div class="page-title-right">
                                <ol class="breadcrumb m-0">
                                    <li class="breadcrumb-item"><a href="<?php echo ($user_role === 'Customer') ? 'dashboard.php' : 'index.php'; ?>">Dashboard</a></li>
                                    <li class="breadcrumb-item">Plugin Store</li>
                                    <li class="breadcrumb-item active">My Orders</li>
                                </ol>
                            </div>
                            <h4 class="page-title">My Orders</h4>
                        </div>
                    </div>
                </div>

                <!-- Debug Info (remove in production) -->
                <?php if (isset($_GET['debug'])): ?>
                <div class="row">
                    <div class="col-12">
                        <div class="alert alert-info">
                            <strong>Debug Info:</strong><br>
                            User ID: <?php echo $user_id; ?><br>
                            User Role: <?php echo $user_role; ?><br>
                            Total Orders: <?php echo count($orders); ?><br>
                            Database Connection: <?php echo isset($conn) ? 'OK' : 'Failed'; ?>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Order Statistics -->
                <div class="stats-grid">
                    <div class="stat-card">
                        <span class="stat-number"><?php echo $order_stats['total_orders']; ?></span>
                        <p class="stat-label">Total Orders</p>
                    </div>
                    
                    <div class="stat-card">
                        <span class="stat-number">$<?php echo number_format($order_stats['total_spent'], 0); ?></span>
                        <p class="stat-label">Total Spent</p>
                    </div>
                    
                    <div class="stat-card">
                        <span class="stat-number"><?php echo $order_stats['active_licenses']; ?></span>
                        <p class="stat-label">Active Licenses</p>
                    </div>
                    
                    <div class="stat-card">
                        <span class="stat-number"><?php echo $order_stats['pending_orders']; ?></span>
                        <p class="stat-label">Pending Orders</p>
                    </div>
                </div>

                <!-- Filters -->
                <div class="filters-section">
                    <form method="GET" action="" class="d-flex align-items-center">
                        <label for="status" style="margin-right: 1rem; font-weight: 500;">Filter by Status:</label>
                        <select name="status" id="status" class="filter-select" onchange="this.form.submit()">
                            <option value="">All Orders</option>
                            <option value="completed" <?php echo ($status_filter === 'completed') ? 'selected' : ''; ?>>Completed</option>
                            <option value="pending" <?php echo ($status_filter === 'pending') ? 'selected' : ''; ?>>Pending</option>
                            <option value="processing" <?php echo ($status_filter === 'processing') ? 'selected' : ''; ?>>Processing</option>
                            <option value="cancelled" <?php echo ($status_filter === 'cancelled') ? 'selected' : ''; ?>>Cancelled</option>
                        </select>
                        <?php if ($status_filter): ?>
                        <a href="my-orders.php" class="btn-outline">Clear Filter</a>
                        <?php endif; ?>
                    </form>
                </div>

                <!-- Orders List -->
                <div class="row">
                    <div class="col-12">
                        <?php if (!empty($orders)): ?>
                            <?php foreach ($orders as $order): ?>
                            <div class="order-card">
                                <div class="order-header">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div>
                                            <h5 class="order-number">Order #<?php echo htmlspecialchars($order['order_number']); ?></h5>
                                            <p class="order-date">Placed on <?php echo date('F j, Y \a\t g:i A', strtotime($order['created_at'])); ?></p>
                                        </div>
                                        <div class="order-status status-<?php echo strtolower($order['order_status']); ?>">
                                            <?php echo ucfirst(strtolower($order['order_status'])); ?>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="order-content">
                                    <!-- Order Items -->
                                    <?php if (!empty($order['items'])): ?>
                                        <?php foreach ($order['items'] as $item): ?>
                                        <div class="order-item">
                                            <div class="item-image">🔌</div>
                                            <div class="item-details">
                                                <h6 class="item-name"><?php echo htmlspecialchars($item['product_name']); ?></h6>
                                                <p class="item-meta">
                                                    <?php echo htmlspecialchars($item['category']); ?>
                                                    <?php if ($item['quantity'] > 1): ?>
                                                    • Quantity: <?php echo $item['quantity']; ?>
                                                    <?php endif; ?>
                                                </p>
                                            </div>
                                            <div class="item-price">
                                                $<?php echo number_format($item['total_price'], 2); ?>
                                            </div>
                                        </div>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <div class="order-item">
                                            <div class="item-image">🔌</div>
                                            <div class="item-details">
                                                <h6 class="item-name">Plugin Purchase</h6>
                                                <p class="item-meta">Payment Gateway Plugin</p>
                                            </div>
                                            <div class="item-price">
                                                $<?php echo number_format($order['total_amount'], 2); ?>
                                            </div>
                                        </div>
                                    <?php endif; ?>

                                    <!-- Order Total -->
                                    <div class="order-total">
                                        <div class="total-amount">
                                            Total: $<?php echo number_format($order['total_amount'], 2); ?> <?php echo $order['currency']; ?>
                                        </div>
                                        <div style="font-size: 0.875rem; color: #64748b; margin-top: 0.25rem;">
                                            Payment via <?php echo ucfirst(str_replace('_', ' ', strtolower($order['payment_method']))); ?>
                                        </div>
                                    </div>

                                    <!-- License Information -->
                                    <?php if ($order['order_status'] === 'COMPLETED' && !empty($order['licenses'])): ?>
                                    <div class="license-info">
                                        <strong>🔑 License Information:</strong>
                                        <?php foreach ($order['licenses'] as $license): ?>
                                        <div style="margin-top: 0.75rem;">
                                            <div><strong><?php echo htmlspecialchars($license['product_name']); ?></strong></div>
                                            <div class="license-key" onclick="copyToClipboard(this)" title="Click to copy">
                                                <?php echo htmlspecialchars($license['license_key']); ?>
                                            </div>
                                            <div style="font-size: 0.75rem; color: #64748b;">
                                                Sites: <?php echo $license['sites_used']; ?>/<?php echo $license['sites_allowed']; ?>
                                                <?php if ($license['expires_at']): ?>
                                                • Expires: <?php echo date('M j, Y', strtotime($license['expires_at'])); ?>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        <?php endforeach; ?>
                                    </div>
                                    <?php endif; ?>

                                    <!-- Order Actions -->
                                    <div class="order-actions">
                                        <a href="#" class="btn-outline">📄 View Details</a>
                                        
                                        <?php if ($order['order_status'] === 'COMPLETED'): ?>
                                        <a href="#" class="btn-outline">📥 Download</a>
                                        <a href="#" class="btn-outline">🧾 Receipt</a>
                                        <?php endif; ?>
                                        
                                        <?php if ($order['order_status'] === 'PENDING'): ?>
                                        <a href="#" class="btn-primary">💳 Complete Payment</a>
                                        <?php endif; ?>
                                        
                                        <a href="#" class="btn-outline">💬 Support</a>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>

                        <?php else: ?>
                            <!-- Empty State -->
                            <div class="empty-state">
                                <div class="empty-icon">📦</div>
                                <h3 class="empty-title">
                                    <?php if ($status_filter): ?>
                                    No <?php echo ucfirst($status_filter); ?> Orders
                                    <?php else: ?>
                                    No Orders Yet
                                    <?php endif; ?>
                                </h3>
                                <p class="empty-text">
                                    <?php if ($status_filter): ?>
                                    You don't have any <?php echo strtolower($status_filter); ?> orders.
                                    <?php else: ?>
                                    You haven't placed any orders yet. Browse our plugin store to get started.
                                    <?php endif; ?>
                                </p>
                                <div>
                                    <?php if ($status_filter): ?>
                                    <a href="my-orders.php" class="btn-primary">View All Orders</a>
                                    <?php else: ?>
                                    <a href="browse-plugins.php" class="btn-primary">Browse Plugin Store</a>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

            </div>
        </div>

        <!-- Footer -->
        <?php 
        if (file_exists('partials/footer.php')) {
            include 'partials/footer.php'; 
        }
        ?>
    </div>
</div>

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

<script>
console.log('📦 My Orders page loaded successfully');

// Copy license key to clipboard
function copyToClipboard(element) {
    const text = element.textContent.trim();
    
    if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(text).then(function() {
            showCopySuccess(element);
        }).catch(function(err) {
            console.error('Failed to copy: ', err);
        });
    }
}

// Show copy success notification
function showCopySuccess(element) {
    const originalText = element.innerHTML;
    element.innerHTML = '✅ Copied!';
    element.style.background = '#dcfce7';
    element.style.color = '#166534';
    
    setTimeout(() => {
        element.innerHTML = originalText;
        element.style.background = 'white';
        element.style.color = '#1e293b';
    }, 2000);
}

// Add hover effects to order cards
document.querySelectorAll('.order-card').forEach(card => {
    card.addEventListener('mouseenter', function() {
        this.style.transform = 'translateY(-2px)';
    });
    
    card.addEventListener('mouseleave', function() {
        this.style.transform = 'translateY(0)';
    });
});

// Add click handlers for action buttons
document.querySelectorAll('.btn-primary, .btn-outline').forEach(btn => {
    btn.addEventListener('click', function(e) {
        // Only prevent default for demo links (href="#")
        if (this.getAttribute('href') === '#') {
            e.preventDefault();
            
            const action = this.textContent.trim();
            console.log('Action clicked:', action);
            
            // Show simple alert for demo
            if (action.includes('Complete Payment')) {
                alert('Redirecting to payment...');
            } else if (action.includes('Download')) {
                alert('Download will start shortly...');
            } else if (action.includes('Support')) {
                alert('Opening support ticket...');
            } else if (action.includes('Receipt')) {
                alert('Generating receipt...');
            } else if (action.includes('Details')) {
                alert('Loading order details...');
            }
        }
    });
});

// Initialize page
document.addEventListener('DOMContentLoaded', function() {
    console.log('📊 Order Statistics:', {
        total_orders: <?php echo $order_stats['total_orders']; ?>,
        total_spent: <?php echo $order_stats['total_spent']; ?>,
        pending_orders: <?php echo $order_stats['pending_orders']; ?>,
        active_licenses: <?php echo $order_stats['active_licenses']; ?>
    });
    
    // Add tooltips to license keys
    document.querySelectorAll('.license-key').forEach(key => {
        key.title = 'Click to copy license key';
        key.style.cursor = 'pointer';
    });
    
    // Remove loading class
    document.body.classList.remove('loading');
});
</script>

</body>
</html><?php
session_start();

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: auth-login.php');
    exit();
}

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

// Get user information
$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['role_name'] ?? 'Customer';

// Simple functions for orders page
/*function getUserOrdersSimple($conn, $user_id, $status_filter = '', $page = 1, $per_page = 10) {
    $offset = ($page - 1) * $per_page;
    
    // Base query
    $where_clause = "WHERE o.user_id = ?";
    $params = [$user_id];
    $types = "i";
    
    // Add status filter if provided
    if (!empty($status_filter)) {
        $where_clause .= " AND o.order_status = ?";
        $params[] = strtoupper($status_filter);
        $types .= "s";
    }
    
    $query = "
        SELECT 
            o.order_id,
            o.order_number,
            o.total_amount,
            o.currency,
            o.payment_method,
            o.payment_status,
            o.order_status,
            o.created_at,
            o.updated_at,
            o.completed_at
        FROM orders o 
        {$where_clause}
        ORDER BY o.created_at DESC 
        LIMIT ? OFFSET ?
    ";
    
    $params[] = $per_page;
    $params[] = $offset;
    $types .= "ii";
    
    try {
        $stmt = $conn->prepare($query);
        $stmt->bind_param($types, ...$params);
        $stmt->execute();
        $result = $stmt->get_result();
        
        $orders = [];
        while ($row = $result->fetch_assoc()) {
            // Get order items
            $items_query = "
                SELECT 
                    oi.quantity,
                    oi.unit_price,
                    oi.total_price,
                    COALESCE(p.name, 'Product') as product_name,
                    COALESCE(p.description, 'No description') as description,
                    COALESCE(p.logo_url, 'assets/images/plugin-default.png') as image,
                    COALESCE(pc.name, 'Plugin') as category
                FROM order_items oi
                LEFT JOIN products p ON oi.product_id = p.product_id
                LEFT JOIN product_categories pc ON p.category_id = pc.category_id
                WHERE oi.order_id = ?
            ";
            
            $items_stmt = $conn->prepare($items_query);
            $items_stmt->bind_param("i", $row['order_id']);
            $items_stmt->execute();
            $items_result = $items_stmt->get_result();
            
            $items = [];
            while ($item = $items_result->fetch_assoc()) {
                $items[] = $item;
            }
            $items_stmt->close();
            
            $row['items'] = $items;
            
            // Get licenses if order is completed
            if ($row['order_status'] === 'COMPLETED') {
                $license_query = "
                    SELECT 
                        l.license_key,
                        l.sites_allowed,
                        l.sites_used,
                        l.expires_at,
                        COALESCE(p.name, 'Product') as product_name
                    FROM licenses l
                    JOIN order_items oi ON l.license_id = oi.license_id
                    LEFT JOIN products p ON oi.product_id = p.product_id
                    WHERE oi.order_id = ?
                ";
                
                $license_stmt = $conn->prepare($license_query);
                $license_stmt->bind_param("i", $row['order_id']);
                $license_stmt->execute();
                $license_result = $license_stmt->get_result();
                
                $licenses = [];
                while ($license = $license_result->fetch_assoc()) {
                    $licenses[] = $license;
                }
                $license_stmt->close();
                
                $row['licenses'] = $licenses;
            } else {
                $row['licenses'] = [];
            }
            
            $orders[] = $row;
        }
        
        $stmt->close();
        return $orders;
        
    } catch (Exception $e) {
        error_log("Error fetching orders: " . $e->getMessage());
        return [];
    }
}*/

/*function getOrdersCount($conn, $user_id, $status_filter = '') {
    $where_clause = "WHERE user_id = ?";
    $params = [$user_id];
    $types = "i";
    
    if (!empty($status_filter)) {
        $where_clause .= " AND order_status = ?";
        $params[] = strtoupper($status_filter);
        $types .= "s";
    }
    
    $query = "SELECT COUNT(*) as count FROM orders {$where_clause}";
    
    try {
        $stmt = $conn->prepare($query);
        $stmt->bind_param($types, ...$params);
        $stmt->execute();
        $result = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        return $result['count'] ?? 0;
    } catch (Exception $e) {
        error_log("Error counting orders: " . $e->getMessage());
        return 0;
    }
}*/

/*function getOrderStats($conn, $user_id) {
    try {
        // Get basic stats
        $query = "
            SELECT 
                COUNT(*) as total_orders,
                COALESCE(SUM(total_amount), 0) as total_spent,
                COUNT(CASE WHEN order_status = 'PENDING' THEN 1 END) as pending_orders,
                COUNT(CASE WHEN order_status = 'COMPLETED' THEN 1 END) as completed_orders
            FROM orders 
            WHERE user_id = ?
        ";
        
        $stmt = $conn->prepare($query);
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $result = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        
        // Get active licenses
        $license_query = "SELECT COUNT(*) as count FROM licenses WHERE user_id = ? AND status = 'ACTIVE'";
        $license_stmt = $conn->prepare($license_query);
        $license_stmt->bind_param("i", $user_id);
        $license_stmt->execute();
        $license_result = $license_stmt->get_result()->fetch_assoc();
        $license_stmt->close();
        
        return [
            'total_orders' => $result['total_orders'] ?? 0,
            'total_spent' => $result['total_spent'] ?? 0,
            'pending_orders' => $result['pending_orders'] ?? 0,
            'completed_orders' => $result['completed_orders'] ?? 0,
            'active_licenses' => $license_result['count'] ?? 0
        ];
        
    } catch (Exception $e) {
        error_log("Error fetching order stats: " . $e->getMessage());
        return [
            'total_orders' => 0,
            'total_spent' => 0,
            'pending_orders' => 0,
            'completed_orders' => 0,
            'active_licenses' => 0
        ];
    }
} */

// Handle filters and pagination
$status_filter = $_GET['status'] ?? '';
$page = max(1, intval($_GET['page'] ?? 1));
$per_page = 10;

// Get data
$orders = getUserOrdersSimple($conn, $user_id, $status_filter, $page, $per_page);
$total_orders = getOrdersCount($conn, $user_id, $status_filter);
$order_stats = getOrderStats($conn, $user_id);
$total_pages = ceil($total_orders / $per_page);

$title = "My Orders";
include 'partials/title-meta.php';
?>

<?php include 'partials/head-css.php'; ?>

<style>
    .orders-container {
        background: #f8fafc;
        min-height: 100vh;
        padding: 2rem 0;
    }
    
    .order-card {
        background: white;
        border: 1px solid #e2e8f0;
        border-radius: 12px;
        margin-bottom: 1.5rem;
        overflow: hidden;
        transition: all 0.2s ease;
    }
    
    .order-card:hover {
        border-color: #cbd5e1;
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    }
    
    .order-header {
        background: #f1f5f9;
        padding: 1.5rem;
        border-bottom: 1px solid #e2e8f0;
    }
    
    .order-number {
        font-size: 1.125rem;
        font-weight: 600;
        color: #1e293b;
        margin: 0;
    }
    
    .order-date {
        color: #64748b;
        font-size: 0.875rem;
        margin: 0.25rem 0 0 0;
    }
    
    .order-status {
        display: inline-flex;
        align-items: center;
        padding: 0.5rem 1rem;
        border-radius: 20px;
        font-size: 0.75rem;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.025em;
    }
    
    .status-completed {
        background: #dcfce7;
        color: #166534;
    }
    
    .status-pending {
        background: #fef3c7;
        color: #92400e;
    }
    
    .status-processing {
        background: #dbeafe;
        color: #1e40af;
    }
    
    .status-cancelled {
        background: #fee2e2;
        color: #dc2626;
    }
    
    .order-content {
        padding: 1.5rem;
    }
    
    .order-item {
        display: flex;
        align-items: center;
        padding: 1rem 0;
        border-bottom: 1px solid #f1f5f9;
        gap: 1rem;
    }
    
    .order-item:last-child {
        border-bottom: none;
        padding-bottom: 0;
    }
    
    .item-image {
        width: 48px;
        height: 48px;
        border-radius: 8px;
        background: #f1f5f9;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.5rem;
        color: #64748b;
    }
    
    .item-details {
        flex: 1;
    }
    
    .item-name {
        font-weight: 600;
        color: #1e293b;
        margin: 0 0 0.25rem 0;
    }
    
    .item-meta {
        color: #64748b;
        font-size: 0.875rem;
        margin: 0;
    }
    
    .item-price {
        font-weight: 600;
        color: #1e293b;
        font-size: 1.125rem;
    }
    
    .order-total {
        background: #f8fafc;
        border-radius: 8px;
        padding: 1rem;
        margin-top: 1rem;
        text-align: right;
    }
    
    .total-amount {
        font-size: 1.25rem;
        font-weight: 700;
        color: #1e293b;
    }
    
    .btn-primary {
        background: #3b82f6;
        border: 1px solid #3b82f6;
        color: white;
        padding: 0.625rem 1.25rem;
        border-radius: 8px;
        font-size: 0.875rem;
        font-weight: 500;
        text-decoration: none;
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
        transition: all 0.2s ease;
    }
    
    .btn-primary:hover {
        background: #2563eb;
        color: white;
        transform: translateY(-1px);
    }
    
    .btn-outline {
        background: white;
        border: 1px solid #d1d5db;
        color: #374151;
        padding: 0.625rem 1.25rem;
        border-radius: 8px;
        font-size: 0.875rem;
        font-weight: 500;
        text-decoration: none;
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
        transition: all 0.2s ease;
        margin-right: 0.75rem;
    }
    
    .btn-outline:hover {
        background: #f9fafb;
        color: #374151;
        border-color: #9ca3af;
    }
    
    .stats-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 1rem;
        margin-bottom: 2rem;
    }
    
    .stat-card {
        background: white;
        border: 1px solid #e2e8f0;
        border-radius: 12px;
        padding: 1.5rem;
        text-align: center;
    }
    
    .stat-number {
        font-size: 2rem;
        font-weight: 700;
        color: #1e293b;
        display: block;
        margin-bottom: 0.5rem;
    }
    
    .stat-label {
        color: #64748b;
        font-size: 0.875rem;
        margin: 0;
    }
    
    .filters-section {
        background: white;
        border: 1px solid #e2e8f0;
        border-radius: 12px;
        padding: 1.5rem;
        margin-bottom: 2rem;
    }
    
    .filter-select {
        background: white;
        border: 1px solid #d1d5db;
        border-radius: 8px;
        padding: 0.625rem 1rem;
        font-size: 0.875rem;
        min-width: 150px;
        margin-right: 1rem;
    }
    
    .filter-select:focus {
        outline: none;
        border-color: #3b82f6;
        box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
    }
    
    .empty-state {
        background: white;
        border: 1px solid #e2e8f0;
        border-radius: 12px;
        padding: 3rem;
        text-align: center;
    }
    
    .empty-icon {
        font-size: 4rem;
        color: #cbd5e1;
        margin-bottom: 1rem;
    }
    
    .empty-title {
        font-size: 1.5rem;
        font-weight: 600;
        color: #374151;
        margin-bottom: 0.5rem;
    }
    
    .empty-text {
        color: #64748b;
        margin-bottom: 2rem;
    }
    
    .pagination {
        display: flex;
        justify-content: center;
        gap: 0.5rem;
        margin-top: 2rem;
    }
    
    .pagination-btn {
        background: white;
        border: 1px solid #d1d5db;
        color: #374151;
        padding: 0.5rem 1rem;
        border-radius: 8px;
        text-decoration: none;
        font-size: 0.875rem;
        transition: all 0.2s ease;
    }
    
    .pagination-btn:hover:not(.disabled) {
        background: #f9fafb;
        color: #374151;
    }
    
    .pagination-btn.active {
        background: #3b82f6;
        border-color: #3b82f6;
        color: white;
    }
    
    .pagination-btn.disabled {
        opacity: 0.5;
        cursor: not-allowed;
    }
    
    .license-info {
        background: #f0f9ff;
        border: 1px solid #bae6fd;
        border-radius: 8px;
        padding: 1rem;
        margin-top: 1rem;
        font-size: 0.875rem;
    }
    
    .license-key {
        font-family: 'Courier New', monospace;
        background: white;
        border: 1px solid #cbd5e1;
        border-radius: 4px;
        padding: 0.5rem;
        margin: 0.5rem 0;
        font-size: 0.75rem;
        word-break: break-all;
        cursor: pointer;
        transition: background 0.2s ease;
    }
    
    .license-key:hover {
        background: #f8fafc;
    }
    
    .order-actions {
        display: flex;
        flex-wrap: wrap;
        gap: 0.75rem;
        margin-top: 1rem;
    }
</style>

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

<div id="wrapper">
    <?php $pagetitle = "My Orders"; include 'partials/menu.php'; ?>

    <div class="content-page">
        <div class="content">
            <div class="container-fluid orders-container">

                <!-- Page Title -->
                <div class="row">
                    <div class="col-12">
                        <div class="page-title-box">
                            <div class="page-title-right">
                                <ol class="breadcrumb m-0">
                                    <li class="breadcrumb-item"><a href="<?php echo ($user_role === 'Customer') ? 'dashboard.php' : 'index.php'; ?>">Dashboard</a></li>
                                    <li class="breadcrumb-item">Plugin Store</li>
                                    <li class="breadcrumb-item active">My Orders</li>
                                </ol>
                            </div>
                            <h4 class="page-title">My Orders</h4>
                        </div>
                    </div>
                </div>

                <!-- Order Statistics -->
                <div class="stats-grid">
                    <div class="stat-card">
                        <span class="stat-number"><?php echo $order_stats['total_orders']; ?></span>
                        <p class="stat-label">Total Orders</p>
                    </div>
                    
                    <div class="stat-card">
                        <span class="stat-number">$<?php echo number_format($order_stats['total_spent'], 0); ?></span>
                        <p class="stat-label">Total Spent</p>
                    </div>
                    
                    <div class="stat-card">
                        <span class="stat-number"><?php echo $order_stats['active_licenses']; ?></span>
                        <p class="stat-label">Active Licenses</p>
                    </div>
                    
                    <div class="stat-card">
                        <span class="stat-number"><?php echo $order_stats['pending_orders']; ?></span>
                        <p class="stat-label">Pending Orders</p>
                    </div>
                </div>

                <!-- Filters -->
                <div class="filters-section">
                    <form method="GET" action="" class="d-flex align-items-center">
                        <label for="status" style="margin-right: 1rem; font-weight: 500;">Filter by Status:</label>
                        <select name="status" id="status" class="filter-select" onchange="this.form.submit()">
                            <option value="">All Orders</option>
                            <option value="completed" <?php echo ($status_filter === 'completed') ? 'selected' : ''; ?>>Completed</option>
                            <option value="pending" <?php echo ($status_filter === 'pending') ? 'selected' : ''; ?>>Pending</option>
                            <option value="processing" <?php echo ($status_filter === 'processing') ? 'selected' : ''; ?>>Processing</option>
                            <option value="cancelled" <?php echo ($status_filter === 'cancelled') ? 'selected' : ''; ?>>Cancelled</option>
                        </select>
                        <?php if ($status_filter): ?>
                        <a href="my-orders.php" class="btn-outline">Clear Filter</a>
                        <?php endif; ?>
                    </form>
                </div>

                <!-- Orders List -->
                <div class="row">
                    <div class="col-12">
                        <?php if (!empty($orders)): ?>
                            <?php foreach ($orders as $order): ?>
                            <div class="order-card">
                                <div class="order-header">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div>
                                            <h5 class="order-number">Order #<?php echo htmlspecialchars($order['order_number']); ?></h5>
                                            <p class="order-date">Placed on <?php echo date('F j, Y \a\t g:i A', strtotime($order['created_at'])); ?></p>
                                        </div>
                                        <div class="order-status status-<?php echo strtolower($order['order_status']); ?>">
                                            <?php echo ucfirst(strtolower($order['order_status'])); ?>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="order-content">
                                    <!-- Order Items -->
                                    <?php if (!empty($order['items'])): ?>
                                        <?php foreach ($order['items'] as $item): ?>
                                        <div class="order-item">
                                            <div class="item-image">
                                                <?php if (!empty($item['image']) && $item['image'] !== 'assets/images/plugin-default.png'): ?>
                                                <img src="<?php echo htmlspecialchars($item['image']); ?>" alt="<?php echo htmlspecialchars($item['product_name']); ?>" style="width: 100%; height: 100%; object-fit: cover; border-radius: 8px;">
                                                <?php else: ?>
                                                🔌
                                                <?php endif; ?>
                                            </div>
                                            <div class="item-details">
                                                <h6 class="item-name"><?php echo htmlspecialchars($item['product_name']); ?></h6>
                                                <p class="item-meta">
                                                    <?php echo htmlspecialchars($item['category']); ?>
                                                    <?php if ($item['quantity'] > 1): ?>
                                                    • Quantity: <?php echo $item['quantity']; ?>
                                                    <?php endif; ?>
                                                </p>
                                            </div>
                                            <div class="item-price">
                                                $<?php echo number_format($item['total_price'], 2); ?>
                                            </div>
                                        </div>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <div class="order-item">
                                            <div class="item-image">🔌</div>
                                            <div class="item-details">
                                                <h6 class="item-name">Plugin Purchase</h6>
                                                <p class="item-meta">Payment Gateway Plugin</p>
                                            </div>
                                            <div class="item-price">
                                                $<?php echo number_format($order['total_amount'], 2); ?>
                                            </div>
                                        </div>
                                    <?php endif; ?>

                                    <!-- Order Total -->
                                    <div class="order-total">
                                        <div class="total-amount">
                                            Total: $<?php echo number_format($order['total_amount'], 2); ?> <?php echo $order['currency']; ?>
                                        </div>
                                        <div style="font-size: 0.875rem; color: #64748b; margin-top: 0.25rem;">
                                            Payment via <?php echo ucfirst(str_replace('_', ' ', strtolower($order['payment_method']))); ?>
                                        </div>
                                    </div>

                                    <!-- License Information -->
                                    <?php if ($order['order_status'] === 'COMPLETED' && !empty($order['licenses'])): ?>
                                    <div class="license-info">
                                        <strong>🔑 License Information:</strong>
                                        <?php foreach ($order['licenses'] as $license): ?>
                                        <div style="margin-top: 0.75rem;">
                                            <div><strong><?php echo htmlspecialchars($license['product_name']); ?></strong></div>
                                            <div class="license-key" onclick="copyToClipboard(this)" title="Click to copy">
                                                <?php echo htmlspecialchars($license['license_key']); ?>
                                            </div>
                                            <div style="font-size: 0.75rem; color: #64748b;">
                                                Sites: <?php echo $license['sites_used']; ?>/<?php echo $license['sites_allowed']; ?>
                                                <?php if ($license['expires_at']): ?>
                                                • Expires: <?php echo date('M j, Y', strtotime($license['expires_at'])); ?>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        <?php endforeach; ?>
                                    </div>
                                    <?php endif; ?>

                                    <!-- Order Actions -->
                                    <div class="order-actions">
                                        <a href="#" class="btn-outline">
                                            📄 View Details
                                        </a>
                                        
                                        <?php if ($order['order_status'] === 'COMPLETED'): ?>
                                        <a href="#" class="btn-outline">
                                            📥 Download
                                        </a>
                                        <a href="#" class="btn-outline">
                                            🧾 Receipt
                                        </a>
                                        <?php endif; ?>
                                        
                                        <?php if ($order['order_status'] === 'PENDING'): ?>
                                        <a href="#" class="btn-primary">
                                            💳 Complete Payment
                                        </a>
                                        <?php endif; ?>
                                        
                                        <a href="#" class="btn-outline">
                                            💬 Support
                                        </a>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>

                            <!-- Pagination -->
                            <?php if ($total_pages > 1): ?>
                            <div class="pagination">
                                <?php if ($page > 1): ?>
                                <a href="?page=<?php echo $page - 1; ?>&status=<?php echo $status_filter; ?>" class="pagination-btn">‹ Previous</a>
                                <?php else: ?>
                                <span class="pagination-btn disabled">‹ Previous</span>
                                <?php endif; ?>

                                <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                                <a href="?page=<?php echo $i; ?>&status=<?php echo $status_filter; ?>" 
                                   class="pagination-btn <?php echo ($i === $page) ? 'active' : ''; ?>">
                                    <?php echo $i; ?>
                                </a>
                                <?php endfor; ?>

                                <?php if ($page < $total_pages): ?>
                                <a href="?page=<?php echo $page + 1; ?>&status=<?php echo $status_filter; ?>" class="pagination-btn">Next ›</a>
                                <?php else: ?>
                                <span class="pagination-btn disabled">Next ›</span>
                                <?php endif; ?>
                            </div>
                            <?php endif; ?>

                        <?php else: ?>
                            <!-- Empty State -->
                            <div class="empty-state">
                                <div class="empty-icon">📦</div>
                                <h3 class="empty-title">
                                    <?php if ($status_filter): ?>
                                    No <?php echo ucfirst($status_filter); ?> Orders
                                    <?php else: ?>
                                    No Orders Yet
                                    <?php endif; ?>
                                </h3>
                                <p class="empty-text">
                                    <?php if ($status_filter): ?>
                                    You don't have any <?php echo strtolower($status_filter); ?> orders. Try viewing all orders or browse our plugin store.
                                    <?php else: ?>
                                    You haven't placed any orders yet. Browse our plugin store to find mobile money payment solutions for your WordPress site.
                                    <?php endif; ?>
                                </p>
                                <div>
                                    <?php if ($status_filter): ?>
                                    <a href="my-orders.php" class="btn-primary">View All Orders</a>
                                    <?php else: ?>
                                    <a href="browse-plugins.php" class="btn-primary">Browse Plugin Store</a>
                                    <a href="payment-gateways.php" class="btn-outline">View Payment Gateways</a>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Quick Actions -->
                <?php if (!empty($orders)): ?>
                <div class="row">
                    <div class="col-12">
                        <div style="background: white; border: 1px solid #e2e8f0; border-radius: 12px; padding: 1.5rem; margin-top: 2rem;">
                            <h5 style="color: #1e293b; margin-bottom: 1rem;">Quick Actions</h5>
                            <div style="display: flex; gap: 1rem; flex-wrap: wrap;">
                                <a href="browse-plugins.php" class="btn-outline">🛒 Continue Shopping</a>
                                <a href="my-licenses.php" class="btn-outline">🔑 Manage Licenses</a>
                                <a href="wallet-overview.php" class="btn-outline">💰 View Wallet</a>
                                <a href="create-ticket.php" class="btn-outline">💬 Contact Support</a>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

            </div>
        </div>

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

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

<script>
console.log('📦 My Orders page loaded successfully');

// Copy license key to clipboard
function copyToClipboard(element) {
    const text = element.textContent.trim();
    
    if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(text).then(function() {
            showCopySuccess(element);
        }).catch(function(err) {
            console.error('Failed to copy: ', err);
            fallbackCopy(text, element);
        });
    } else {
        fallbackCopy(text, element);
    }
}

// Fallback copy method
function fallbackCopy(text, element) {
    const textArea = document.createElement('textarea');
    textArea.value = text;
    textArea.style.position = 'fixed';
    textArea.style.left = '-999999px';
    textArea.style.top = '-999999px';
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();
    
    try {
        document.execCommand('copy');
        showCopySuccess(element);
    } catch (err) {
        console.error('Fallback copy failed: ', err);
    }
    
    document.body.removeChild(textArea);
}

// Show copy success notification
function showCopySuccess(element) {
    const originalText = element.innerHTML;
    element.innerHTML = '✅ Copied!';
    element.style.background = '#dcfce7';
    element.style.color = '#166534';
    
    setTimeout(() => {
        element.innerHTML = originalText;
        element.style.background = 'white';
        element.style.color = '#1e293b';
    }, 2000);
    
    // Also show a toast notification
    showToast('License key copied to clipboard!', 'success');
}

// Simple toast notification
function showToast(message, type = 'info') {
    const toast = document.createElement('div');
    toast.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: ${type === 'success' ? '#10b981' : '#3b82f6'};
        color: white;
        padding: 1rem 1.5rem;
        border-radius: 8px;
        font-size: 0.875rem;
        font-weight: 500;
        z-index: 1000;
        box-shadow: 0 10px 25px -3px rgba(0, 0, 0, 0.1);
        transform: translateX(400px);
        transition: transform 0.3s ease;
    `;
    toast.textContent = message;
    document.body.appendChild(toast);
    
    // Animate in
    setTimeout(() => {
        toast.style.transform = 'translateX(0)';
    }, 100);
    
    // Animate out and remove
    setTimeout(() => {
        toast.style.transform = 'translateX(400px)';
        setTimeout(() => {
            document.body.removeChild(toast);
        }, 300);
    }, 3000);
}

// Add hover effects to order cards
document.querySelectorAll('.order-card').forEach(card => {
    card.addEventListener('mouseenter', function() {
        this.style.transform = 'translateY(-2px)';
    });
    
    card.addEventListener('mouseleave', function() {
        this.style.transform = 'translateY(0)';
    });
});

// Add click handlers for action buttons
document.querySelectorAll('.btn-primary, .btn-outline').forEach(btn => {
    btn.addEventListener('click', function(e) {
        // Only prevent default for demo links (href="#")
        if (this.getAttribute('href') === '#') {
            e.preventDefault();
            
            const action = this.textContent.trim();
            console.log('Action clicked:', action);
            
            // Show appropriate messages for different actions
            if (action.includes('Complete Payment')) {
                showToast('Redirecting to payment...', 'info');
            } else if (action.includes('Download')) {
                showToast('Download will start shortly...', 'info');
            } else if (action.includes('Support')) {
                showToast('Opening support ticket...', 'info');
            } else if (action.includes('Receipt')) {
                showToast('Generating receipt...', 'info');
            } else if (action.includes('Details')) {
                showToast('Loading order details...', 'info');
            }
        }
    });
});

// Auto-refresh for pending orders (every 30 seconds)
<?php if ($order_stats['pending_orders'] > 0): ?>
let refreshCount = 0;
const maxRefreshes = 10; // Stop after 5 minutes

const refreshInterval = setInterval(() => {
    refreshCount++;
    
    if (refreshCount >= maxRefreshes) {
        clearInterval(refreshInterval);
        return;
    }
    
    // Only refresh if user is still on the page and no filters are applied
    if (!document.hidden && !window.location.search.includes('status=')) {
        console.log('Checking for order updates...');
        
        // Add a subtle loading indicator
        const indicator = document.querySelector('.refresh-indicator');
        if (!indicator) {
            const refreshIndicator = document.createElement('div');
            refreshIndicator.className = 'refresh-indicator';
            refreshIndicator.style.cssText = `
                position: fixed;
                bottom: 20px;
                right: 20px;
                background: rgba(59, 130, 246, 0.9);
                color: white;
                padding: 0.75rem 1rem;
                border-radius: 25px;
                font-size: 0.75rem;
                z-index: 1000;
                display: flex;
                align-items: center;
                gap: 0.5rem;
                opacity: 0.8;
            `;
            refreshIndicator.innerHTML = '🔄 <span>Checking for updates...</span>';
            document.body.appendChild(refreshIndicator);
            
            // Remove after 3 seconds
            setTimeout(() => {
                if (document.body.contains(refreshIndicator)) {
                    document.body.removeChild(refreshIndicator);
                }
            }, 3000);
        }
    }
}, 30000);
<?php endif; ?>

// Keyboard shortcuts
document.addEventListener('keydown', function(e) {
    // F5 or Ctrl+R to refresh
    if (e.key === 'F5' || (e.ctrlKey && e.key === 'r')) {
        console.log('Manual refresh triggered');
    }
    
    // Escape to clear filters
    if (e.key === 'Escape' && window.location.search.includes('status=')) {
        window.location.href = 'my-orders.php';
    }
    
    // Arrow keys for pagination
    if (e.key === 'ArrowLeft' && document.querySelector('.pagination-btn:contains("Previous")')) {
        e.preventDefault();
        const prevBtn = document.querySelector('a.pagination-btn[href*="page=' + (<?php echo $page; ?> - 1) + '"]');
        if (prevBtn) prevBtn.click();
    }
    
    if (e.key === 'ArrowRight' && document.querySelector('.pagination-btn:contains("Next")')) {
        e.preventDefault();
        const nextBtn = document.querySelector('a.pagination-btn[href*="page=' + (<?php echo $page; ?> + 1) + '"]');
        if (nextBtn) nextBtn.click();
    }
});

// Initialize page
document.addEventListener('DOMContentLoaded', function() {
    console.log('📊 Order Statistics:', {
        total_orders: <?php echo $order_stats['total_orders']; ?>,
        total_spent: <?php echo $order_stats['total_spent']; ?>,
        pending_orders: <?php echo $order_stats['pending_orders']; ?>,
        active_licenses: <?php echo $order_stats['active_licenses']; ?>
    });
    
    // Add loading states to buttons on click
    document.querySelectorAll('.btn-primary, .btn-outline').forEach(btn => {
        btn.addEventListener('click', function() {
            if (this.getAttribute('href') !== '#') {
                const originalText = this.innerHTML;
                this.innerHTML = '⏳ Loading...';
                this.style.opacity = '0.7';
                
                // Reset after 2 seconds if still on page
                setTimeout(() => {
                    if (document.body.contains(this)) {
                        this.innerHTML = originalText;
                        this.style.opacity = '1';
                    }
                }, 2000);
            }
        });
    });
    
    // Add tooltips to license keys
    document.querySelectorAll('.license-key').forEach(key => {
        key.title = 'Click to copy license key';
        key.style.cursor = 'pointer';
    });
    
    // Animate stats on load
    document.querySelectorAll('.stat-number').forEach((stat, index) => {
        stat.style.opacity = '0';
        stat.style.transform = 'translateY(20px)';
        
        setTimeout(() => {
            stat.style.transition = 'all 0.5s ease';
            stat.style.opacity = '1';
            stat.style.transform = 'translateY(0)';
        }, index * 100);
    });
});

// Performance monitoring
window.addEventListener('load', function() {
    const loadTime = performance.now();
    console.log(`📈 Page loaded in ${loadTime.toFixed(2)}ms`);
    
    // Track if there are any slow elements
    if (loadTime > 2000) {
        console.warn('⚠️ Page load time is slow, consider optimization');
    }
});
</script>

</body>
</html>