<?php
require_once '../config.php';
require_once '../app/classes/AdminAuth.php';

$adminAuth = new AdminAuth($conn);

if (!$adminAuth->isAuthenticated()) {
    header('Location: admin_login.php');
    exit;
}

// Read filters (GET)
$status_filter = isset($_GET['status']) ? trim($_GET['status']) : '';
$agent_filter = isset($_GET['agent']) ? trim($_GET['agent']) : '';
$network_filter = isset($_GET['network']) ? trim($_GET['network']) : '';
$date_from = isset($_GET['date_from']) ? trim($_GET['date_from']) : '';
$date_to = isset($_GET['date_to']) ? trim($_GET['date_to']) : '';
$time_from = isset($_GET['time_from']) ? trim($_GET['time_from']) : '';
$time_to = isset($_GET['time_to']) ? trim($_GET['time_to']) : '';

// Build unified query to get all orders from both orders and agent_orders tables
function buildAllOrdersQuery($conn, $status_filter, $agent_filter, $network_filter, $date_from, $time_from, $date_to, $time_to) {
    $whereConditions = [];
    
    // Build WHERE conditions for filters
    if ($status_filter !== '') {
        $whereConditions[] = "status = '" . mysqli_real_escape_string($conn, $status_filter) . "'";
    }
    
    if ($network_filter !== '') {
        $whereConditions[] = "network_type = '" . mysqli_real_escape_string($conn, $network_filter) . "'";
    }
    
    if ($date_from !== '') {
        $from = $date_from . ($time_from !== '' ? (" " . $time_from . ":00") : ' 00:00:00');
        $whereConditions[] = "created_at >= '" . mysqli_real_escape_string($conn, $from) . "'";
    }
    
    if ($date_to !== '') {
        $to = $date_to . ($time_to !== '' ? (" " . $time_to . ":59") : ' 23:59:59');
        $whereConditions[] = "created_at <= '" . mysqli_real_escape_string($conn, $to) . "'";
    }
    
    // Add 3-day limit by default (unless specific date filters are provided)
    if ($date_from === '' && $date_to === '') {
        $whereConditions[] = "created_at >= DATE_SUB(NOW(), INTERVAL 3 DAY)";
    }
    
    $whereClause = !empty($whereConditions) ? "WHERE " . implode(' AND ', $whereConditions) : "";
    
    // Check if store_id column exists in orders table
    $checkStoreCol = $conn->query("SHOW COLUMNS FROM orders LIKE 'store_id'");
    $hasStoreId = $checkStoreCol && $checkStoreCol->num_rows > 0;
    if ($checkStoreCol) $checkStoreCol->close();
    
    // Unified query combining orders and agent_orders
    $query = "
        SELECT 
            id,
            status,
            'Website' as source,
            network_type,
            package_size,
            amount,
            created_at,
            " . ($hasStoreId ? "store_id," : "NULL as store_id,") . "
            agent_id,
            'orders' as order_table
        FROM orders
        {$whereClause}
        
        UNION ALL
        
        SELECT 
            id,
            status,
            CASE 
                WHEN order_source = 'api' THEN 'Agent (API)'
                ELSE 'Agent (Dashboard)'
            END as source,
            network_type,
            package_size,
            amount,
            created_at,
            " . ($hasStoreId ? "store_id," : "NULL as store_id,") . "
            agent_id,
            'agent_orders' as order_table
        FROM agent_orders
        {$whereClause}
        
        ORDER BY created_at DESC
    ";
    
    return $query;
}

// Build unified query with proper joins for store owner and agent filtering
function buildAllOrdersQueryWithJoins($conn, $status_filter, $agent_filter, $network_filter, $date_from, $time_from, $date_to, $time_to) {
    // Both tables use 'created_at' column
    $whereConditions = [];
    
    // Build WHERE conditions for filters (orders table)
    if ($status_filter !== '') {
        $whereConditions[] = "o.status = '" . mysqli_real_escape_string($conn, $status_filter) . "'";
    }
    
    if ($network_filter !== '') {
        $whereConditions[] = "o.network_type = '" . mysqli_real_escape_string($conn, $network_filter) . "'";
    }
    
    if ($date_from !== '') {
        $from = $date_from . ($time_from !== '' ? (" " . $time_from . ":00") : ' 00:00:00');
        $whereConditions[] = "o.created_at >= '" . mysqli_real_escape_string($conn, $from) . "'";
    }
    
    if ($date_to !== '') {
        $to = $date_to . ($time_to !== '' ? (" " . $time_to . ":59") : ' 23:59:59');
        $whereConditions[] = "o.created_at <= '" . mysqli_real_escape_string($conn, $to) . "'";
    }
    
    // Add 3-day limit by default (unless specific date filters are provided)
    if ($date_from === '' && $date_to === '') {
        $whereConditions[] = "o.created_at >= DATE_SUB(NOW(), INTERVAL 3 DAY)";
    }
    
    $whereClause = !empty($whereConditions) ? "WHERE " . implode(' AND ', $whereConditions) : "";
    
    // Check if store_id column exists
    $checkStoreCol = $conn->query("SHOW COLUMNS FROM orders LIKE 'store_id'");
    $hasStoreId = $checkStoreCol && $checkStoreCol->num_rows > 0;
    if ($checkStoreCol) $checkStoreCol->close();
    
    // Agent filter condition
    $agentJoin = "";
    $agentWhere = "";
    $agentFilterSafe = "";
    if ($agent_filter !== '') {
        $agentFilterSafe = mysqli_real_escape_string($conn, $agent_filter);
        $agentJoin = "LEFT JOIN agents a_filter ON o.agent_id = a_filter.id";
        $agentWhere = "AND a_filter.username LIKE '%{$agentFilterSafe}%'";
    }
    
    // Build WHERE conditions for agent_orders
    $whereConditionsAgent = [];
    if ($status_filter !== '') {
        $whereConditionsAgent[] = "ao.status = '" . mysqli_real_escape_string($conn, $status_filter) . "'";
    }
    
    if ($network_filter !== '') {
        $whereConditionsAgent[] = "ao.network_type = '" . mysqli_real_escape_string($conn, $network_filter) . "'";
    }
    
    if ($date_from !== '') {
        $from = $date_from . ($time_from !== '' ? (" " . $time_from . ":00") : ' 00:00:00');
        $whereConditionsAgent[] = "ao.created_at >= '" . mysqli_real_escape_string($conn, $from) . "'";
    }
    
    if ($date_to !== '') {
        $to = $date_to . ($time_to !== '' ? (" " . $time_to . ":59") : ' 23:59:59');
        $whereConditionsAgent[] = "ao.created_at <= '" . mysqli_real_escape_string($conn, $to) . "'";
    }
    
    // Add 3-day limit by default (unless specific date filters are provided)
    if ($date_from === '' && $date_to === '') {
        $whereConditionsAgent[] = "ao.created_at >= DATE_SUB(NOW(), INTERVAL 3 DAY)";
    }
    
    $whereClauseAgent = !empty($whereConditionsAgent) ? "WHERE " . implode(' AND ', $whereConditionsAgent) : "";
    
    // Unified query combining orders and agent_orders with store owner info
    $query = "
        SELECT 
            o.id,
            o.status,
            'Website' as source,
            o.network_type,
            o.package_size,
            o.amount,
            o.created_at,
            o.beneficiary_number,
            " . ($hasStoreId ? "o.store_id," : "NULL as store_id,") . "
            o.agent_id,
            'orders' as order_table,
            " . ($hasStoreId ? "COALESCE(store_owner.username, 'N/A') as store_owner_name,
            COALESCE(store_owner.store_name, 'N/A') as store_name" : "'N/A' as store_owner_name, 'N/A' as store_name") . "
        FROM orders o
        " . ($hasStoreId ? "LEFT JOIN (
            SELECT s.id as store_id, s.store_name, a.username, a.id as owner_id
            FROM stores s
            INNER JOIN agents a ON s.owner_id = a.id
        ) store_owner ON o.store_id = store_owner.store_id" : "") . "
        {$agentJoin}
        {$whereClause} {$agentWhere}
        
        UNION ALL
        
        SELECT 
            ao.id,
            ao.status,
            CASE 
                WHEN ao.order_source = 'api' THEN 'Agent (API)'
                ELSE 'Agent (Dashboard)'
            END as source,
            ao.network_type,
            ao.package_size,
            ao.amount,
            ao.created_at,
            ao.beneficiary_number,
            " . ($hasStoreId ? "ao.store_id," : "NULL as store_id,") . "
            ao.agent_id,
            'agent_orders' as order_table,
            " . ($hasStoreId ? "COALESCE(store_owner_ao.username, 'N/A') as store_owner_name,
            COALESCE(store_owner_ao.store_name, 'N/A') as store_name" : "'N/A' as store_owner_name, 'N/A' as store_name") . "
            FROM agent_orders ao
        " . ($hasStoreId ? "LEFT JOIN (
            SELECT s.id as store_id, s.store_name, a.username, a.id as owner_id
            FROM stores s
            INNER JOIN agents a ON s.owner_id = a.id
        ) store_owner_ao ON ao.store_id = store_owner_ao.store_id" : "") . "
        " . ($agent_filter !== '' ? "LEFT JOIN agents a_filter_ao ON ao.agent_id = a_filter_ao.id" : "") . "
        {$whereClauseAgent} " . ($agent_filter !== '' ? "AND a_filter_ao.username LIKE '%{$agentFilterSafe}%'" : "") . "
        
        ORDER BY created_at DESC
    ";
    
    return $query;
}

// Get all orders with store owner information
$allOrdersQuery = buildAllOrdersQueryWithJoins($conn, $status_filter, $agent_filter, $network_filter, $date_from, $time_from, $date_to, $time_to);
$allOrdersResult = mysqli_query($conn, $allOrdersQuery);

// Fetch all orders and separate into regular orders and agent orders
$regularOrders = [];
$agentOrders = [];
while ($row = mysqli_fetch_assoc($allOrdersResult)) {
    $order = $row;
    
    // Format store owner display
    if (!empty($order['store_owner_name']) && $order['store_owner_name'] !== 'N/A') {
        $order['store_owner'] = $order['store_owner_name'] . (!empty($order['store_name']) && $order['store_name'] !== 'N/A' ? ' (' . $order['store_name'] . ')' : '');
    } else {
        $order['store_owner'] = 'N/A';
    }
    
    // Separate orders by table type
    if ($order['order_table'] === 'orders') {
        $regularOrders[] = $order;
    } else {
        $agentOrders[] = $order;
    }
}

// Set page variables for header
$page_title = 'Orders Management';
$page_description = 'Manage and monitor all orders across the platform';
?>

<div class="p-6">
        <!-- Filters and Bulk Operations -->
        <div class="form-card mb-6 p-6">
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                <!-- Filters -->
                <div>
                    <h3 class="text-lg font-semibold text-dark-primary mb-4">Filters</h3>
                    <form method="GET" class="space-y-4">
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-dark-secondary mb-2">Status</label>
                                <select name="status" class="w-full p-2 border border-dark-primary bg-dark-tertiary text-dark-primary rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                    <option value="">All Statuses</option>
                                    <option value="pending" <?= $status_filter === 'pending' ? 'selected' : '' ?>>Pending</option>
                                    <option value="delivered" <?= $status_filter === 'delivered' ? 'selected' : '' ?>>Delivered</option>
                                    <option value="failed" <?= $status_filter === 'failed' ? 'selected' : '' ?>>Failed</option>
                                    <option value="api_failed" <?= $status_filter === 'api_failed' ? 'selected' : '' ?>>API Failed</option>
                                </select>
                            </div>
                                    <div>
                                        <label class="block text-sm font-medium text-dark-secondary mb-2">Network</label>
                                        <select name="network" class="w-full p-2 border border-dark-primary bg-dark-tertiary text-dark-primary rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                            <option value="" <?= $network_filter === '' ? 'selected' : '' ?>>All</option>
                                            <option value="mtn" <?= $network_filter === 'mtn' ? 'selected' : '' ?>>MTN</option>
                                        </select>
                                    </div>
                            <div>
                                <label class="block text-sm font-medium text-dark-secondary mb-2">Agent Username</label>
                                <input type="text" name="agent" value="<?= htmlspecialchars($agent_filter) ?>" placeholder="Search by username" class="w-full p-2 border border-dark-primary bg-dark-tertiary text-dark-primary rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-dark-secondary mb-2">Date From</label>
                                <input type="date" name="date_from" value="<?= htmlspecialchars($date_from) ?>" class="w-full p-2 border border-dark-primary bg-dark-tertiary text-dark-primary rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-dark-secondary mb-2">Date To</label>
                                <input type="date" name="date_to" value="<?= htmlspecialchars($date_to) ?>" class="w-full p-2 border border-dark-primary bg-dark-tertiary text-dark-primary rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-dark-secondary mb-2">Time From</label>
                                <input type="time" name="time_from" value="<?= htmlspecialchars($time_from) ?>" class="w-full p-2 border border-dark-primary bg-dark-tertiary text-dark-primary rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-dark-secondary mb-2">Time To</label>
                                <input type="time" name="time_to" value="<?= htmlspecialchars($time_to) ?>" class="w-full p-2 border border-dark-primary bg-dark-tertiary text-dark-primary rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                            </div>
                        </div>
                        <div class="flex space-x-3">
                            <button type="submit" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
                                <i class="fas fa-search mr-2"></i>Apply Filters
                            </button>
                            <a href="orders_management.php" class="bg-gray-500 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded">
                                <i class="fas fa-times mr-2"></i>Clear Filters
                            </a>
                        </div>
                    </form>
                </div>

                <!-- Bulk Operations -->
                <div>
                    <h3 class="text-lg font-semibold text-dark-primary mb-4">Bulk Operations</h3>
                    
                    <!-- Bulk Update by Selection -->
                            <form method="POST" id="bulkUpdateForm" class="mb-4" onsubmit="return submitBulkUpdate(event)">
                        <div class="flex space-x-3">
                                    <select name="new_status" id="bulk_new_status" class="flex-1 p-2 border border-dark-primary bg-dark-tertiary text-dark-primary rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                <option value="">Select Status</option>
                                <option value="pending">Pending</option>
                                <option value="delivered">Delivered</option>
                                <option value="failed">Failed</option>
                                <option value="api_failed">API Failed</option>
                            </select>
                            <button type="submit" class="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded">
                                <i class="fas fa-check mr-2"></i>Update Selected
                            </button>
                        </div>
                    </form>
                    
                    <!-- Bulk Selection Controls -->
                    <div class="mb-4">
                        <div class="flex space-x-3">
                            <button onclick="selectAllOrders()" class="bg-gray-500 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded">
                                <i class="fas fa-check-square mr-2"></i>Select All Orders
                            </button>
                            <button onclick="deselectAllOrders()" class="bg-gray-500 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded">
                                <i class="fas fa-square mr-2"></i>Deselect All Orders
                            </button>
                        </div>
                        <p class="text-sm text-gray-600 mt-2">
                            <i class="fas fa-info-circle mr-1"></i>
                            Each network tab has its own "Export Selected (CSV)" button. Use the individual network export buttons to export orders from specific networks.
                        </p>
                    </div>

                    <!-- Bulk Update by Time Range -->
                    <form method="POST" id="bulkUpdateByRangeForm" onsubmit="return submitBulkUpdateByRange(event)">
                        <div class="space-y-3">
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                                <div>
                                    <label class="block text-sm font-medium text-dark-secondary mb-1">From Date</label>
                                    <input type="date" name="date_from" required class="w-full p-2 border border-dark-primary bg-dark-tertiary text-dark-primary rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-dark-secondary mb-1">To Date</label>
                                    <input type="date" name="date_to" required class="w-full p-2 border border-dark-primary bg-dark-tertiary text-dark-primary rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                </div>
                            </div>
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                                <div>
                                    <label class="block text-sm font-medium text-dark-secondary mb-1">From Time (Optional)</label>
                                    <input type="time" name="time_from" class="w-full p-2 border border-dark-primary bg-dark-tertiary text-dark-primary rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-dark-secondary mb-1">To Time (Optional)</label>
                                    <input type="time" name="time_to" class="w-full p-2 border border-dark-primary bg-dark-tertiary text-dark-primary rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                </div>
                            </div>
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                                <div>
                                    <label class="block text-sm font-medium text-dark-secondary mb-1">Current Status (Optional)</label>
                                    <select name="current_status" class="w-full p-2 border border-dark-primary bg-dark-tertiary text-dark-primary rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                        <option value="">All Statuses</option>
                                        <option value="pending">Pending</option>
                                        <option value="delivered">Delivered</option>
                                        <option value="failed">Failed</option>
                                        <option value="api_failed">API Failed</option>
                                    </select>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-dark-secondary mb-1">New Status</label>
                                    <select name="new_status" required class="w-full p-2 border border-dark-primary bg-dark-tertiary text-dark-primary rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                        <option value="">Select Status</option>
                                        <option value="pending">Pending</option>
                                        <option value="delivered">Delivered</option>
                                        <option value="failed">Failed</option>
                                        <option value="api_failed">API Failed</option>
                                    </select>
                                </div>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-dark-secondary mb-1">Agent Filter (Optional)</label>
                                <input type="text" name="agent_filter" placeholder="Filter by agent username" class="w-full p-2 border border-dark-primary bg-dark-tertiary text-dark-primary rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                            </div>
                                    <div>
                                        <label class="block text-sm font-medium text-dark-secondary mb-1">Network (Optional)</label>
                                        <select name="network_type" class="w-full p-2 border border-dark-primary bg-dark-tertiary text-dark-primary rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                            <option value="">All</option>
                                            <option value="mtn">MTN</option>
                                            <option value="telecel">Telecel</option>
                                            <option value="airtel_tigo">AirtelTigo</option>
                                        </select>
                                    </div>
                                    <div>
                                        <label class="block text-sm font-medium text-dark-secondary mb-1">Network</label>
                                        <select name="network_type" class="w-full p-2 border border-dark-primary bg-dark-tertiary text-dark-primary rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                            <option value="">All</option>
                                            <option value="mtn">MTN</option>
                                            <option value="telecel">Telecel</option>
                                            <option value="airtel_tigo">AirtelTigo</option>
                                        </select>
                                    </div>
                            <button type="submit" class="w-full bg-purple-500 hover:bg-purple-700 text-white font-bold py-2 px-4 rounded">
                                        <i class="fas fa-calendar-check mr-2"></i>Update Agent Orders by Time Range
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

                <!-- Regular Orders (Website Orders) -->
                <div class="cute-card mb-8 p-6">
                    <div class="flex items-center justify-between mb-6">
                        <h2 class="text-xl font-bold text-dark-primary">
                            <i class="fas fa-globe mr-2 text-purple-600"></i>Regular Orders (Website)
                        </h2>
                        <p class="text-sm text-gray-300">Total: <?php echo count($regularOrders); ?> orders</p>
                    </div>
                    
                    <!-- Bulk Update Form for Regular Orders -->
                    <div class="mb-4 p-4 bg-purple-50 border border-purple-200 rounded-lg">
                        <form method="POST" id="bulkUpdateRegularForm" onsubmit="return submitBulkUpdateRegular(event)">
                            <div class="flex items-center gap-3">
                                <select name="new_status" id="bulk_new_status_regular" class="flex-1 p-2 border border-dark-primary bg-dark-tertiary text-dark-primary rounded-md focus:ring-2 focus:ring-purple-500 focus:border-transparent">
                                    <option value="">Select Status</option>
                                    <option value="pending">Pending</option>
                                    <option value="delivered">Delivered</option>
                                    <option value="failed">Failed</option>
                                </select>
                                <button type="submit" class="bg-purple-500 hover:bg-purple-700 text-white font-bold py-2 px-4 rounded">
                                    <i class="fas fa-check mr-2"></i>Update Selected
                                </button>
                                <button type="button" onclick="selectAllRegularOrders()" class="bg-gray-500 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded">
                                    <i class="fas fa-check-square mr-2"></i>Select All
                                </button>
                                <button type="button" onclick="deselectAllRegularOrders()" class="bg-gray-500 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded">
                                    <i class="fas fa-square mr-2"></i>Deselect All
                                </button>
                            </div>
                        </form>
                    </div>

                    <div class="overflow-x-auto p-4 table-container">
                        <table id="regularOrdersTable" class="min-w-full divide-y divide-dark-primary bg-dark-secondary text-dark-primary display" style="width:100%">
                            <thead>
                                <tr>
                                    <th class="px-4 py-3 text-left text-xs font-medium text-dark-secondary uppercase tracking-wider">
                                        <input type="checkbox" id="selectAllRegular" onchange="toggleAllRegular(this)">
                                    </th>
                                    <th class="px-4 py-3 text-left text-xs font-medium text-dark-secondary uppercase tracking-wider">ID</th>
                                    <th class="px-4 py-3 text-left text-xs font-medium text-dark-secondary uppercase tracking-wider">Status</th>
                                    <th class="px-4 py-3 text-left text-xs font-medium text-dark-secondary uppercase tracking-wider">Store Owner</th>
                                    <th class="px-4 py-3 text-left text-xs font-medium text-dark-secondary uppercase tracking-wider">Package Size</th>
                                    <th class="px-4 py-3 text-left text-xs font-medium text-dark-secondary uppercase tracking-wider">Amount</th>
                                    <th class="px-4 py-3 text-left text-xs font-medium text-dark-secondary uppercase tracking-wider">Beneficiary</th>
                                    <th class="px-4 py-3 text-left text-xs font-medium text-dark-secondary uppercase tracking-wider">Created At</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-dark-primary">
                                <?php foreach ($regularOrders as $order): ?>
                                <tr class="hover:bg-dark-tertiary transition-colors">
                                    <td class="px-4 py-3 whitespace-nowrap">
                                        <input type="checkbox" class="regular-order-checkbox" value="<?= htmlspecialchars($order['id']) ?>" data-table="orders">
                                    </td>
                                    <td class="px-4 py-3 whitespace-nowrap text-sm text-dark-primary font-mono">
                                        #<?= htmlspecialchars($order['id']) ?>
                                    </td>
                                    <td class="px-4 py-3 whitespace-nowrap">
                                        <span class="px-2 py-1 rounded-full text-xs font-medium
                                            <?php 
                                            switch($order['status']) {
                                                case 'pending': echo 'bg-yellow-100 text-yellow-800'; break;
                                                case 'delivered': echo 'bg-green-100 text-green-800'; break;
                                                case 'failed': echo 'bg-red-100 text-red-800'; break;
                                                case 'api_failed': echo 'bg-orange-100 text-orange-800'; break;
                                                case 'processing': echo 'bg-blue-100 text-blue-800'; break;
                                                default: echo 'bg-gray-100 text-dark-primary';
                                            }
                                            ?>">
                                            <?= $order['status'] === 'api_failed' ? 'API Failed' : ucfirst($order['status']) ?>
                                        </span>
                                    </td>
                                    <td class="px-4 py-3 whitespace-nowrap text-sm text-dark-primary">
                                        <?= htmlspecialchars($order['store_owner']) ?>
                                    </td>
                                    <td class="px-4 py-3 whitespace-nowrap text-sm text-dark-primary">
                                        <?= htmlspecialchars($order['package_size']) ?>
                                    </td>
                                    <td class="px-4 py-3 whitespace-nowrap text-sm text-dark-primary font-semibold">
                                        GH₵ <?= number_format($order['amount'], 2) ?>
                                    </td>
                                    <td class="px-4 py-3 whitespace-nowrap text-sm text-dark-primary">
                                        <?= htmlspecialchars($order['beneficiary_number'] ?? 'N/A') ?>
                                    </td>
                                    <td class="px-4 py-3 whitespace-nowrap text-sm text-dark-primary">
                                        <?= date('M j, Y g:i A', strtotime($order['created_at'])) ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- Agent Orders -->
                <div class="cute-card mb-8 p-6">
                    <div class="flex items-center justify-between mb-6">
                        <h2 class="text-xl font-bold text-dark-primary">
                            <i class="fas fa-users mr-2 text-blue-600"></i>Agent Orders
                        </h2>
                        <p class="text-sm text-gray-300">Total: <?php echo count($agentOrders); ?> orders</p>
                    </div>
                    
                    <!-- Bulk Update Form for Agent Orders -->
                    <div class="mb-4 p-4 bg-blue-50 border border-blue-200 rounded-lg">
                        <form method="POST" id="bulkUpdateAgentForm" onsubmit="return submitBulkUpdateAgent(event)">
                            <div class="flex items-center gap-3">
                                <select name="new_status" id="bulk_new_status_agent" class="flex-1 p-2 border border-dark-primary bg-dark-tertiary text-dark-primary rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                    <option value="">Select Status</option>
                                    <option value="pending">Pending</option>
                                    <option value="delivered">Delivered</option>
                                    <option value="failed">Failed</option>
                                    <option value="api_failed">API Failed</option>
                                </select>
                                <button type="submit" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
                                    <i class="fas fa-check mr-2"></i>Update Selected
                                </button>
                                <button type="button" onclick="selectAllAgentOrders()" class="bg-gray-500 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded">
                                    <i class="fas fa-check-square mr-2"></i>Select All
                                </button>
                                <button type="button" onclick="deselectAllAgentOrders()" class="bg-gray-500 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded">
                                    <i class="fas fa-square mr-2"></i>Deselect All
                                </button>
                            </div>
                        </form>
                    </div>

                    <div class="overflow-x-auto p-4 table-container">
                        <table id="agentOrdersTable" class="min-w-full divide-y divide-dark-primary bg-dark-secondary text-dark-primary display" style="width:100%">
                            <thead>
                                <tr>
                                    <th class="px-4 py-3 text-left text-xs font-medium text-dark-secondary uppercase tracking-wider">
                                        <input type="checkbox" id="selectAllAgent" onchange="toggleAllAgent(this)">
                                    </th>
                                    <th class="px-4 py-3 text-left text-xs font-medium text-dark-secondary uppercase tracking-wider">ID</th>
                                    <th class="px-4 py-3 text-left text-xs font-medium text-dark-secondary uppercase tracking-wider">Status</th>
                                    <th class="px-4 py-3 text-left text-xs font-medium text-dark-secondary uppercase tracking-wider">Source</th>
                                    <th class="px-4 py-3 text-left text-xs font-medium text-dark-secondary uppercase tracking-wider">Store Owner</th>
                                    <th class="px-4 py-3 text-left text-xs font-medium text-dark-secondary uppercase tracking-wider">Package Size</th>
                                    <th class="px-4 py-3 text-left text-xs font-medium text-dark-secondary uppercase tracking-wider">Amount</th>
                                    <th class="px-4 py-3 text-left text-xs font-medium text-dark-secondary uppercase tracking-wider">Beneficiary</th>
                                    <th class="px-4 py-3 text-left text-xs font-medium text-dark-secondary uppercase tracking-wider">Created At</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-dark-primary">
                                <?php foreach ($agentOrders as $order): ?>
                                <tr class="hover:bg-dark-tertiary transition-colors">
                                    <td class="px-4 py-3 whitespace-nowrap">
                                        <input type="checkbox" class="agent-order-checkbox" value="<?= htmlspecialchars($order['id']) ?>" data-table="agent_orders">
                                    </td>
                                    <td class="px-4 py-3 whitespace-nowrap text-sm text-dark-primary font-mono">
                                        #<?= htmlspecialchars($order['id']) ?>
                                    </td>
                                    <td class="px-4 py-3 whitespace-nowrap">
                                        <span class="px-2 py-1 rounded-full text-xs font-medium
                                            <?php 
                                            switch($order['status']) {
                                                case 'pending': echo 'bg-yellow-100 text-yellow-800'; break;
                                                case 'delivered': echo 'bg-green-100 text-green-800'; break;
                                                case 'failed': echo 'bg-red-100 text-red-800'; break;
                                                case 'api_failed': echo 'bg-orange-100 text-orange-800'; break;
                                                case 'processing': echo 'bg-blue-100 text-blue-800'; break;
                                                default: echo 'bg-gray-100 text-dark-primary';
                                            }
                                            ?>">
                                            <?= $order['status'] === 'api_failed' ? 'API Failed' : ucfirst($order['status']) ?>
                                        </span>
                                    </td>
                                    <td class="px-4 py-3 whitespace-nowrap text-sm text-dark-primary">
                                        <span class="px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                                            <?= htmlspecialchars($order['source']) ?>
                                        </span>
                                    </td>
                                    <td class="px-4 py-3 whitespace-nowrap text-sm text-dark-primary">
                                        <?= htmlspecialchars($order['store_owner']) ?>
                                    </td>
                                    <td class="px-4 py-3 whitespace-nowrap text-sm text-dark-primary">
                                        <?= htmlspecialchars($order['package_size']) ?>
                                    </td>
                                    <td class="px-4 py-3 whitespace-nowrap text-sm text-dark-primary font-semibold">
                                        GH₵ <?= number_format($order['amount'], 2) ?>
                                    </td>
                                    <td class="px-4 py-3 whitespace-nowrap text-sm text-dark-primary">
                                        <?= htmlspecialchars($order['beneficiary_number'] ?? 'N/A') ?>
                                    </td>
                                    <td class="px-4 py-3 whitespace-nowrap text-sm text-dark-primary">
                                        <?= date('M j, Y g:i A', strtotime($order['created_at'])) ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- DataTables CSS - Additional styles for this page -->
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/2.4.2/css/buttons.dataTables.min.css">

    <style>
    .network-tab-content {
        display: none;
    }
    .network-tab-content.active {
        display: block !important;
    }
    .network-tab-button {
        transition: all 0.3s ease;
    }
    .network-tab-button.active {
        background-color: #3b82f6;
        color: white;
    }
    
    /* DataTables Dark Theme Overrides */
    .dataTables_wrapper .dataTables_length,
    .dataTables_wrapper .dataTables_filter,
    .dataTables_wrapper .dataTables_info,
    .dataTables_wrapper .dataTables_processing,
    .dataTables_wrapper .dataTables_paginate {
        color: #f9fafb !important;
    }
    
    .dataTables_wrapper .dataTables_length select,
    .dataTables_wrapper .dataTables_filter input {
        background-color: #374151 !important;
        border-color: #4b5563 !important;
        color: #f9fafb !important;
    }
    
    .dataTables_wrapper .dataTables_paginate .paginate_button {
        color: #f9fafb !important;
        background-color: #374151 !important;
        border-color: #4b5563 !important;
    }
    
    .dataTables_wrapper .dataTables_paginate .paginate_button:hover {
        background-color: #4b5563 !important;
        color: #f9fafb !important;
    }
    
    .dataTables_wrapper .dataTables_paginate .paginate_button.current {
        background-color: #3b82f6 !important;
        color: white !important;
    }
    
    .dataTables_wrapper .dataTables_paginate .paginate_button.disabled {
        color: #6b7280 !important;
    }
    </style>

    <!-- DataTables JS - Additional scripts for this page -->
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/buttons/2.4.2/js/dataTables.buttons.min.js"></script>
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.html5.min.js"></script>
    <script type="text/javascript" charset="utf8" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
    <script type="text/javascript" charset="utf8" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
    <script type="text/javascript" charset="utf8" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>

    <script>
    function showToast(msg, type = 'success') {
        alert(msg);
    }
    
    // Regular Orders Functions
    function getSelectedRegularOrderIds() {
        const checkboxes = document.querySelectorAll('.regular-order-checkbox:checked');
        return Array.from(checkboxes).map(cb => cb.value);
    }
    
    function selectAllRegularOrders() {
        document.querySelectorAll('.regular-order-checkbox').forEach(cb => cb.checked = true);
        const master = document.getElementById('selectAllRegular');
        if (master) master.checked = true;
        showToast('All regular orders selected', 'success');
    }
    
    function deselectAllRegularOrders() {
        document.querySelectorAll('.regular-order-checkbox').forEach(cb => cb.checked = false);
        const master = document.getElementById('selectAllRegular');
        if (master) master.checked = false;
        showToast('All regular orders deselected', 'success');
    }
    
    function toggleAllRegular(checkbox) {
        document.querySelectorAll('.regular-order-checkbox').forEach(cb => cb.checked = checkbox.checked);
    }
    
    function submitBulkUpdateRegular(e) {
        e.preventDefault();
        const ids = getSelectedRegularOrderIds();
        const newStatus = document.getElementById('bulk_new_status_regular').value;
        if (ids.length === 0) { 
            showToast('Select orders to update', 'error'); 
            return false; 
        }
        if (!newStatus) { 
            showToast('Select a new status', 'error'); 
            return false; 
        }
        if (!confirm(`Update ${ids.length} regular order(s) to ${newStatus}?`)) return false;

        fetch('pages/bulk_update_status.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ order_ids: ids, status: newStatus, table_type: 'orders' })
        }).then(r => r.json()).then(data => {
            if (data.success) {
                showToast(data.message, 'success');
                setTimeout(() => location.reload(), 800);
            } else {
                showToast(data.message || 'Failed to update', 'error');
            }
        }).catch(error => {
            console.error('Fetch error:', error);
            showToast('Request failed: ' + error.message, 'error');
        });
        return false;
    }
    
    // Agent Orders Functions
    function getSelectedAgentOrderIds() {
        const checkboxes = document.querySelectorAll('.agent-order-checkbox:checked');
        return Array.from(checkboxes).map(cb => cb.value);
    }
    
    function selectAllAgentOrders() {
        document.querySelectorAll('.agent-order-checkbox').forEach(cb => cb.checked = true);
        const master = document.getElementById('selectAllAgent');
        if (master) master.checked = true;
        showToast('All agent orders selected', 'success');
    }
    
    function deselectAllAgentOrders() {
        document.querySelectorAll('.agent-order-checkbox').forEach(cb => cb.checked = false);
        const master = document.getElementById('selectAllAgent');
        if (master) master.checked = false;
        showToast('All agent orders deselected', 'success');
    }
    
    function toggleAllAgent(checkbox) {
        document.querySelectorAll('.agent-order-checkbox').forEach(cb => cb.checked = checkbox.checked);
    }
    
    function submitBulkUpdateAgent(e) {
        e.preventDefault();
        const ids = getSelectedAgentOrderIds();
        const newStatus = document.getElementById('bulk_new_status_agent').value;
        if (ids.length === 0) { 
            showToast('Select orders to update', 'error'); 
            return false; 
        }
        if (!newStatus) { 
            showToast('Select a new status', 'error'); 
            return false; 
        }
        if (!confirm(`Update ${ids.length} agent order(s) to ${newStatus}?`)) return false;

        fetch('pages/bulk_update_status.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ order_ids: ids, status: newStatus, table_type: 'agent_orders' })
        }).then(r => r.json()).then(data => {
            if (data.success) {
                showToast(data.message, 'success');
                setTimeout(() => location.reload(), 800);
            } else {
                showToast(data.message || 'Failed to update', 'error');
            }
        }).catch(error => {
            console.error('Fetch error:', error);
            showToast('Request failed: ' + error.message, 'error');
        });
        return false;
    }
    
    // Legacy functions for backward compatibility
    function getSelectedOrderIds() {
        // Combine both regular and agent orders
        return [...getSelectedRegularOrderIds(), ...getSelectedAgentOrderIds()];
    }
    
    function selectAll() {
        selectAllRegularOrders();
        selectAllAgentOrders();
    }
    
    function deselectAll() {
        deselectAllRegularOrders();
        deselectAllAgentOrders();
    }
    
    function toggleAllCheckboxes() {
        // This is a generic function - not used anymore but kept for compatibility
        const master = document.getElementById('selectAllCheckbox');
        if (master) {
            document.querySelectorAll('.order-checkbox').forEach(cb => cb.checked = master.checked);
        }
    }
    
    // Network-specific select all functions
    function toggleAllAgentMtn(checkbox) {
        const table = document.getElementById('agentMtnOrdersTable');
        if (table) {
            const checkboxes = table.querySelectorAll('.order-checkbox');
            checkboxes.forEach(cb => cb.checked = checkbox.checked);
        }
    }
    
    function toggleAllAgentTelecel(checkbox) {
        const table = document.getElementById('agentTelecelOrdersTable');
        if (table) {
            const checkboxes = table.querySelectorAll('.order-checkbox');
            checkboxes.forEach(cb => cb.checked = checkbox.checked);
        }
    }
    
    function toggleAllAgentAirtelTigo(checkbox) {
        const table = document.getElementById('agentAirtelTigoOrdersTable');
        if (table) {
            const checkboxes = table.querySelectorAll('.order-checkbox');
            checkboxes.forEach(cb => cb.checked = checkbox.checked);
        }
    }
    
    // Global select all/deselect all functions for bulk operations
    function selectAllOrders() {
        document.querySelectorAll('.order-checkbox').forEach(cb => cb.checked = true);
        // Also update the individual "select all" checkboxes in table headers
        document.querySelectorAll('input[id^="selectAllAgent"]').forEach(cb => cb.checked = true);
        showToast('All orders selected', 'success');
    }
    
    function deselectAllOrders() {
        document.querySelectorAll('.order-checkbox').forEach(cb => cb.checked = false);
        // Also update the individual "select all" checkboxes in table headers
        document.querySelectorAll('input[id^="selectAllAgent"]').forEach(cb => cb.checked = false);
        showToast('All orders deselected', 'success');
    }
    
    
    // Network-specific export functions
    function exportSelectedAgentOrders(networkType) {
        // Get only the selected orders from the current network tab
        let tableId;
        switch(networkType) {
            case 'mtn':
                tableId = 'agentMtnOrdersTable';
                break;
            case 'telecel':
                tableId = 'agentTelecelOrdersTable';
                break;
            case 'airtel_tigo':
                tableId = 'agentAirtelTigoOrdersTable';
                break;
            default:
                showToast('Invalid network type', 'error');
                return;
        }
        
        const table = document.getElementById(tableId);
        if (!table) {
            showToast('Network table not found', 'error');
            return;
        }
        
        const checkboxes = table.querySelectorAll('.order-checkbox:checked');
        const ids = Array.from(checkboxes).map(cb => cb.value);
        
        console.log('Export - Selected IDs for', networkType, ':', ids);
        
        if (ids.length === 0) { 
            showToast(`Select at least one order from ${networkType.toUpperCase()} tab to export`, 'error'); 
            return; 
        }
        
        // Show loading state
        const button = event.target;
        const originalText = button.innerHTML;
        button.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Exporting...';
        button.disabled = true;
        
        // Make AJAX request to export endpoint
        fetch('pages/export_orders_csv.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ 
                order_ids: ids,
                source: 'agent_orders',
                network_type: networkType
            })
        })
        .then(response => {
            if (response.ok) {
                // Get filename from Content-Disposition header
                const contentDisposition = response.headers.get('Content-Disposition');
                let filename = 'agent_orders_export.csv';
                if (contentDisposition) {
                    const filenameMatch = contentDisposition.match(/filename="(.+)"/);
                    if (filenameMatch) {
                        filename = filenameMatch[1];
                    }
                }
                
                // Create download link
                return response.blob().then(blob => {
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = filename;
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    window.URL.revokeObjectURL(url);
                    
                    showToast(`Successfully exported ${ids.length} ${networkType.toUpperCase()} order(s)`, 'success');
                });
            } else {
                return response.json().then(data => {
                    showToast(data.message || 'Export failed', 'error');
                });
            }
        })
        .catch(error => {
            console.error('Export error:', error);
            showToast('Export failed. Please try again.', 'error');
        })
        .finally(() => {
            // Restore button state
            button.innerHTML = originalText;
            button.disabled = false;
        });
    }
    function exportSelected() {
        const ids = getSelectedOrderIds();
        if (ids.length === 0) { 
            showToast('Select at least one order to export', 'error'); 
            return; 
        }
        
        // Show loading state
        const button = event.target;
        const originalText = button.innerHTML;
        button.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Exporting...';
        button.disabled = true;
        
        // Make AJAX request to export endpoint
        fetch('pages/export_orders_csv.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ 
                order_ids: ids,
                source: 'agent_orders'
            })
        })
        .then(response => {
            if (response.ok) {
                // Get filename from Content-Disposition header
                const contentDisposition = response.headers.get('Content-Disposition');
                let filename = 'orders_export.csv';
                if (contentDisposition) {
                    const filenameMatch = contentDisposition.match(/filename="(.+)"/);
                    if (filenameMatch) {
                        filename = filenameMatch[1];
                    }
                }
                
                // Create download link
                return response.blob().then(blob => {
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = filename;
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    window.URL.revokeObjectURL(url);
                    
                    showToast(`Successfully exported ${ids.length} ${networkType.toUpperCase()} order(s)`, 'success');
                });
            } else {
                return response.json().then(data => {
                    showToast(data.message || 'Export failed', 'error');
                });
            }
        })
        .catch(error => {
            console.error('Export error:', error);
            showToast('Export failed. Please try again.', 'error');
        })
        .finally(() => {
            // Restore button state
            button.innerHTML = originalText;
            button.disabled = false;
        });
    }
    function submitBulkUpdate(e) {
        e.preventDefault();
        const ids = getSelectedOrderIds();
        const newStatus = document.getElementById('bulk_new_status').value;
        if (ids.length === 0) { showToast('Select orders to update', 'error'); return false; }
        if (!newStatus) { showToast('Select a new status', 'error'); return false; }
        if (!confirm(`Update ${ids.length} order(s) to ${newStatus}?`)) return false;

        fetch('pages/bulk_update_status.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ order_ids: ids, status: newStatus })
        }).then(r => {
            console.log('Response status:', r.status);
            return r.json();
        }).then(data => {
            console.log('Response data:', data);
            if (data.success) {
                showToast(data.message, 'success');
                setTimeout(() => location.reload(), 800);
            } else {
                showToast(data.message || 'Failed to update', 'error');
            }
        }).catch(error => {
            console.error('Fetch error:', error);
            showToast('Request failed: ' + error.message, 'error');
        });
        return false;
    }
    function submitBulkUpdateByRange(e) {
        e.preventDefault();
        const form = e.target;
        const date_from = form.date_from.value;
        const date_to = form.date_to.value;
        const time_from = form.time_from.value;
        const time_to = form.time_to.value;
        const current_status = form.current_status.value;
        const new_status = form.new_status.value;
        const agent_filter = form.agent_filter.value;
        const network_type = form.network_type.value;
        if (!date_from || !date_to || !new_status) { showToast('Missing required fields', 'error'); return false; }
        const start = date_from + (time_from ? (' ' + time_from) : ' 00:00');
        const end = date_to + (time_to ? (' ' + time_to) : ' 23:59');
        if (!confirm(`Update orders between\n${start} and ${end}\nto ${new_status}?`)) return false;

        fetch('pages/bulk_update_status_by_time.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ start, end, status: new_status, current_status, agent_filter, network_type })
        }).then(r => r.json()).then(data => {
            if (data.success) {
                showToast(data.message, 'success');
                setTimeout(() => location.reload(), 800);
            } else {
                showToast(data.message || 'Failed to update by range', 'error');
            }
        }).catch(() => showToast('Request failed', 'error'));
        return false;
    }

    // Export all orders function
    function exportAllOrders() {
        const table = $('#allOrdersTable').DataTable();
        const data = table.rows({search: 'applied'}).data();
        
        if (data.length === 0) {
            showToast('No orders to export', 'error');
            return;
        }
        
        // Create CSV content
        let csv = 'ID,Status,Source,Store Owner,Package Size,Amount,Created At\n';
        
        data.each(function(row) {
            const id = $(row[0]).text().trim();
            const status = $(row[1]).text().trim();
            const source = $(row[2]).text().trim();
            const storeOwner = $(row[3]).text().trim();
            const packageSize = $(row[4]).text().trim();
            const amount = $(row[5]).text().trim();
            const createdAt = $(row[6]).text().trim();
            
            csv += `"${id}","${status}","${source}","${storeOwner}","${packageSize}","${amount}","${createdAt}"\n`;
        });
        
        // Create download link
        const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        const url = URL.createObjectURL(blob);
        link.setAttribute('href', url);
        link.setAttribute('download', 'all_orders_' + new Date().toISOString().split('T')[0] + '.csv');
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        showToast(`Successfully exported ${data.length} order(s)`, 'success');
    }
    
    // Initialize DataTables when page loads
    document.addEventListener('DOMContentLoaded', function() {
        console.log('Orders Management page loaded - initializing DataTables...');
        
        setTimeout(function() {
            initializeDataTables();
        }, 500);
    });
    
    // DataTables initialization function
    function initializeDataTables() {
        console.log('Initializing DataTables for both tables...');
        
        // Check if jQuery and DataTables are available
        if (typeof $ === 'undefined') {
            console.error('jQuery is not loaded');
            return;
        }
        
        if (typeof $.fn.DataTable === 'undefined') {
            console.error('DataTables is not loaded');
            return;
        }
        
        // Initialize DataTables for Regular Orders Table
        const regularOrdersTable = $('#regularOrdersTable');
        if (regularOrdersTable.length > 0) {
            if ($.fn.DataTable.isDataTable('#regularOrdersTable')) {
                $('#regularOrdersTable').DataTable().destroy();
            }
            
            try {
                $('#regularOrdersTable').DataTable({
                    responsive: true,
                    pageLength: 25,
                    order: [[7, 'desc']], // Order by Created At column (index 7)
                    dom: 'Bfrtip',
                    language: {
                        search: "Search:",
                        lengthMenu: "Show _MENU_ entries",
                        info: "Showing _START_ to _END_ of _TOTAL_ entries",
                        paginate: {
                            first: "First",
                            last: "Last",
                            next: "Next",
                            previous: "Previous"
                        }
                    },
                    buttons: [
                        {
                            extend: 'excel',
                            text: 'Export to Excel',
                            className: 'bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded'
                        }
                    ]
                });
                console.log('Regular Orders DataTable initialized successfully');
            } catch (error) {
                console.error('Error initializing Regular Orders DataTable:', error);
            }
        }
        
        // Initialize DataTables for Agent Orders Table
        const agentOrdersTable = $('#agentOrdersTable');
        if (agentOrdersTable.length > 0) {
            if ($.fn.DataTable.isDataTable('#agentOrdersTable')) {
                $('#agentOrdersTable').DataTable().destroy();
            }
            
            try {
                $('#agentOrdersTable').DataTable({
                    responsive: true,
                    pageLength: 25,
                    order: [[8, 'desc']], // Order by Created At column (index 8)
                    dom: 'Bfrtip',
                    language: {
                        search: "Search:",
                        lengthMenu: "Show _MENU_ entries",
                        info: "Showing _START_ to _END_ of _TOTAL_ entries",
                        paginate: {
                            first: "First",
                            last: "Last",
                            next: "Next",
                            previous: "Previous"
                        }
                    },
                    buttons: [
                        {
                            extend: 'excel',
                            text: 'Export to Excel',
                            className: 'bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded'
                        }
                    ]
                });
                console.log('Agent Orders DataTable initialized successfully');
            } catch (error) {
                console.error('Error initializing Agent Orders DataTable:', error);
            }
        }
    }
    </script>