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

$adminAuth = new AdminAuth($conn);

// Check if admin is authenticated
$adminAuth->requireAuth('admin_login.php');

// Handle Add Agent form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] == 'add_agent') {
    // Sanitize and validate input
    $username = trim($_POST['username']);
    $email = trim($_POST['email']);
    $default_password = trim($_POST['default_password']);
    $balance = floatval($_POST['balance']);
    $role = trim($_POST['role']);

    // Ensure required fields are not empty
    if ($username === '' || $email === '' || $default_password === '' || $role === '') {
        $message = "Please fill in all required fields.";
        $message_type = "error";
    }
    // Validate email format
    elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $message = "Please enter a valid email address.";
        $message_type = "error";
    }
    // Validate role - only 'agent' is allowed
    elseif ($role !== 'agent') {
        $message = "Please select a valid role. Only 'agent' role is supported.";
        $message_type = "error";
    }
    else {
        // Check if username already exists
        $check_username_stmt = $conn->prepare("SELECT id FROM agents WHERE username = ?");
        $check_username_stmt->bind_param("s", $username);
        $check_username_stmt->execute();
        $username_result = $check_username_stmt->get_result();
        
        if ($username_result->num_rows > 0) {
            $check_username_stmt->close();
            $message = "Username '$username' already exists. Please choose a different username.";
            $message_type = "error";
        }
        else {
            $check_username_stmt->close();

            // Check if email already exists
            $check_email_stmt = $conn->prepare("SELECT id FROM agents WHERE email = ?");
            $check_email_stmt->bind_param("s", $email);
            $check_email_stmt->execute();
            $email_result = $check_email_stmt->get_result();
            
            if ($email_result->num_rows > 0) {
                $check_email_stmt->close();
                $message = "Email '$email' is already registered. Please use a different email address.";
                $message_type = "error";
            }
            else {
                $check_email_stmt->close();

                // Hash the default password
                $password_hash = password_hash($default_password, PASSWORD_BCRYPT);

                // Prepare insert statement to prevent SQL injection
                $stmt = $conn->prepare("INSERT INTO agents (username, email, password_hash, balance, role, created_at) VALUES (?, ?, ?, ?, ?, NOW())");
                $stmt->bind_param("sssds", $username, $email, $password_hash, $balance, $role);

                if ($stmt->execute()) {
                    $message = "Agent '$username' has been successfully added!";
                    $message_type = "success";
                    // Close the modal after successful submission
                    echo "<script>setTimeout(() => { if (typeof closeAddAgentForm === 'function') closeAddAgentForm(); }, 1000);</script>";
                } else {
                    $message = "Database error occurred. Please try again.";
                    $message_type = "error";
                }

                $stmt->close();
            }
        }
    }
}

// Get admin info
$admin_id = $_SESSION['admin_id'];
$admin_username = $_SESSION['admin_username'];

// Get system statistics
$stats = [];

// Total agents
$result = mysqli_query($conn, "SELECT COUNT(*) as total FROM agents");
$stats['total_agents'] = mysqli_fetch_assoc($result)['total'];

// Total orders (all orders + agent orders)
$result = mysqli_query($conn, "SELECT COUNT(*) as total FROM orders");
$stats['total_regular_orders'] = mysqli_fetch_assoc($result)['total'];

$result = mysqli_query($conn, "SELECT COUNT(*) as total FROM agent_orders");
$stats['total_agent_orders'] = mysqli_fetch_assoc($result)['total'];

$stats['total_orders'] = $stats['total_regular_orders'] + $stats['total_agent_orders'];

// Total revenue from agent_orders table only
$result = mysqli_query($conn, "SELECT SUM(amount) as total FROM agent_orders WHERE status = 'delivered'");
$stats['total_revenue'] = mysqli_fetch_assoc($result)['total'] ?? 0;

// Pending orders (excluding databundle orders)
$result = mysqli_query($conn, "SELECT COUNT(*) as total FROM orders o LEFT JOIN pending_databundle_orders pdo ON o.order_reference = pdo.reference WHERE o.status = 'pending' AND pdo.reference IS NULL");
$stats['pending_orders'] = mysqli_fetch_assoc($result)['total'];

// Databundle statistics
$result = mysqli_query($conn, "SELECT COUNT(*) as total FROM pending_databundle_orders");
$stats['pending_databundle_orders'] = mysqli_fetch_assoc($result)['total'];

$result = mysqli_query($conn, "SELECT COUNT(*) as total FROM verified_databundle_orders");
$stats['verified_databundle_orders'] = mysqli_fetch_assoc($result)['total'];

$result = mysqli_query($conn, "SELECT COUNT(*) as total FROM completed_databundle_orders");
$stats['completed_databundle_orders'] = mysqli_fetch_assoc($result)['total'];

$result = mysqli_query($conn, "SELECT COUNT(*) as total FROM processing_databundle_orders");
$stats['processing_databundle_orders'] = mysqli_fetch_assoc($result)['total'];

// Total sum of all store owners' balances
$result = mysqli_query($conn, "
    SELECT COALESCE(SUM(a.balance), 0) as total_balance 
    FROM stores s 
    INNER JOIN agents a ON s.owner_id = a.id
");
$stats['total_store_owners_balance'] = mysqli_fetch_assoc($result)['total_balance'] ?? 0;

// Admin Daily Stats
// SECURITY FIX: Use prepared statements to prevent SQL injection
$today = date('Y-m-d');
$yesterday = date('Y-m-d', strtotime('-1 day'));

// Today's agent orders count
$stmt = $conn->prepare("SELECT COUNT(*) as total FROM agent_orders WHERE DATE(created_at) = ?");
$stmt->bind_param("s", $today);
$stmt->execute();
$result = $stmt->get_result();
$daily_stats['today_agent_orders'] = $result->fetch_assoc()['total'];
$stmt->close();

$daily_stats['today_total_orders'] = $daily_stats['today_agent_orders'];

// Yesterday's agent orders for comparison
$stmt = $conn->prepare("SELECT COUNT(*) as total FROM agent_orders WHERE DATE(created_at) = ?");
$stmt->bind_param("s", $yesterday);
$stmt->execute();
$result = $stmt->get_result();
$daily_stats['yesterday_agent_orders'] = $result->fetch_assoc()['total'];
$stmt->close();

$daily_stats['yesterday_total_orders'] = $daily_stats['yesterday_agent_orders'];

// Today's delivered data from agent orders
$stmt = $conn->prepare("SELECT SUM(CAST(package_size AS UNSIGNED)) as total_gb FROM agent_orders WHERE DATE(created_at) = ? AND status = 'delivered'");
$stmt->bind_param("s", $today);
$stmt->execute();
$result = $stmt->get_result();
$daily_stats['today_agent_delivered_gb'] = round($result->fetch_assoc()['total_gb'] ?? 0, 2);
$stmt->close();

$daily_stats['today_total_delivered_gb'] = $daily_stats['today_agent_delivered_gb'];

// Today's total revenue from agent_orders table only
$stmt = $conn->prepare("SELECT SUM(amount) as total FROM agent_orders WHERE DATE(created_at) = ? AND status = 'delivered'");
$stmt->bind_param("s", $today);
$stmt->execute();
$result = $stmt->get_result();
$daily_stats['today_agent_revenue'] = $result->fetch_assoc()['total'] ?? 0;
$stmt->close();

$daily_stats['today_total_revenue'] = $daily_stats['today_agent_revenue'];

// Pending agent orders today
$stmt = $conn->prepare("SELECT COUNT(*) as total FROM agent_orders WHERE DATE(created_at) = ? AND status = 'pending'");
$stmt->bind_param("s", $today);
$stmt->execute();
$result = $stmt->get_result();
$daily_stats['today_pending_orders'] = $result->fetch_assoc()['total'];
$stmt->close();

// Get network-specific statistics
// SECURITY FIX: Use prepared statements even though network comes from hardcoded array
$network_stats = [];
$networks = ['mtn', 'telecel', 'airtel_tigo'];
$tables = ['pending_databundle_orders', 'verified_databundle_orders', 'processing_databundle_orders', 'completed_databundle_orders', 'cleanup_databundle_orders'];
$keys = ['pending', 'verified', 'processing', 'completed', 'cleanup'];

foreach ($networks as $network) {
    $network_stats[$network] = [];
    foreach ($tables as $index => $table) {
        $stmt = $conn->prepare("SELECT COUNT(*) as count FROM `$table` WHERE network_type = ?");
        $stmt->bind_param("s", $network);
        $stmt->execute();
        $result = $stmt->get_result();
        $network_stats[$network][$keys[$index]] = $result->fetch_assoc()['count'];
        $stmt->close();
    }
}

// Get active tab from URL parameter
$active_tab = isset($_GET['tab']) ? $_GET['tab'] : 'overview';

// Get all store owners
$storeManager = new StoreManager($conn);
$allStores = $storeManager->getAllStores(1000, 0); // Get all stores

// Get detailed stats for each store
$storeOwners = [];
foreach ($allStores as $store) {
    $storeStats = $storeManager->getStoreStats($store['id']);
    
    // Get owner balance
    $ownerBalanceStmt = $conn->prepare("SELECT balance, username, email, phone FROM agents WHERE id = ?");
    $ownerBalanceStmt->bind_param("i", $store['owner_id']);
    $ownerBalanceStmt->execute();
    $ownerResult = $ownerBalanceStmt->get_result();
    $ownerData = $ownerResult->fetch_assoc();
    $ownerBalanceStmt->close();
    
    // Get agents for this store
    $agents = $storeManager->getStoreAgents($store['id']);
    
    $storeOwners[] = [
        'store_id' => $store['id'],
        'store_name' => $store['store_name'],
        'store_slug' => $store['store_slug'],
        'store_status' => $store['status'],
        'owner_id' => $store['owner_id'],
        'owner_username' => $ownerData['username'] ?? 'N/A',
        'owner_email' => $ownerData['email'] ?? 'N/A',
        'owner_phone' => $ownerData['phone'] ?? 'N/A',
        'owner_balance' => floatval($ownerData['balance'] ?? 0),
        'total_agents' => $storeStats['total_agents'],
        'total_orders' => $storeStats['total_orders'],
        'total_revenue' => $storeStats['total_revenue'],
        'agent_orders' => $storeStats['agent_orders'],
        'customer_orders' => $storeStats['customer_orders'],
        'created_at' => $store['created_at'] ?? null,
        'agents' => $agents // Include agents data
    ];
}

// Note: Regular customer orders from bundle.php (formerly databundle.php) are now managed through the orders system
// Only agent orders are shown in this orders management section

// Agent orders filters (GET)
$status_filter = isset($_GET['status']) ? trim($_GET['status']) : '';
$agent_filter = isset($_GET['agent']) ? trim($_GET['agent']) : '';
$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']) : '';

// Detect timestamp column
$agentTimestampColumn = 'created_at';
$checkAgentTs = mysqli_query($conn, "SHOW COLUMNS FROM agent_orders LIKE 'created_at'");
if (!$checkAgentTs || mysqli_num_rows($checkAgentTs) === 0) {
    $agentTimestampColumn = 'order_date';
}
if ($checkAgentTs) { mysqli_free_result($checkAgentTs); }

function buildAgentOrdersQuery($network, $agentTimestampColumn, $status_filter, $agent_filter, $date_from, $time_from, $date_to, $time_to) {
    $where = ["ao.network_type = '" . mysqli_real_escape_string($GLOBALS['conn'], $network) . "'"];
    if ($status_filter !== '') {
        $where[] = "ao.status = '" . mysqli_real_escape_string($GLOBALS['conn'], $status_filter) . "'";
    }
    if ($agent_filter !== '') {
        $safe = mysqli_real_escape_string($GLOBALS['conn'], $agent_filter);
        $where[] = "a.username LIKE '%{$safe}%'";
    }
    if ($date_from !== '') {
        $from = $date_from . ($time_from !== '' ? (" " . $time_from . ":00") : ' 00:00:00');
        $where[] = "ao." . $agentTimestampColumn . " >= '" . mysqli_real_escape_string($GLOBALS['conn'], $from) . "'";
    }
    if ($date_to !== '') {
        $to = $date_to . ($time_to !== '' ? (" " . $time_to . ":59") : ' 23:59:59');
        $where[] = "ao." . $agentTimestampColumn . " <= '" . mysqli_real_escape_string($GLOBALS['conn'], $to) . "'";
    }
    $whereSql = implode(' AND ', $where);
    return "SELECT ao.*, COALESCE(a.username, CONCAT('Agent #', ao.agent_id), 'Unknown Agent') as agent_name
            FROM agent_orders ao
            LEFT JOIN agents a ON ao.agent_id = a.id
            WHERE {$whereSql}
            ORDER BY ao." . $agentTimestampColumn . " DESC";
}

$agent_mtn_orders_query = buildAgentOrdersQuery('mtn', $agentTimestampColumn, $status_filter, $agent_filter, $date_from, $time_from, $date_to, $time_to);
$agent_mtn_orders_result = mysqli_query($conn, $agent_mtn_orders_query);

$agent_telecel_orders_query = buildAgentOrdersQuery('telecel', $agentTimestampColumn, $status_filter, $agent_filter, $date_from, $time_from, $date_to, $time_to);
$agent_telecel_orders_result = mysqli_query($conn, $agent_telecel_orders_query);

$agent_airtel_tigo_orders_query = buildAgentOrdersQuery('airtel_tigo', $agentTimestampColumn, $status_filter, $agent_filter, $date_from, $time_from, $date_to, $time_to);
$agent_airtel_tigo_orders_result = mysqli_query($conn, $agent_airtel_tigo_orders_query);

// Also keep the general query for total count
$agent_orders_query = "SELECT ao.*, COALESCE(a.username, CONCAT('Agent #', ao.agent_id), 'Unknown Agent') as agent_name FROM agent_orders ao LEFT JOIN agents a ON ao.agent_id = a.id ORDER BY ao.created_at DESC";
$agent_orders_result = mysqli_query($conn, $agent_orders_query);

// AFA registration functionality removed per requirements

// Customer packages functionality removed per requirements


// Balance history functionality moved to dedicated page

// ===========================================
// AGENT & SUPER AGENT STATISTICS
// ===========================================

// Get agent statistics
$agent_stats = [];

// Total agents by role
$result = mysqli_query($conn, "SELECT role, COUNT(*) as count FROM agents GROUP BY role");
while ($row = mysqli_fetch_assoc($result)) {
    $agent_stats['total_' . $row['role']] = $row['count'];
}

// Total orders by agent role (from agent_orders table)
$result = mysqli_query($conn, "
    SELECT a.role, COUNT(ao.id) as total_orders
    FROM agents a
    LEFT JOIN agent_orders ao ON a.id = ao.agent_id
    GROUP BY a.role
");
while ($row = mysqli_fetch_assoc($result)) {
    $agent_stats['total_orders_' . $row['role']] = $row['total_orders'];
}

// Today's orders by agent role
$result = mysqli_query($conn, "
    SELECT a.role, COUNT(ao.id) as today_orders
    FROM agents a
    LEFT JOIN agent_orders ao ON a.id = ao.agent_id AND DATE(ao.created_at) = '$today'
    GROUP BY a.role
");
while ($row = mysqli_fetch_assoc($result)) {
    $agent_stats['today_orders_' . $row['role']] = $row['today_orders'];
}

// Last order timestamp by agent role
$result = mysqli_query($conn, "
    SELECT a.role, MAX(ao.created_at) as last_order_time
    FROM agents a
    LEFT JOIN agent_orders ao ON a.id = ao.agent_id
    GROUP BY a.role
");
while ($row = mysqli_fetch_assoc($result)) {
    $agent_stats['last_order_' . $row['role']] = $row['last_order_time'];
}



// Helper function to format error messages
function formatErrorMessage($error_msg, $error_type, $remaining_balance, $api_endpoint) {
    $network_name = strpos($api_endpoint, 'megabytehub.com') !== false ? 'MTN API' : 'External API';
    
    switch ($error_type) {
        case 'insufficient_balance':
            return "❌ Insufficient balance in $network_name" . ($remaining_balance ? " (Balance: $remaining_balance)" : "");
        case 'incorrect_details':
            return "❌ Incorrect details provided to $network_name";
        case 'connection_error':
            return "❌ Connection error with $network_name";
        case 'authentication_error':
            return "❌ Authentication failed with $network_name";
        case 'authorization_error':
            return "❌ Authorization failed with $network_name";
        case 'server_error':
            return "❌ Server error in $network_name";
        case 'api_error':
            return "❌ API error from $network_name: $error_msg";
        default:
            return "❌ Error from $network_name: $error_msg";
    }
}

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['verify_payment'])) {
        // Handle payment verification
        $selected_orders = $_POST['selected_orders'] ?? [];
        if (!empty($selected_orders)) {
            foreach ($selected_orders as $order_id) {
                // Move from pending to verified
                $order_id = intval($order_id);
                $result = mysqli_query($conn, "SELECT * FROM pending_databundle_orders WHERE id = $order_id");
                if ($row = mysqli_fetch_assoc($result)) {
                    // Insert into verified table
                    $stmt = mysqli_prepare($conn, "INSERT INTO verified_databundle_orders (momo_name, momo_number, package, package_mb, amount_paid, reference, megabytes, received, network_type, external_transaction_id, api_response_data, payment_verified_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");
                    mysqli_stmt_bind_param($stmt, "ssssdssisss", $row['momo_name'], $row['momo_number'], $row['package'], $row['package_mb'], $row['amount_paid'], $row['reference'], $row['megabytes'], $row['received'], $row['network_type'], $row['external_transaction_id'], $row['api_response_data']);
                    mysqli_stmt_execute($stmt);
                    
                    // Delete from pending table
                    mysqli_query($conn, "DELETE FROM pending_databundle_orders WHERE id = $order_id");
                }
            }
            $message = "Orders moved to verified successfully!";
            $message_type = "success";
        }
    }
    
    
    if (isset($_POST['process_orders'])) {
        // Handle move from verified to processing with API calls
        $selected_orders = $_POST['selected_orders'] ?? [];
        if (!empty($selected_orders)) {
            $successful_orders = 0;
            $failed_orders = 0;
            $error_messages = [];
            
            foreach ($selected_orders as $order_id) {
                $order_id = intval($order_id);
                $result = mysqli_query($conn, "SELECT * FROM verified_databundle_orders WHERE id = $order_id");
                if ($row = mysqli_fetch_assoc($result)) {
                    // Call appropriate API based on network type
                    $apiService = new ExternalAPIService($row['network_type']);
                    $capacity = $apiService->convertPackageSize($row['package']);
                    $cleanPhone = $apiService->validatePhoneNumber($row['momo_number']);
                    
                    // Make API call
                    $apiResponse = $apiService->purchaseData($cleanPhone, $row['network_type'], $capacity);
                    
                    if ($apiResponse['success']) {
                        // API call successful - move to processing
                        $externalApiReference = isset($apiResponse['data']['transactionReference']) ? $apiResponse['data']['transactionReference'] : null;
                        
                        // Get the data website's purchase ID (this is the order ID from data website)
                        $purchaseId = isset($apiResponse['data']['purchaseId']) ? $apiResponse['data']['purchaseId'] : null;
                        
                        // Use the purchase ID directly as the transaction ID
                        $dataWebsiteTransactionId = $purchaseId ? (string)$purchaseId : null;
                        
                        $api_response_data = json_encode($apiResponse['data']);
                        
                        $stmt = mysqli_prepare($conn, "INSERT INTO processing_databundle_orders (original_id, verified_id, momo_name, momo_number, package, package_mb, amount_paid, reference, megabytes, received, network_type, external_transaction_id, api_response_data, payment_verified_at, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                        mysqli_stmt_bind_param($stmt, "iissssdssisssss", $row['original_id'], $row['id'], $row['momo_name'], $row['momo_number'], $row['package'], $row['package_mb'], $row['amount_paid'], $row['reference'], $row['megabytes'], $row['received'], $row['network_type'], $dataWebsiteTransactionId, $api_response_data, $row['payment_verified_at'], $row['created_at']);
                        mysqli_stmt_execute($stmt);
                        
                        // Update main orders table with data website transaction ID
                        $updateMainOrderStmt = mysqli_prepare($conn, "UPDATE orders SET external_transaction_id = ?, external_reference = ?, api_response_data = ?, status_updated_at = NOW() WHERE order_reference = ?");
                        mysqli_stmt_bind_param($updateMainOrderStmt, "ssss", $dataWebsiteTransactionId, $externalApiReference, $api_response_data, $row['reference']);
                        mysqli_stmt_execute($updateMainOrderStmt);
                        mysqli_stmt_close($updateMainOrderStmt);
                        
                        // Delete from verified table
                        mysqli_query($conn, "DELETE FROM verified_databundle_orders WHERE id = $order_id");
                        $successful_orders++;
                        
                        // Log successful API call
                    } else {
                        // API call failed - keep in verified table but log error
                        $error_msg = $apiResponse['error'];
                        $error_type = isset($apiResponse['error_type']) ? $apiResponse['error_type'] : 'unknown_error';
                        $remaining_balance = isset($apiResponse['remaining_balance']) ? $apiResponse['remaining_balance'] : null;
                        $api_endpoint = $apiService->getBaseUrl();
                        
                        // Format error message based on error type
                        $formatted_error = formatErrorMessage($error_msg, $error_type, $remaining_balance, $api_endpoint);
                        
                        // Update verified order with error information
                        $error_data = json_encode([
                            'error' => $error_msg,
                            'error_type' => $error_type,
                            'formatted_error' => $formatted_error,
                            'remaining_balance' => $remaining_balance,
                            'attempted_at' => date('Y-m-d H:i:s'),
                            'api_endpoint' => $api_endpoint,
                            'network_routed' => $row['network_type']
                        ]);
                        
                        $updateStmt = mysqli_prepare($conn, "UPDATE verified_databundle_orders SET api_response_data = ? WHERE id = ?");
                        mysqli_stmt_bind_param($updateStmt, "si", $error_data, $order_id);
                        mysqli_stmt_execute($updateStmt);
                        
                        $failed_orders++;
                        $error_messages[] = "Order {$row['reference']} ({$row['network_type']}): $formatted_error";
                        
                        // Log failed API call
                    }
                }
            }
            
            // Prepare success message
            if ($successful_orders > 0 && $failed_orders == 0) {
                $message = "$successful_orders orders processed successfully!";
                $message_type = "success";
            } elseif ($successful_orders > 0 && $failed_orders > 0) {
                $message = "$successful_orders orders processed successfully, $failed_orders failed. Check logs for details.";
                $message_type = "warning";
            } else {
                $message = "All $failed_orders orders failed to process. Check logs for details.";
                $message_type = "error";
            }
            
            // Add specific error messages if any
            if (!empty($error_messages)) {
                $message .= "<br><br>Error details:<br>" . implode("<br>", array_slice($error_messages, 0, 5));
                if (count($error_messages) > 5) {
                    $message .= "<br>... and " . (count($error_messages) - 5) . " more errors";
                }
            }
        }
    }
    
    if (isset($_POST['deliver_orders'])) {
        // Handle move from processing to completed
        $selected_orders = $_POST['selected_orders'] ?? [];
        if (!empty($selected_orders)) {
            foreach ($selected_orders as $order_id) {
                $order_id = intval($order_id);
                $result = mysqli_query($conn, "SELECT * FROM processing_databundle_orders WHERE id = $order_id");
                if ($row = mysqli_fetch_assoc($result)) {
                    // Insert into completed table
                    $stmt = mysqli_prepare($conn, "INSERT INTO completed_databundle_orders (original_id, verified_id, momo_name, momo_number, package, package_mb, amount_paid, reference, megabytes, received, network_type, external_transaction_id, api_response_data, status, payment_verified_at, processed_at, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'delivered', ?, NOW(), ?)");
                    mysqli_stmt_bind_param($stmt, "iissssdssisssss", $row['original_id'], $row['verified_id'], $row['momo_name'], $row['momo_number'], $row['package'], $row['package_mb'], $row['amount_paid'], $row['reference'], $row['megabytes'], $row['received'], $row['network_type'], $row['external_transaction_id'], $row['api_response_data'], $row['payment_verified_at'], $row['created_at']);
                    mysqli_stmt_execute($stmt);
                    
                    // Update main orders table status to delivered
                    $updateMainOrderStmt = mysqli_prepare($conn, "UPDATE orders SET status = 'delivered', status_updated_at = NOW() WHERE order_reference = ?");
                    mysqli_stmt_bind_param($updateMainOrderStmt, "s", $row['reference']);
                    mysqli_stmt_execute($updateMainOrderStmt);
                    mysqli_stmt_close($updateMainOrderStmt);
                    
                    // Delete from processing table
                    mysqli_query($conn, "DELETE FROM processing_databundle_orders WHERE id = $order_id");
                }
            }
            $message = "Orders marked as delivered successfully!";
            $message_type = "success";
        }
    }
}





// Deprecated: logout is handled globally via router; removing local handler
if (false && isset($_GET['logout'])) {
    session_destroy();
    header('Location: admin_login.php');
    exit();
}

// Handle success/error messages
$message = '';
$message_type = '';

if (isset($_GET['message']) && isset($_GET['message_type'])) {
    $message = $_GET['message'];
    $message_type = $_GET['message_type'];
} elseif (isset($_GET['added']) && $_GET['added'] == '1') {
    $message = 'Agent added successfully!';
    $message_type = 'success';
} elseif (isset($_GET['deleted']) && $_GET['deleted'] == '1') {
    $message = 'Agent deleted successfully!';
    $message_type = 'success';
} elseif (isset($_GET['success']) && $_GET['success'] == '1') {
    $message = 'Balance updated successfully!';
    $message_type = 'success';
} elseif (isset($_GET['error'])) {
    switch ($_GET['error']) {
        case 'missing_fields':
            $message = 'Please fill in all required fields.';
            break;
        case 'invalid_email':
            $message = 'Please enter a valid email address.';
            break;
        case 'invalid_role':
            $message = 'Please select a valid role.';
            break;
        case 'username_exists':
            $username = isset($_GET['username']) ? htmlspecialchars($_GET['username']) : 'this username';
            $message = "Username '{$username}' already exists. Please choose a different username.";
            break;
        case 'email_exists':
            $email = isset($_GET['email']) ? htmlspecialchars($_GET['email']) : 'this email';
            $message = "Email '{$email}' is already registered. Please use a different email address.";
            break;
        case 'duplicate_account':
            $message = 'An account with this username or email already exists.';
            break;
        case 'db':
            $message = 'Database error. Please try again.';
            break;
        case '1':
            $message = 'An error occurred. Please try again.';
            break;
        case 'agent_not_found':
            $message = 'Agent not found or already deleted.';
            break;
        case 'invalid_id':
            $message = 'Invalid agent ID provided.';
            break;
        default:
            $message = 'An error occurred. Please try again.';
    } 
    $message_type = 'error';
}

// Set page variables for header
$page_title = 'Admin Dashboard';
$page_description = 'Manage agents, orders, pricing, and system configuration for your data bundle business';
?>

<!-- Message Display Area -->
<?php if (!empty($message)): ?>
<div class="fixed top-4 right-4 z-50 max-w-md">
    <div class="bg-<?= $message_type === 'success' ? 'green' : ($message_type === 'warning' ? 'yellow' : 'red') ?>-50 border border-<?= $message_type === 'success' ? 'green' : ($message_type === 'warning' ? 'yellow' : 'red') ?>-200 text-<?= $message_type === 'success' ? 'green' : ($message_type === 'warning' ? 'yellow' : 'red') ?>-700 px-4 py-3 rounded-xl shadow-lg flex items-center">
        <i class="fas fa-<?= $message_type === 'success' ? 'check-circle' : ($message_type === 'warning' ? 'exclamation-triangle' : 'exclamation-circle') ?> mr-3"></i>
        <span><?= htmlspecialchars($message) ?></span>
        <button onclick="this.parentElement.parentElement.remove()" class="ml-3 text-<?= $message_type === 'success' ? 'green' : ($message_type === 'warning' ? 'yellow' : 'red') ?>-500 hover:text-<?= $message_type === 'success' ? 'green' : ($message_type === 'warning' ? 'yellow' : 'red') ?>-700">
            <i class="fas fa-times"></i>
        </button>
    </div>
</div>
<script>
// Auto-hide message after 5 seconds
setTimeout(() => {
    const messageDiv = document.querySelector('.fixed.top-4.right-4');
    if (messageDiv) {
        messageDiv.style.opacity = '0';
        messageDiv.style.transform = 'translateX(100%)';
        setTimeout(() => messageDiv.remove(), 300);
    }
}, 5000);
</script>
<?php endif; ?>

<!-- Admin Daily Stats Section -->
    <div class="bg-gradient-to-r from-blue-600 to-purple-600 text-white p-6">
        <div class="max-w-7xl mx-auto">
            <div class="flex items-center justify-between mb-6">
                <div>
                    <h2 class="text-2xl font-bold">Admin Account Stats</h2>
                    <p class="text-blue-100"><?= date('l, F j, Y') ?></p>
                </div>
                <div class="text-right">
                    <p class="text-sm text-blue-100">Last Updated</p>
                    <p class="text-lg font-semibold"><?= date('g:i A', time()) ?></p>
                </div>
            </div>

            <!-- Stats Grid -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                <!-- Today's Total Orders -->
                <div class="backdrop-blur-sm rounded-xl p-6 border border-gray-700/50 hover:border-gray-600/70 transition-all duration-300 shadow-lg hover:shadow-xl group" style="background-color: #1F2937;">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-300 text-sm font-medium group-hover:text-white transition-colors">Today's Orders</p>
                            <p class="text-3xl font-bold text-white group-hover:text-blue-400 transition-colors"><?= number_format($daily_stats['today_total_orders']) ?></p>
                            <div class="flex items-center mt-2">
                                <span class="text-xs text-gray-400 group-hover:text-gray-300 transition-colors">
                                    Agent Orders: <?= number_format($daily_stats['today_agent_orders']) ?>
                                </span>
                            </div>
                        </div>
                        <div class="w-12 h-12 bg-blue-600/20 rounded-full flex items-center justify-center group-hover:bg-blue-600/30 transition-all duration-300">
                            <i class="fas fa-shopping-cart text-blue-400 text-xl group-hover:text-blue-300 transition-colors"></i>
                        </div>
                    </div>
                </div>

                <!-- Data Delivered Today -->
                <div class="backdrop-blur-sm rounded-xl p-6 border border-gray-700/50 hover:border-gray-600/70 transition-all duration-300 shadow-lg hover:shadow-xl group" style="background-color: #1F2937;">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-300 text-sm font-medium group-hover:text-white transition-colors">Data Delivered</p>
                            <p class="text-3xl font-bold text-white group-hover:text-green-400 transition-colors"><?= number_format($daily_stats['today_total_delivered_gb'], 2) ?> GB</p>
                            <div class="flex items-center mt-2">
                                <span class="text-xs text-gray-400 group-hover:text-gray-300 transition-colors">
                                    Agent Data: <?= number_format($daily_stats['today_agent_delivered_gb'], 2) ?> GB
                                </span>
                            </div>
                        </div>
                        <div class="w-12 h-12 bg-green-600/20 rounded-full flex items-center justify-center group-hover:bg-green-600/30 transition-all duration-300">
                            <i class="fas fa-database text-green-400 text-xl group-hover:text-green-300 transition-colors"></i>
                        </div>
                    </div>
                </div>

                <!-- Today's Revenue -->
                <div class="backdrop-blur-sm rounded-xl p-6 border border-gray-700/50 hover:border-gray-600/70 transition-all duration-300 shadow-lg hover:shadow-xl group" style="background-color: #1F2937;">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-300 text-sm font-medium group-hover:text-white transition-colors">Today's Revenue</p>
                            <p class="text-3xl font-bold text-white group-hover:text-yellow-400 transition-colors">GHS <?= number_format($daily_stats['today_total_revenue'], 2) ?></p>
                            <div class="flex items-center mt-2">
                        <span class="text-xs text-gray-400 group-hover:text-gray-300 transition-colors">
                            Total cost of delivered orders today
                        </span>
                            </div>
                        </div>
                        <div class="w-12 h-12 bg-yellow-600/20 rounded-full flex items-center justify-center group-hover:bg-yellow-600/30 transition-all duration-300">
                            <i class="fas fa-money-bill-wave text-yellow-400 text-xl group-hover:text-yellow-300 transition-colors"></i>
                        </div>
                    </div>
                </div>

                <!-- Active Agents -->
                <div class="backdrop-blur-sm rounded-xl p-6 border border-gray-700/50 hover:border-gray-600/70 transition-all duration-300 shadow-lg hover:shadow-xl group" style="background-color: #1F2937;">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-300 text-sm font-medium group-hover:text-white transition-colors">Agents</p>
                            <p class="text-3xl font-bold text-white group-hover:text-purple-400 transition-colors"><?php
                                $agents_total_res = mysqli_query($conn, "SELECT COUNT(*) as total FROM agents");
                                $agents_total = 0;
                                if ($agents_total_res) {
                                    $row = mysqli_fetch_assoc($agents_total_res);
                                    $agents_total = isset($row['total']) ? (int)$row['total'] : 0;
                                }
                                echo number_format($agents_total);
                            ?></p>
                            <div class="flex items-center mt-2">
                                <span class="text-xs text-gray-400 group-hover:text-gray-300 transition-colors">
                                    Pending Today: <?= number_format($daily_stats['today_pending_orders']) ?>
                                </span>
                            </div>
                        </div>
                        <div class="w-12 h-12 bg-purple-600/20 rounded-full flex items-center justify-center group-hover:bg-purple-600/30 transition-all duration-300">
                            <i class="fas fa-users text-purple-400 text-xl group-hover:text-purple-300 transition-colors"></i>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Comparison with Yesterday -->
            <div class="mt-6 backdrop-blur-sm rounded-xl p-4 border border-gray-700/30 hover:border-gray-600/40 transition-all duration-300" style="background-color: #1F2937;">
                <div class="flex items-center justify-between">
                    <div>
                        <h3 class="text-lg font-semibold text-white">Yesterday Comparison</h3>
                        <p class="text-blue-100 text-sm">Agent Orders: <?= number_format($daily_stats['yesterday_agent_orders']) ?></p>
                    </div>
                    <div class="text-right">
                        <?php 
                        $order_change = $daily_stats['today_total_orders'] - $daily_stats['yesterday_total_orders'];
                        $change_percent = $daily_stats['yesterday_total_orders'] > 0 ? round(($order_change / $daily_stats['yesterday_total_orders']) * 100, 1) : 0;
                        $is_positive = $order_change >= 0;
                        ?>
                        <p class="text-sm text-blue-100">Change from yesterday</p>
                        <p class="text-lg font-bold <?= $is_positive ? 'text-green-300' : 'text-red-300' ?>">
                            <?= $is_positive ? '+' : '' ?><?= number_format($order_change) ?> (<?= $is_positive ? '+' : '' ?><?= $change_percent ?>%)
                        </p>
                    </div>
                </div>
            </div>
        </div>
    </div>

        <!-- Tab Navigation -->
        <div class="p-6">
            <div class="flex space-x-1 bg-gray-800 p-1 rounded-xl mb-6">
                <button onclick="switchTab('overview')" class="tab-button flex-1 px-4 py-2 rounded-lg transition-all <?= $active_tab === 'overview' ? 'active' : '' ?>">
                    <i class="fas fa-tachometer-alt mr-2"></i>Overview
                </button>
                <button onclick="switchTab('orders')" class="tab-button flex-1 px-4 py-2 rounded-lg transition-all <?= $active_tab === 'orders' ? 'active' : '' ?>">
                    <i class="fas fa-clipboard-list mr-2"></i>Orders Management
                </button>
                
            </div>

            <!-- Overview Tab -->
            <div id="overview-tab" class="tab-content <?= $active_tab === 'overview' ? 'active' : '' ?>">
            <!-- Welcome Section -->
            <div class="cute-card mb-8">
                <div class="flex items-center justify-between">
                    <div>
                        <h1 class="text-2xl font-bold text-gray-100 mb-2">Welcome back, <?= htmlspecialchars($admin_username) ?>!</h1>
                        <p class="text-gray-300">Manage your data bundle platform from this central dashboard</p>
                    </div>
                    <div class="text-right">
                        <p class="text-sm text-gray-300">Last Login</p>
                        <p class="text-lg font-semibold text-gray-100"><?= date('M j, Y g:i A', time()) ?></p>
                    </div>
                </div>
            </div>

            <!-- Statistics Cards -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-6 mb-8">
                <div class="cute-card">
                    <div class="flex items-center">
                        <div class="w-12 h-12 bg-blue-600/20 rounded-xl flex items-center justify-center">
                            <i class="fas fa-users text-blue-400 text-xl"></i>
                        </div>
                        <div class="ml-4">
                            <p class="text-sm text-gray-300">Total Agents</p>
                            <p class="text-2xl font-bold text-gray-100"><?= number_format($stats['total_agents']) ?></p>
                        </div>
                    </div>
                </div>

                <div class="cute-card">
                    <div class="flex items-center">
                        <div class="w-12 h-12 bg-green-600/20 rounded-xl flex items-center justify-center">
                            <i class="fas fa-shopping-cart text-green-400 text-xl"></i>
                        </div>
                        <div class="ml-4">
                            <p class="text-sm text-gray-300">Total Orders</p>
                            <p class="text-2xl font-bold text-gray-100"><?= number_format($stats['total_orders']) ?></p>
                        </div>
                    </div>
                </div>

                <div class="cute-card">
                    <div class="flex items-center">
                        <div class="w-12 h-12 bg-purple-600/20 rounded-xl flex items-center justify-center">
                            <i class="fas fa-money-bill text-purple-400 text-xl"></i>
                        </div>
                        <div class="ml-4">
                            <p class="text-sm text-gray-300">Total Revenue</p>
                            <p class="text-2xl font-bold text-gray-100">GHC <?= number_format($stats['total_revenue'], 2) ?></p>
                        </div>
                    </div>
                </div>

                <div class="cute-card">
                    <div class="flex items-center">
                        <div class="w-12 h-12 bg-yellow-600/20 rounded-xl flex items-center justify-center">
                            <i class="fas fa-clock text-yellow-400 text-xl"></i>
                        </div>
                        <div class="ml-4">
                            <p class="text-sm text-gray-300">Pending Orders</p>
                            <p class="text-2xl font-bold text-gray-100"><?= number_format($stats['pending_orders']) ?></p>
                        </div>
                    </div>
                </div>

                <div class="cute-card">
                    <div class="flex items-center">
                        <div class="w-12 h-12 bg-cyan-600/20 rounded-xl flex items-center justify-center">
                            <i class="fas fa-wallet text-cyan-400 text-xl"></i>
                        </div>
                        <div class="ml-4">
                            <p class="text-sm text-gray-300">Store Owners Balance</p>
                            <p class="text-2xl font-bold text-gray-100">GHC <?= number_format($stats['total_store_owners_balance'], 2) ?></p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Store Owners Section -->
            <div class="cute-card mb-8">
                <div class="flex items-center justify-between mb-6">
                    <div>
                        <h2 class="text-xl font-bold text-gray-100">
                            <i class="fas fa-store mr-2 text-blue-500"></i>Registered Store Owners
                        </h2>
                        <p class="text-gray-400">All store owners and their store statistics</p>
                    </div>
                    <div class="text-right">
                        <p class="text-sm text-gray-400">Total Stores</p>
                        <p class="text-lg font-semibold text-gray-100"><?= count($storeOwners) ?></p>
                    </div>
                </div>

                <?php if (empty($storeOwners)): ?>
                <div class="text-center py-12">
                    <i class="fas fa-store text-5xl text-gray-600 mb-4"></i>
                    <p class="text-gray-400">No store owners registered yet.</p>
                        </div>
                <?php else: ?>
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead>
                            <tr class="border-b border-gray-700 text-left">
                                <th class="pb-3 text-gray-400 font-medium">Store Name</th>
                                <th class="pb-3 text-gray-400 font-medium">Owner</th>
                                <th class="pb-3 text-gray-400 font-medium">Balance</th>
                                <th class="pb-3 text-gray-400 font-medium">Agents</th>
                                <th class="pb-3 text-gray-400 font-medium">Orders</th>
                                <th class="pb-3 text-gray-400 font-medium">Revenue</th>
                                <th class="pb-3 text-gray-400 font-medium">Status</th>
                                <th class="pb-3 text-gray-400 font-medium">Created</th>
                                <th class="pb-3 text-gray-400 font-medium">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($storeOwners as $store): ?>
                            <tr class="border-b border-gray-700 hover:bg-gray-800/50 transition">
                                <td class="py-4">
                                    <div class="flex items-center gap-2">
                                        <div class="w-8 h-8 bg-blue-600 rounded-lg flex items-center justify-center">
                                            <i class="fas fa-store text-white text-xs"></i>
                            </div>
                                        <div>
                                            <div class="text-white font-medium"><?= htmlspecialchars($store['store_name']) ?></div>
                                            <div class="text-xs text-gray-500"><?= htmlspecialchars($store['store_slug']) ?></div>
                        </div>
                            </div>
                                </td>
                                <td class="py-4">
                                    <div class="text-white"><?= htmlspecialchars($store['owner_username']) ?></div>
                                    <div class="text-xs text-gray-500"><?= htmlspecialchars($store['owner_email']) ?></div>
                                </td>
                                <td class="py-4">
                                    <div class="text-white font-bold <?= $store['owner_balance'] < 10 ? 'text-red-400' : ($store['owner_balance'] < 50 ? 'text-yellow-400' : 'text-green-400') ?>">
                                        GH₵ <?= number_format($store['owner_balance'], 2) ?>
                            </div>
                                </td>
                                <td class="py-4">
                                    <div class="flex items-center gap-2">
                                        <i class="fas fa-users text-blue-400"></i>
                                        <span class="text-white"><?= $store['total_agents'] ?></span>
                            </div>
                                </td>
                                <td class="py-4">
                                    <div class="text-white"><?= $store['total_orders'] ?></div>
                                    <div class="text-xs text-gray-500">
                                        <?= $store['agent_orders'] ?> agents | <?= $store['customer_orders'] ?> customers
                        </div>
                                </td>
                                <td class="py-4">
                                    <div class="text-green-400 font-bold">GH₵ <?= number_format($store['total_revenue'], 2) ?></div>
                                </td>
                                <td class="py-4">
                                    <span class="px-3 py-1 rounded-full text-xs font-medium 
                                        <?= $store['store_status'] === 'active' ? 'bg-green-900 text-green-300' : 'bg-red-900 text-red-300' ?>">
                                        <?= ucfirst($store['store_status']) ?>
                            </span>
                                </td>
                                <td class="py-4 text-gray-400 text-sm">
                                    <?= $store['created_at'] ? date('M d, Y', strtotime($store['created_at'])) : 'N/A' ?>
                                </td>
                                <td class="py-4">
                                    <button onclick="toggleStoreAgents(<?= $store['store_id'] ?>)" 
                                            class="px-3 py-1 bg-blue-600 text-white rounded text-sm hover:bg-blue-700 transition">
                                        <i class="fas fa-users mr-1"></i>
                                        View Agents (<?= $store['total_agents'] ?>)
                                    </button>
                                </td>
                            </tr>
                            <!-- Agents Row (Expandable) -->
                            <tr id="agents-row-<?= $store['store_id'] ?>" class="hidden bg-gray-900/50">
                                <td colspan="9" class="py-4 px-6">
                                    <div class="mb-3">
                                        <h4 class="text-white font-semibold mb-3">
                                            <i class="fas fa-users mr-2 text-blue-400"></i>
                                            Agents Registered on <?= htmlspecialchars($store['store_name']) ?>
                                        </h4>
                            </div>
                                    <?php if (empty($store['agents'])): ?>
                                        <p class="text-gray-400 text-center py-4">No agents registered yet.</p>
                                    <?php else: ?>
                                        <div class="overflow-x-auto">
                                            <table class="w-full text-sm">
                                                <thead>
                                                    <tr class="border-b border-gray-700">
                                                        <th class="pb-2 text-left text-gray-400 font-medium">Agent ID</th>
                                                        <th class="pb-2 text-left text-gray-400 font-medium">Username</th>
                                                        <th class="pb-2 text-left text-gray-400 font-medium">Email</th>
                                                        <th class="pb-2 text-left text-gray-400 font-medium">Phone</th>
                                                        <th class="pb-2 text-left text-gray-400 font-medium">Balance</th>
                                                        <th class="pb-2 text-left text-gray-400 font-medium">Status</th>
                                                        <th class="pb-2 text-left text-gray-400 font-medium">Joined</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php foreach ($store['agents'] as $agent): ?>
                                                    <tr class="border-b border-gray-800 hover:bg-gray-800/30">
                                                        <td class="py-2 text-white">#<?= $agent['id'] ?></td>
                                                        <td class="py-2 text-white font-medium"><?= htmlspecialchars($agent['username']) ?></td>
                                                        <td class="py-2 text-gray-300"><?= htmlspecialchars($agent['email'] ?? 'N/A') ?></td>
                                                        <td class="py-2 text-gray-300"><?= htmlspecialchars($agent['phone'] ?? 'N/A') ?></td>
                                                        <td class="py-2">
                                                            <span class="text-white font-bold <?= floatval($agent['balance'] ?? 0) < 10 ? 'text-red-400' : (floatval($agent['balance'] ?? 0) < 50 ? 'text-yellow-400' : 'text-green-400') ?>">
                                                                GH₵ <?= number_format(floatval($agent['balance'] ?? 0), 2) ?>
                            </span>
                                                        </td>
                                                        <td class="py-2">
                                                            <span class="px-2 py-1 rounded-full text-xs font-medium <?= ($agent['agent_status'] ?? 'active') === 'active' ? 'bg-green-900 text-green-300' : 'bg-red-900 text-red-300' ?>">
                                                                <?= ucfirst($agent['agent_status'] ?? 'active') ?>
                                                            </span>
                                                        </td>
                                                        <td class="py-2 text-gray-400 text-xs">
                                                            <?= $agent['joined_at'] ? date('M d, Y', strtotime($agent['joined_at'])) : 'N/A' ?>
                                                        </td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                </tbody>
                                            </table>
                        </div>
                                    <?php endif; ?>
                                </td>
                            </tr>
                    <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>
            </div>

            <!-- Agent Statistics Section -->
            <div class="cute-card mb-8">
                <div class="flex items-center justify-between mb-6">
                    <div>
                        <h2 class="text-xl font-bold text-gray-100">Agent Statistics</h2>
                        <p class="text-gray-300">Comprehensive order tracking for all agents</p>
                    </div>
                    <div class="text-right">
                        <p class="text-sm text-gray-300">Last Updated</p>
                        <p class="text-lg font-semibold text-gray-100 agent-stats-last-updated"><?= date('g:i A', time()) ?></p>
                    </div>
                </div>

                <!-- Agent Role Statistics -->
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
                    <!-- Agents -->
                    <div class="bg-gradient-to-r from-blue-500 to-blue-600 text-white rounded-xl p-6" data-role="agent">
                        <div class="flex items-center justify-between">
                            <div>
                                <p class="text-blue-100 text-sm font-medium">Total Agents</p>
                                <p class="text-3xl font-bold text-white role-total"><?= number_format($agent_stats['total_agent'] ?? 0) ?></p>
                                <div class="mt-2">
                                    <p class="text-xs text-blue-100">Total Orders: <span class="role-total-orders"><?= number_format($agent_stats['total_orders_agent'] ?? 0) ?></span></p>
                                    <p class="text-xs text-blue-100">Today: <span class="role-today-orders"><?= number_format($agent_stats['today_orders_agent'] ?? 0) ?></span></p>
                                </div>
                            </div>
                            <div class="w-12 h-12 bg-white bg-opacity-20 rounded-full flex items-center justify-center">
                                <i class="fas fa-user text-white text-xl"></i>
                            </div>
                        </div>
                    </div>

                    <!-- Last Order Activity -->
                    <div class="bg-gradient-to-r from-orange-500 to-orange-600 text-white rounded-xl p-6">
                        <div class="flex items-center justify-between">
                            <div>
                                <p class="text-orange-100 text-sm font-medium">Last Order Activity</p>
                                <p class="text-lg font-bold text-white last-order-timestamp">
                                    <?php 
                                    $last_order_time = $agent_stats['last_order_agent'] ?? '1970-01-01';
                                    if ($last_order_time && $last_order_time !== '1970-01-01') {
                                        echo date('M j, g:i A', strtotime($last_order_time));
                                    } else {
                                        echo 'No orders yet';
                                    }
                                    ?>
                                </p>
                                <div class="mt-2">
                                    <p class="text-xs text-orange-100 last-order-time-ago">
                                        <?php
                                        if ($last_order_time && $last_order_time !== '1970-01-01') {
                                            $time_diff = time() - strtotime($last_order_time);
                                            if ($time_diff < 3600) {
                                                echo 'Active now';
                                            } elseif ($time_diff < 86400) {
                                                echo round($time_diff / 3600) . ' hours ago';
                                            } else {
                                                echo round($time_diff / 86400) . ' days ago';
                                            }
                                        } else {
                                            echo 'No activity';
                                        }
                                        ?>
                                    </p>
                                </div>
                            </div>
                            <div class="w-12 h-12 bg-white bg-opacity-20 rounded-full flex items-center justify-center">
                                <i class="fas fa-clock text-white text-xl"></i>
                            </div>
                        </div>
                    </div>
                </div>

            </div>

            <!-- Agent Management Section -->
            <div id="agent-management" class="cute-card">
                <div class="flex items-center justify-between mb-6">
                    <h2 class="text-xl font-bold text-gray-100">
                        <i class="fas fa-users mr-2"></i>Agent Management
                    </h2>
                    <button onclick="toggleAddAgentForm()" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-xl transition-all">
                        <i class="fas fa-plus mr-2"></i>Add New Agent
                    </button>
                </div>

                <!-- Search and Filter Controls -->
                <div class="mb-6 grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-300 mb-2">Search Agents</label>
                        <div class="relative">
                            <input type="text" id="agentSearch" placeholder="Search by username or email..." 
                                   class="w-full bg-gray-700 border-2 border-gray-600 rounded-xl p-3 pl-10 text-gray-100 placeholder-gray-400 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 transition-all">
                            <i class="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                        </div>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-300 mb-2">Filter by Type</label>
                        <select id="typeFilter" class="w-full bg-gray-700 border-2 border-gray-600 rounded-xl p-3 text-gray-100 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 transition-all">
                            <option value="">All Users</option>
                            <option value="store_owner">Store Owners</option>
                            <option value="sub_agent">Sub-Agents</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-300 mb-2">Sort by</label>
                        <select id="sortBy" class="w-full bg-gray-700 border-2 border-gray-600 rounded-xl p-3 text-gray-100 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 transition-all">
                            <option value="id_desc">Newest First</option>
                            <option value="id_asc">Oldest First</option>
                            <option value="username_asc">Username A-Z</option>
                            <option value="username_desc">Username Z-A</option>
                            <option value="balance_desc">Highest Balance</option>
                            <option value="balance_asc">Lowest Balance</option>
                        </select>
                    </div>
                </div>

                <!-- Agents Table -->
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead>
                            <tr class="bg-gray-800/50">
                                <th class="px-4 py-3 text-left font-medium text-gray-100">Username</th>
                                <th class="px-4 py-3 text-left font-medium text-gray-100">Email</th>
                                <th class="px-4 py-3 text-left font-medium text-gray-100">Balance</th>
                                <th class="px-4 py-3 text-left font-medium text-gray-100">Type</th>
                                <th class="px-4 py-3 text-left font-medium text-gray-100">Store</th>
                                <th class="px-4 py-3 text-left font-medium text-gray-100">Actions</th>
                            </tr>
                        </thead>
                        <tbody id="agentsTableBody">
                            <!-- Agents will be loaded here via JavaScript -->
                        </tbody>
                    </table>
                </div>

                <!-- Pagination Controls -->
                <div class="flex items-center justify-between mt-6">
                    <div class="flex items-center space-x-4">
                        <div class="text-sm text-gray-400">
                            Showing <span id="showingStart">0</span> to <span id="showingEnd">0</span> of <span id="totalAgents">0</span> agents
                        </div>
                        <div class="flex items-center space-x-2">
                            <label class="text-sm text-gray-400">Show:</label>
                            <select id="itemsPerPage" class="bg-gray-700 border border-gray-600 rounded px-2 py-1 text-gray-100 text-sm">
                                <option value="5">5</option>
                                <option value="10">10</option>
                                <option value="20">20</option>
                                <option value="50">50</option>
                                <option value="100" selected>100</option>
                            </select>
                            <span class="text-sm text-gray-400">per page</span>
                        </div>
                    </div>
                    <div class="flex items-center space-x-2">
                        <button id="prevPage" onclick="changePage(-1)" class="px-3 py-2 bg-gray-700 text-gray-300 rounded-lg hover:bg-gray-600 disabled:opacity-50 disabled:cursor-not-allowed transition-all">
                            <i class="fas fa-chevron-left"></i>
                        </button>
                        <span id="pageInfo" class="px-3 py-2 text-gray-300">Page 1 of 1</span>
                        <button id="nextPage" onclick="changePage(1)" class="px-3 py-2 bg-gray-700 text-gray-300 rounded-lg hover:bg-gray-600 disabled:opacity-50 disabled:cursor-not-allowed transition-all">
                            <i class="fas fa-chevron-right"></i>
                        </button>
                    </div>
                </div>
            </div>
            </div>

     
        </div>
    </div>

    <!-- Add Agent Form (Hidden by default) -->
    <div id="addAgentForm" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50">
        <div class="flex items-center justify-center min-h-screen p-4">
            <div class="bg-gray-800 rounded-2xl p-6 w-full max-w-md border border-gray-700 shadow-2xl" onclick="event.stopPropagation()">
                <div class="flex justify-between items-center mb-6">
                    <h3 class="text-xl font-bold text-gray-100">Add New Agent</h3>
                    <button onclick="closeAddAgentForm()" class="text-gray-300 hover:text-gray-100 transition-colors">
                        <i class="fas fa-times text-xl"></i>
                    </button>
                </div>
                
                <form method="POST" action="index.php?page=dashboard" class="space-y-4" onsubmit="return validateAgentForm()">
                    <input type="hidden" name="action" value="add_agent">
                    <div>
                        <label class="block text-sm font-medium text-gray-300 mb-2">Username</label>
                        <input type="text" name="username" class="w-full bg-gray-700 border-2 border-gray-600 rounded-xl p-3 text-gray-100 placeholder-gray-400 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 transition-all" required>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-300 mb-2">Email Address</label>
                        <input type="email" name="email" class="w-full bg-gray-700 border-2 border-gray-600 rounded-xl p-3 text-gray-100 placeholder-gray-400 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 transition-all" required>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-300 mb-2">Default Password</label>
                        <input type="text" name="default_password" value="password123" class="w-full bg-gray-700 border-2 border-gray-600 rounded-xl p-3 text-gray-100 placeholder-gray-400 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 transition-all" required>
                        <p class="text-xs text-gray-400 mt-1">Agent can change this after first login</p>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-300 mb-2">Initial Balance</label>
                        <input type="number" name="balance" step="0.01" value="0.00" class="w-full bg-gray-700 border-2 border-gray-600 rounded-xl p-3 text-gray-100 placeholder-gray-400 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 transition-all" required>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-300 mb-2">Role</label>
                        <select name="role" class="w-full bg-gray-700 border-2 border-gray-600 rounded-xl p-3 text-gray-100 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 transition-all" required>
                            <option value="agent">Agent</option>
                        </select>
                    </div>
                    <div class="flex space-x-3">
                        <button type="button" onclick="closeAddAgentForm()" class="flex-1 bg-gray-600 hover:bg-gray-700 text-white py-3 rounded-xl transition-all">
                            Cancel
                        </button>
                        <button type="submit" class="flex-1 bg-blue-600 hover:bg-blue-700 text-white py-3 rounded-xl transition-all">
                            Add Agent
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Role Change Modal -->
    <div id="roleChangeModal" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50">
        <div class="flex items-center justify-center min-h-screen p-4">
            <div class="bg-gray-800 rounded-2xl p-6 w-full max-w-md border border-gray-700">
                <div class="flex justify-between items-center mb-6">
                    <h3 class="text-xl font-bold text-gray-100">Change User Role</h3>
                    <button onclick="closeRoleChangeModal()" class="text-gray-400 hover:text-gray-200">
                        <i class="fas fa-times text-xl"></i>
                    </button>
                </div>
                
                <form id="roleChangeForm" class="space-y-4">
                    <input type="hidden" id="role_change_agent_id" name="agent_id">
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-300 mb-2">Username</label>
                        <input type="text" id="role_change_username" class="w-full bg-gray-700 border-2 border-gray-600 rounded-xl p-3 text-gray-100" readonly>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-300 mb-2">Current Role</label>
                        <input type="text" id="role_change_current_role" class="w-full bg-gray-700 border-2 border-gray-600 rounded-xl p-3 text-gray-100" readonly>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-300 mb-2">New Role</label>
                        <select id="role_change_new_role" class="w-full bg-gray-700 border-2 border-gray-600 rounded-xl p-3 text-gray-100 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 transition-all" required>
                            <option value="">Select New Role</option>
                            <option value="agent">Agent</option>
                        </select>
                    </div>
                    
                    <div class="flex space-x-3">
                        <button type="button" onclick="closeRoleChangeModal()" class="flex-1 bg-gray-600 hover:bg-gray-700 text-white py-3 rounded-xl transition-all">
                            Cancel
                        </button>
                        <button type="button" onclick="changeUserRole()" class="flex-1 bg-blue-600 hover:bg-blue-700 text-white py-3 rounded-xl transition-all">
                            <i class="fas fa-user-edit mr-2"></i>Change Role
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Payment Modal -->
    <div id="paymentModal" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50">
        <div class="flex items-center justify-center min-h-screen p-4">
            <div class="bg-gray-800 rounded-2xl p-6 w-full max-w-md border border-gray-700">
                <div class="flex justify-between items-center mb-6">
                    <h3 class="text-xl font-bold text-gray-100">Account Transaction</h3>
                    <button onclick="closePaymentModal()" class="text-gray-400 hover:text-gray-200">
                        <i class="fas fa-times text-xl"></i>
                    </button>
                </div>
                
                <form id="paymentForm" method="POST" action="pages/add_payment.php" class="space-y-4" onsubmit="return validatePaymentForm()">
                    <input type="hidden" name="agent_id" id="agentId">
                    <div>
                        <label class="block text-sm font-medium text-gray-300 mb-2">Agent</label>
                        <input type="text" id="agentName" class="w-full bg-gray-700 border-2 border-gray-600 rounded-xl p-3 text-gray-100 placeholder-gray-400 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 transition-all" readonly>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-300 mb-2">Current Balance</label>
                        <input type="text" id="currentBalance" class="w-full bg-gray-700 border-2 border-gray-600 rounded-xl p-3 text-gray-100 placeholder-gray-400 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 transition-all" readonly>
                    </div>
                    <div id="subAgentWarning" class="hidden bg-yellow-900/30 border border-yellow-600/50 rounded-lg p-3 text-sm">
                        <!-- Warning message will be inserted here -->
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-300 mb-2">Transaction Amount (GHS)</label>
                        <input type="number" name="amount" step="0.01" class="w-full bg-gray-700 border-2 border-gray-600 rounded-xl p-3 text-gray-100 placeholder-gray-400 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 transition-all" required>
                        <p class="text-xs text-blue-400 mt-1">
                            <i class="fas fa-info-circle mr-1"></i>
                            Enter positive amount to credit account, negative amount to debit account
                        </p>
                    </div>
                    <div class="flex space-x-3">
                        <button type="button" onclick="closePaymentModal()" class="flex-1 bg-gray-500 hover:bg-gray-600 text-white py-3 rounded-xl transition-all">
                            Cancel
                        </button>
                        <button type="submit" class="flex-1 bg-green-500 hover:bg-green-600 text-white py-3 rounded-xl transition-all">
                            Process Transaction
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>



    <script>
        function toggleAddAgentForm() {
            const form = document.getElementById('addAgentForm');
            if (form) {
                form.classList.toggle('hidden');
                console.log('Add Agent Form toggled. Hidden:', form.classList.contains('hidden'));
                
                // Reset form when opening
                if (!form.classList.contains('hidden')) {
                    resetAddAgentForm();
                }
            } else {
                console.error('Add Agent Form element not found');
            }
        }

        function resetAddAgentForm() {
            const form = document.querySelector('#addAgentForm form');
            if (form) {
                form.reset();
                // Reset button state
                const submitBtn = form.querySelector('button[type="submit"]');
                if (submitBtn) {
                    submitBtn.textContent = 'Add Agent';
                    submitBtn.disabled = false;
                }
            }
        }

        function closeAddAgentForm() {
            const form = document.getElementById('addAgentForm');
            if (form) {
                form.classList.add('hidden');
                resetAddAgentForm();
            }
        }

        function openPaymentModal(agentId, agentName, currentBalance, isStoreOwner = false) {
            document.getElementById('agentId').value = agentId;
            document.getElementById('agentName').value = agentName;
            document.getElementById('currentBalance').value = 'GHC ' + parseFloat(currentBalance).toFixed(2);
            
            // Show warning if trying to credit a sub-agent
            const warningDiv = document.getElementById('subAgentWarning');
            if (warningDiv) {
                if (isStoreOwner) {
                    warningDiv.classList.add('hidden');
                } else {
                    warningDiv.classList.remove('hidden');
                    warningDiv.innerHTML = '<i class="fas fa-exclamation-triangle mr-2 text-yellow-400"></i><strong class="text-yellow-400">Warning:</strong> <span class="text-gray-300">This is a Sub-Agent. Only credit Store Owners directly.</span>';
                }
            }
            
            document.getElementById('paymentModal').classList.remove('hidden');
        }

        function closePaymentModal() {
            document.getElementById('paymentModal').classList.add('hidden');
            resetPaymentForm();
        }

        function resetPaymentForm() {
            const form = document.getElementById('paymentForm');
            if (form) {
                form.reset();
                // Reset button state
                const submitBtn = form.querySelector('button[type="submit"]');
                if (submitBtn) {
                    submitBtn.textContent = 'Process Transaction';
                    submitBtn.disabled = false;
                }
            }
        }

        // Role Change Modal Functions
        function openRoleChangeModal(agentId, username, currentRole) {
            document.getElementById('role_change_agent_id').value = agentId;
            document.getElementById('role_change_username').value = username;
            document.getElementById('role_change_current_role').value = currentRole.charAt(0).toUpperCase() + currentRole.slice(1).replace('_', ' ');
            document.getElementById('role_change_new_role').value = '';
            document.getElementById('roleChangeModal').classList.remove('hidden');
        }

        function closeRoleChangeModal() {
            document.getElementById('roleChangeModal').classList.add('hidden');
            resetRoleChangeForm();
        }

        function resetRoleChangeForm() {
            const form = document.getElementById('roleChangeForm');
            if (form) {
                form.reset();
                // Reset button state
                const submitBtn = form.querySelector('button[onclick="changeUserRole()"]');
                if (submitBtn) {
                    submitBtn.innerHTML = '<i class="fas fa-user-edit mr-2"></i>Change Role';
                    submitBtn.disabled = false;
                }
            }
        }

        function changeUserRole() {
            const agentId = document.getElementById('role_change_agent_id').value;
            const newRole = document.getElementById('role_change_new_role').value;
            const username = document.getElementById('role_change_username').value;
            const currentRole = document.getElementById('role_change_current_role').value;

            if (!agentId || !newRole) {
                showMessage('Please select a new role', 'error');
                return;
            }

            if (newRole === currentRole.toLowerCase().replace(' ', '_')) {
                showMessage('The new role is the same as the current role', 'error');
                return;
            }

            // Show confirmation
            const roleDisplay = newRole.charAt(0).toUpperCase() + newRole.slice(1).replace('_', ' ');
            if (!confirm(`Are you sure you want to change ${username}'s role to ${roleDisplay}?`)) {
                return;
            }

            // Show loading state
            const submitBtn = document.querySelector('button[onclick="changeUserRole()"]');
            const originalText = submitBtn.innerHTML;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Changing...';
            submitBtn.disabled = true;

            // Make AJAX request
            const formData = new FormData();
            formData.append('action', 'change_role');
            formData.append('agent_id', agentId);
            formData.append('new_role', newRole);

            fetch('pages/change_agent_role.php', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    showMessage(data.message, 'success');
                    closeRoleChangeModal();
                    loadAgents(); // Refresh agents table instead of full page reload
                } else {
                    showMessage(data.message || 'Failed to change role', 'error');
                }
            })
            .catch(error => {
                console.error('Error changing role:', error);
                showMessage(`Error: ${error.message}`, 'error');
            })
            .finally(() => {
                // Restore button state
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
            });
        }

        function validatePaymentForm() {
            const form = document.getElementById('paymentForm');
            if (!form) {
                console.error('Payment form not found');
                alert('Payment form not found. Please refresh the page and try again.');
                return false;
            }
            
            const agentId = form.querySelector('input[name="agent_id"]').value;
            const amount = form.querySelector('input[name="amount"]').value;
            
            if (!agentId || !amount) {
                alert('Please fill in all required fields');
                return false;
            }
            
            // Validate amount
            const amountNum = parseFloat(amount);
            if (isNaN(amountNum) || amountNum === 0) {
                alert('Please enter a valid transaction amount (cannot be zero)');
                return false;
            }
            
            if (Math.abs(amountNum) > 10000) {
                const action = amountNum > 0 ? 'credit' : 'debit';
                if (!confirm('Are you sure you want to ' + action + ' GHS ' + Math.abs(amountNum).toFixed(2) + '? This is a large amount.')) {
                    return false;
                }
            }
            
            console.log('Payment form validation passed');
            console.log('Form data:', { agentId, amount: amountNum });
            
            // Show loading state
            const submitBtn = form.querySelector('button[type="submit"]');
            const originalText = submitBtn.textContent;
            submitBtn.textContent = 'Adding Payment...';
            submitBtn.disabled = true;
            
            // Re-enable button after 5 seconds as fallback
            setTimeout(() => {
                submitBtn.textContent = originalText;
                submitBtn.disabled = false;
            }, 5000);
            
            return true;
        }

        function validateAgentForm() {
            // Find the form within the add agent modal
            const form = document.querySelector('#addAgentForm form');
            if (!form) {
                console.error('Add Agent form not found');
                alert('Form not found. Please refresh the page and try again.');
                return false;
            }
            
            const username = form.querySelector('input[name="username"]').value.trim();
            const email = form.querySelector('input[name="email"]').value.trim();
            const password = form.querySelector('input[name="default_password"]').value.trim();
            const role = form.querySelector('select[name="role"]').value;
            
            if (!username || !email || !password || !role) {
                alert('Please fill in all required fields');
                return false;
            }
            
            // Email validation
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test(email)) {
                alert('Please enter a valid email address');
                return false;
            }
            
            console.log('Form validation passed, submitting to:', form.action);
            console.log('Form data:', { username, email, role });
            
            // Show loading state
            const submitBtn = form.querySelector('button[type="submit"]');
            const originalText = submitBtn.textContent;
            submitBtn.textContent = 'Adding Agent...';
            submitBtn.disabled = true;
            
            // Re-enable button after 3 seconds as fallback
            setTimeout(() => {
                submitBtn.textContent = originalText;
                submitBtn.disabled = false;
            }, 3000);
            
            return true;
        }

        // Close modals when clicking outside
        document.addEventListener('click', function(event) {
            const addAgentForm = document.getElementById('addAgentForm');
            const paymentModal = document.getElementById('paymentModal');
            
            if (event.target === addAgentForm) {
                closeAddAgentForm();
            }
            if (event.target === paymentModal) {
                closePaymentModal();
            }
        });

        // Tab switching function
        function switchTab(tabName) {
            // Hide all tab contents
            document.querySelectorAll('.tab-content').forEach(tab => {
                tab.classList.remove('active');
            });
            
            // Remove active class from all buttons
            document.querySelectorAll('.tab-button').forEach(button => {
                button.classList.remove('active');
            });
            
            // Show selected tab content
            document.getElementById(tabName + '-tab').classList.add('active');
            
            // Add active class to clicked button
            event.target.classList.add('active');
            
            // Update URL without page reload
            const url = new URL(window.location);
            url.searchParams.set('tab', tabName);
            window.history.pushState({}, '', url);
        }

        // Network tab switching function
        function switchNetworkTab(networkName) {
            // Hide all network tab contents
            document.querySelectorAll('.network-tab-content').forEach(tab => {
                tab.classList.add('hidden');
            });
            
            // Show selected network tab content
            const selectedTab = document.getElementById(networkName + '-orders-tab');
            if (selectedTab) {
                selectedTab.classList.remove('hidden');
            }
        }

        // Update agent order status function
        function updateAgentOrderStatus(orderId, newStatus) {
            if (!confirm(`Are you sure you want to update this order to ${newStatus}?`)) {
                return;
            }

            const button = event.target.closest('button');
            const originalText = button.innerHTML;
            button.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i>Updating...';
            button.disabled = true;

            fetch('bulk_update_agent_status.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    order_ids: [orderId],
                    status: newStatus
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showMessage(data.message, 'success');
                    // Reload the page to show updated data
                    setTimeout(() => {
                        location.reload();
                    }, 1500);
                } else {
                    showMessage(data.message || 'Failed to update order', 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showMessage('An error occurred while updating the order', 'error');
            })
            .finally(() => {
                // Restore button state
                button.innerHTML = originalText;
                button.disabled = false;
            });
        }

        // Network filtering function
        function filterByNetwork(network) {
            currentNetworkFilter = network;
            
            // Update button states
            document.querySelectorAll('.network-filter-btn').forEach(btn => {
                btn.classList.remove('bg-blue-500', 'text-white');
                btn.classList.add('bg-gray-700', 'text-gray-300');
            });
            event.target.classList.remove('bg-gray-700', 'text-gray-300');
            event.target.classList.add('bg-blue-500', 'text-white');
            
            // Filter orders by network
            document.querySelectorAll('.order-card').forEach(card => {
                const cardNetwork = card.getAttribute('data-network');
                if (network === 'all' || cardNetwork === network) {
                    card.style.display = 'block';
                } else {
                    card.style.display = 'none';
                }
            });
            
            // Update network statistics
            updateNetworkStats();
        }

        // Order selection function
        function selectOrder(element, stage) {
            const orderId = element.getAttribute('data-order-id');
            
            // Toggle selection
            if (element.classList.contains('selected')) {
                element.classList.remove('selected', 'bg-blue-100', 'border-blue-300');
                selectedOrders[stage] = selectedOrders[stage].filter(id => id !== orderId);
            } else {
                element.classList.add('selected', 'bg-blue-100', 'border-blue-300');
                selectedOrders[stage].push(orderId);
            }
            
            // Update visual feedback
            updateSelectionCount(stage);
        }

        // Update selection count display
        function updateSelectionCount(stage) {
            const count = selectedOrders[stage].length;
            const countElement = document.getElementById(stage + '-count');
            if (count > 0) {
                countElement.textContent = count + ' selected';
                countElement.classList.add('bg-blue-500', 'text-white');
            } else {
                countElement.textContent = document.getElementById(stage + '-count').getAttribute('data-original-count');
                countElement.classList.remove('bg-blue-500', 'text-white');
            }
        }

        // Move selected orders to verified
        function moveSelectedToVerified() {
            const selected = document.querySelectorAll('.pending-checkbox:checked');
            if (selected.length === 0) {
                showMessage('Please select orders to verify', 'error');
                return;
            }
            
            if (confirm(`Move ${selected.length} orders to verified?`)) {
                // Workflow action removed
            }
        }


        // Move selected orders to completed
        function moveSelectedToCompleted() {
            const selected = document.querySelectorAll('.verified-checkbox:checked');
            if (selected.length === 0) {
                showMessage('Please select orders to complete', 'error');
                return;
            }
            
            const status = document.getElementById('completion-status').value;
            if (confirm(`Mark ${selected.length} orders as ${status}?`)) {
                // Workflow action removed
            }
        }



        // Update network statistics
        function updateNetworkStats() {
            const networks = ['mtn', 'telecel', 'airtel_tigo'];
            networks.forEach(network => {
                const count = document.querySelectorAll(`.order-card[data-network="${network}"]`).length;
                document.getElementById(network + '-count').textContent = count;
            });
        }

        // Export completed orders
        function exportCompletedOrders() {
            alert('Export functionality will be implemented');
        }

        // Payment configuration functions moved to payment_config.php

        // Process verified orders through API
        function processVerifiedOrders() {
            if (!confirm('This will process all verified orders through the configured APIs. Continue?')) {
                return;
            }
            
            showMessage('Processing verified orders through APIs...', 'info');
            
            fetch('../process_verified_orders.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                }
            })
            .then(response => response.text())
            .then(data => {
                // Parse the output from the script
                const lines = data.split('\n');
                const successCount = lines.find(line => line.includes('Successfully processed:'))?.match(/\d+/)?.[0] || '0';
                const errorCount = lines.find(line => line.includes('Failed:'))?.match(/\d+/)?.[0] || '0';
                
                if (parseInt(successCount) > 0 || parseInt(errorCount) > 0) {
                    showMessage(`✅ API Processing Complete! Success: ${successCount}, Failed: ${errorCount}`, 'success');
                    // Refresh the page to show updated data
                    setTimeout(() => {
                        location.reload();
                    }, 2000);
                } else {
                    showMessage('ℹ️ No verified orders to process', 'info');
                }
            })
            .catch(error => {
                showMessage('❌ Error processing orders: ' + error.message, 'error');
            });
        }


        // Sidebar toggle functionality
        function toggleSidebar() {
            const sidebar = document.getElementById('sidebar');
            const mainContent = document.getElementById('mainContent');
            const toggleButton = document.getElementById('sidebarToggle');
            
            sidebar.classList.toggle('collapsed');
            mainContent.classList.toggle('expanded');
            toggleButton.classList.toggle('visible');
            
            // Store sidebar state in localStorage
            const isCollapsed = sidebar.classList.contains('collapsed');
            localStorage.setItem('sidebarCollapsed', isCollapsed);
        }

        // Initialize sidebar state from localStorage
        function initializeSidebarState() {
            const isCollapsed = localStorage.getItem('sidebarCollapsed') === 'true';
            
            if (isCollapsed) {
                const sidebar = document.getElementById('sidebar');
                const mainContent = document.getElementById('mainContent');
                const toggleButton = document.getElementById('sidebarToggle');
                
                sidebar.classList.add('collapsed');
                mainContent.classList.add('expanded');
                toggleButton.classList.add('visible');
            }
        }

        // Initialize page on load
        document.addEventListener('DOMContentLoaded', function() {
            // Initialize sidebar state
            initializeSidebarState();
            // Store original counts
            document.getElementById('pending-count').setAttribute('data-original-count', document.getElementById('pending-count').textContent);
            document.getElementById('verified-count').setAttribute('data-original-count', document.getElementById('verified-count').textContent);
            document.getElementById('completed-count').setAttribute('data-original-count', document.getElementById('completed-count').textContent);
            
            // Initialize network stats
            updateNetworkStats();
            
            // Add keyboard shortcut for sidebar toggle (Ctrl+B or Cmd+B)
            document.addEventListener('keydown', function(e) {
                if ((e.ctrlKey || e.metaKey) && e.key === 'b') {
                    e.preventDefault();
                    toggleSidebar();
                }
            });
        });

        // Network tab switching function
        function switchNetworkTab(networkName) {
            // Hide all network tab contents
            document.querySelectorAll('.network-tab-content').forEach(tab => {
                tab.style.display = 'none';
            });
            
            // Remove active class from all network buttons
            document.querySelectorAll('.network-tab-button').forEach(button => {
                button.classList.remove('active');
            });
            
            // Show selected network tab content
            document.getElementById(networkName + '-network-tab').style.display = 'block';
            
            // Add active class to clicked button
            event.target.classList.add('active');
        }

        // Export selected agent orders function
        function exportSelectedAgentOrders(networkType) {
            const checkboxClass = `.agent-${networkType}-order-checkbox`;
            const checkboxes = document.querySelectorAll(checkboxClass);
            const selectedIds = Array.from(checkboxes).filter(cb => cb.checked).map(cb => cb.value);
            
            if (selectedIds.length === 0) {
                showMessage('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('export_orders_csv.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ 
                    order_ids: selectedIds,
                    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_${networkType}_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);
                        
                        showMessage(`Successfully exported ${selectedIds.length} ${networkType} order(s)`, 'success');
                    });
                } else {
                    return response.json().then(data => {
                        showMessage(data.message || 'Export failed', 'error');
                    });
                }
            })
            .catch(error => {
                console.error('Export error:', error);
                showMessage('Export failed. Please try again.', 'error');
            })
            .finally(() => {
                // Restore button state
                button.innerHTML = originalText;
                button.disabled = false;
            });
        }
    </script>

    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <!-- DataTables JS -->
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.js"></script>
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/buttons/2.2.2/js/dataTables.buttons.min.js"></script>
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/buttons/2.2.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>
        // Initialize DataTables when document is ready
        $(document).ready(function() {
            // Custom time formatting function
            function formatDateTime(data, type, row) {
                if (type === 'display' || type === 'type') {
                    if (data) {
                        // Parse the UTC date and convert to local time
                        const date = new Date(data);
                        return date.toLocaleString('en-US', {
                            year: 'numeric',
                            month: 'short',
                            day: 'numeric',
                            hour: '2-digit',
                            minute: '2-digit',
                            hour12: true
                        });
                    }
                }
                return data;
            }

            // Initialize DataTables for network tables
            $('#mtnTable').DataTable({
                responsive: true,
                pageLength: 25,
                order: [[0, 'desc']],
                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: [
                    'excel', 'pdf'
                ],
                columnDefs: [
                    {
                        targets: [1], // created_at column
                        render: formatDateTime
                    }
                ]
            });
            
            $('#telecelTable').DataTable({
                responsive: true,
                pageLength: 25,
                order: [[0, 'desc']],
                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: [
                    'excel', 'pdf'
                ],
                columnDefs: [
                    {
                        targets: [1], // created_at column
                        render: formatDateTime
                    }
                ]
            });
            
            $('#airtelTigoTable').DataTable({
                responsive: true,
                pageLength: 25,
                order: [[0, 'desc']],
                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: [
                    'excel', 'pdf'
                ],
                columnDefs: [
                    {
                        targets: [1], // created_at column
                        render: formatDateTime
                    }
                ]
            });
            
            // Agent Orders Tables
            $('#agentMtnOrdersTable').DataTable({
                responsive: true,
                pageLength: 25,
                order: [[0, 'desc']],
                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: [
                    'excel', 'pdf'
                ],
                columnDefs: [
                    {
                        targets: [7], // created_at column (adjust index as needed)
                        render: formatDateTime
                    }
                ]
            });
            
            $('#agentTelecelOrdersTable').DataTable({
                responsive: true,
                pageLength: 25,
                order: [[0, 'desc']],
                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: [
                    'excel', 'pdf'
                ],
                columnDefs: [
                    {
                        targets: [7], // created_at column (adjust index as needed)
                        render: formatDateTime
                    }
                ]
            });
            
            $('#agentAirtelTigoOrdersTable').DataTable({
                responsive: true,
                pageLength: 25,
                order: [[0, 'desc']],
                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: [
                    'excel', 'pdf'
                ],
                columnDefs: [
                    {
                        targets: [7], // created_at column (adjust index as needed)
                        render: formatDateTime
                    }
                ]
            });
            
            
            // Initialize customer packages table
            try {
                if ($.fn.DataTable.isDataTable('#customerPackagesTable')) {
                    $('#customerPackagesTable').DataTable().destroy();
                }
                
                $('#customerPackagesTable').DataTable({
                    responsive: true,
                    pageLength: 25,
                    order: [[6, 'asc']], // Sort by sort_order
                    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: [
                        'excel', 'pdf'
                    ]
                    // No time columns in packages table
                });
                
            } catch (error) {
                console.error('Error initializing customer packages table:', error);
            }
            
            // Initialize agent pricing table
            try {
                if ($.fn.DataTable.isDataTable('#agentPricingTable')) {
                    $('#agentPricingTable').DataTable().destroy();
                }
                
                $('#agentPricingTable').DataTable({
                    responsive: true,
                    pageLength: 25,
                    order: [[0, 'asc']],
                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: [
                        'excel', 'pdf'
                    ]
                    // No time columns in pricing table
                });
                
            } catch (error) {
                console.error('Error initializing agent pricing table:', error);
            }
        });





        // Bulk selection functions for Agent Orders
        function toggleAllAgents(checkbox) {
            const checkboxes = document.querySelectorAll('.agent-order-checkbox');
            checkboxes.forEach(cb => cb.checked = checkbox.checked);
        }

        function selectAllAgents() {
            const checkboxes = document.querySelectorAll('.agent-order-checkbox');
            checkboxes.forEach(cb => cb.checked = true);
            document.getElementById('selectAllAgents').checked = true;
        }

        function clearSelectionAgents() {
            const checkboxes = document.querySelectorAll('.agent-order-checkbox');
            checkboxes.forEach(cb => cb.checked = false);
            document.getElementById('selectAllAgents').checked = false;
        }

        // Copy selected orders function
        function copySelectedOrders(network) {
            let checkboxes;
            let networkName;
            
            switch(network) {
                case 'mtn':
                    checkboxes = document.querySelectorAll('.mtn-order-checkbox:checked');
                    networkName = 'MTN';
                    break;
                case 'telecel':
                    checkboxes = document.querySelectorAll('.telecel-order-checkbox:checked');
                    networkName = 'Telecel';
                    break;
                case 'airtel_tigo':
                    checkboxes = document.querySelectorAll('.airtel_tigo-order-checkbox:checked');
                    networkName = 'AirtelTigo';
                    break;
                default:
                    alert('Invalid network');
                    return;
            }

            if (checkboxes.length === 0) {
                alert('Please select at least one order to copy.');
                return;
            }

            // Collect data from selected rows
            let copyData = [];
            checkboxes.forEach(checkbox => {
                const row = checkbox.closest('tr');
                const beneficiary = row.getAttribute('data-beneficiary');
                const packageSize = row.getAttribute('data-package-size');
                
                copyData.push({
                    beneficiary: beneficiary,
                    packageSize: packageSize
                });
            });

            // Format data for copying
            let copyText = `${networkName} Orders - Beneficiary & Package Size:\n\n`;
            copyData.forEach((item, index) => {
                copyText += `${index + 1}. Beneficiary: ${item.beneficiary} | Package: ${item.packageSize}\n`;
            });

            // Copy to clipboard
            navigator.clipboard.writeText(copyText).then(() => {
                showMessage(`Copied ${checkboxes.length} ${networkName} order(s) to clipboard`, 'success');
            }).catch(err => {
                console.error('Failed to copy: ', err);
                // Fallback for older browsers
                const textArea = document.createElement('textarea');
                textArea.value = copyText;
                document.body.appendChild(textArea);
                textArea.select();
                document.execCommand('copy');
                document.body.removeChild(textArea);
                showMessage(`Copied ${checkboxes.length} ${networkName} order(s) to clipboard`, 'success');
            });
        }

        // Agent MTN Orders Functions
        function selectAllAgentMtn() {
            const checkboxes = document.querySelectorAll('.agent-mtn-order-checkbox');
            checkboxes.forEach(checkbox => checkbox.checked = true);
            document.getElementById('selectAllAgentMtn').checked = true;
        }

        function clearSelectionAgentMtn() {
            const checkboxes = document.querySelectorAll('.agent-mtn-order-checkbox');
            checkboxes.forEach(checkbox => checkbox.checked = false);
            document.getElementById('selectAllAgentMtn').checked = false;
        }

        function toggleAllAgentMtn(checkbox) {
            const checkboxes = document.querySelectorAll('.agent-mtn-order-checkbox');
            checkboxes.forEach(cb => cb.checked = checkbox.checked);
        }

        function copySelectedAgentMtnOrders() {
            const checkboxes = document.querySelectorAll('.agent-mtn-order-checkbox:checked');
            if (checkboxes.length === 0) {
                showMessage('Please select at least one order to copy', 'error');
                return;
            }

            let copyData = [];
            checkboxes.forEach(checkbox => {
                const row = checkbox.closest('tr');
                const beneficiary = row.getAttribute('data-beneficiary');
                const packageSize = row.getAttribute('data-package-size');
                
                copyData.push({
                    beneficiary: beneficiary,
                    packageSize: packageSize
                });
            });

            let copyText = `Agent MTN Orders - Beneficiary & Package Size:\n\n`;
            copyData.forEach((item, index) => {
                copyText += `${index + 1}. Beneficiary: ${item.beneficiary} | Package: ${item.packageSize}\n`;
            });

            navigator.clipboard.writeText(copyText).then(() => {
                showMessage(`Copied ${checkboxes.length} Agent MTN order(s) to clipboard`, 'success');
            }).catch(err => {
                console.error('Failed to copy: ', err);
                const textArea = document.createElement('textarea');
                textArea.value = copyText;
                document.body.appendChild(textArea);
                textArea.select();
                document.execCommand('copy');
                document.body.removeChild(textArea);
                showMessage(`Copied ${checkboxes.length} Agent MTN order(s) to clipboard`, 'success');
            });
        }

        function bulkUpdateAgentMtnStatus(status) {
            const checkboxes = document.querySelectorAll('.agent-mtn-order-checkbox:checked');
            if (checkboxes.length === 0) {
                showMessage('Please select at least one order to update', 'error');
                return;
            }

            const orderIds = Array.from(checkboxes).map(cb => cb.value);
            const statusText = status.charAt(0).toUpperCase() + status.slice(1);
            
            if (!confirm(`Are you sure you want to mark ${checkboxes.length} Agent MTN order(s) as ${statusText}?`)) {
                return;
            }

            // Show loading state
            const button = event.target;
            const originalText = button.innerHTML;
            button.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i>Updating...';
            button.disabled = true;

            // Make AJAX request
            const requestData = {
                order_ids: orderIds,
                status: status
            };
            
            fetch('bulk_update_agent_status.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(requestData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showMessage(data.message, 'success');
                    // Reload the page to show updated data
                    setTimeout(() => {
                        location.reload();
                    }, 1500);
                } else {
                    showMessage(data.message || 'Failed to update orders', 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showMessage('An error occurred while updating orders', 'error');
            })
            .finally(() => {
                // Restore button state
                button.innerHTML = originalText;
                button.disabled = false;
            });
        }

        // Agent Telecel Orders Functions
        function selectAllAgentTelecel() {
            const checkboxes = document.querySelectorAll('.agent-telecel-order-checkbox');
            checkboxes.forEach(checkbox => checkbox.checked = true);
            document.getElementById('selectAllAgentTelecel').checked = true;
        }

        function clearSelectionAgentTelecel() {
            const checkboxes = document.querySelectorAll('.agent-telecel-order-checkbox');
            checkboxes.forEach(checkbox => checkbox.checked = false);
            document.getElementById('selectAllAgentTelecel').checked = false;
        }

        function toggleAllAgentTelecel(checkbox) {
            const checkboxes = document.querySelectorAll('.agent-telecel-order-checkbox');
            checkboxes.forEach(cb => cb.checked = checkbox.checked);
        }

        function copySelectedAgentTelecelOrders() {
            const checkboxes = document.querySelectorAll('.agent-telecel-order-checkbox:checked');
            if (checkboxes.length === 0) {
                showMessage('Please select at least one order to copy', 'error');
                return;
            }

            let copyData = [];
            checkboxes.forEach(checkbox => {
                const row = checkbox.closest('tr');
                const beneficiary = row.getAttribute('data-beneficiary');
                const packageSize = row.getAttribute('data-package-size');
                
                copyData.push({
                    beneficiary: beneficiary,
                    packageSize: packageSize
                });
            });

            let copyText = `Agent Telecel Orders - Beneficiary & Package Size:\n\n`;
            copyData.forEach((item, index) => {
                copyText += `${index + 1}. Beneficiary: ${item.beneficiary} | Package: ${item.packageSize}\n`;
            });

            navigator.clipboard.writeText(copyText).then(() => {
                showMessage(`Copied ${checkboxes.length} Agent Telecel order(s) to clipboard`, 'success');
            }).catch(err => {
                console.error('Failed to copy: ', err);
                const textArea = document.createElement('textarea');
                textArea.value = copyText;
                document.body.appendChild(textArea);
                textArea.select();
                document.execCommand('copy');
                document.body.removeChild(textArea);
                showMessage(`Copied ${checkboxes.length} Agent Telecel order(s) to clipboard`, 'success');
            });
        }

        function bulkUpdateAgentTelecelStatus(status) {
            const checkboxes = document.querySelectorAll('.agent-telecel-order-checkbox:checked');
            if (checkboxes.length === 0) {
                showMessage('Please select at least one order to update', 'error');
                return;
            }

            const orderIds = Array.from(checkboxes).map(cb => cb.value);
            const statusText = status.charAt(0).toUpperCase() + status.slice(1);
            
            if (!confirm(`Are you sure you want to mark ${checkboxes.length} Agent Telecel order(s) as ${statusText}?`)) {
                return;
            }

            // Show loading state
            const button = event.target;
            const originalText = button.innerHTML;
            button.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i>Updating...';
            button.disabled = true;

            // Make AJAX request
            const requestData = {
                order_ids: orderIds,
                status: status
            };
            
            fetch('bulk_update_agent_status.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(requestData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showMessage(data.message, 'success');
                    // Reload the page to show updated data
                    setTimeout(() => {
                        location.reload();
                    }, 1500);
                } else {
                    showMessage(data.message || 'Failed to update orders', 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showMessage('An error occurred while updating orders', 'error');
            })
            .finally(() => {
                // Restore button state
                button.innerHTML = originalText;
                button.disabled = false;
            });
        }

        // Agent AirtelTigo Orders Functions
        function selectAllAgentAirtelTigo() {
            const checkboxes = document.querySelectorAll('.agent-airtel-tigo-order-checkbox');
            checkboxes.forEach(checkbox => checkbox.checked = true);
            document.getElementById('selectAllAgentAirtelTigo').checked = true;
        }

        function clearSelectionAgentAirtelTigo() {
            const checkboxes = document.querySelectorAll('.agent-airtel-tigo-order-checkbox');
            checkboxes.forEach(checkbox => checkbox.checked = false);
            document.getElementById('selectAllAgentAirtelTigo').checked = false;
        }

        function toggleAllAgentAirtelTigo(checkbox) {
            const checkboxes = document.querySelectorAll('.agent-airtel-tigo-order-checkbox');
            checkboxes.forEach(cb => cb.checked = checkbox.checked);
        }

        function copySelectedAgentAirtelTigoOrders() {
            const checkboxes = document.querySelectorAll('.agent-airtel-tigo-order-checkbox:checked');
            if (checkboxes.length === 0) {
                showMessage('Please select at least one order to copy', 'error');
                return;
            }

            let copyData = [];
            checkboxes.forEach(checkbox => {
                const row = checkbox.closest('tr');
                const beneficiary = row.getAttribute('data-beneficiary');
                const packageSize = row.getAttribute('data-package-size');
                
                copyData.push({
                    beneficiary: beneficiary,
                    packageSize: packageSize
                });
            });

            let copyText = `Agent AirtelTigo Orders - Beneficiary & Package Size:\n\n`;
            copyData.forEach((item, index) => {
                copyText += `${index + 1}. Beneficiary: ${item.beneficiary} | Package: ${item.packageSize}\n`;
            });

            navigator.clipboard.writeText(copyText).then(() => {
                showMessage(`Copied ${checkboxes.length} Agent AirtelTigo order(s) to clipboard`, 'success');
            }).catch(err => {
                console.error('Failed to copy: ', err);
                const textArea = document.createElement('textarea');
                textArea.value = copyText;
                document.body.appendChild(textArea);
                textArea.select();
                document.execCommand('copy');
                document.body.removeChild(textArea);
                showMessage(`Copied ${checkboxes.length} Agent AirtelTigo order(s) to clipboard`, 'success');
            });
        }

        function bulkUpdateAgentAirtelTigoStatus(status) {
            const checkboxes = document.querySelectorAll('.agent-airtel-tigo-order-checkbox:checked');
            if (checkboxes.length === 0) {
                showMessage('Please select at least one order to update', 'error');
                return;
            }

            const orderIds = Array.from(checkboxes).map(cb => cb.value);
            const statusText = status.charAt(0).toUpperCase() + status.slice(1);
            
            if (!confirm(`Are you sure you want to mark ${checkboxes.length} Agent AirtelTigo order(s) as ${statusText}?`)) {
                return;
            }

            // Show loading state
            const button = event.target;
            const originalText = button.innerHTML;
            button.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i>Updating...';
            button.disabled = true;

            // Make AJAX request
            const requestData = {
                order_ids: orderIds,
                status: status
            };
            
            fetch('bulk_update_agent_status.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(requestData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showMessage(data.message, 'success');
                    // Reload the page to show updated data
                    setTimeout(() => {
                        location.reload();
                    }, 1500);
                } else {
                    showMessage(data.message || 'Failed to update orders', 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showMessage('An error occurred while updating orders', 'error');
            })
            .finally(() => {
                // Restore button state
                button.innerHTML = originalText;
                button.disabled = false;
            });
        }

        function bulkUpdateSelectedAgentOrders(e) {
            e.preventDefault();
            const ids = Array.from(document.querySelectorAll('.agent-mtn-order-checkbox:checked, .agent-telecel-order-checkbox:checked, .agent-airtel-tigo-order-checkbox:checked')).map(cb => cb.value);
            const newStatus = document.getElementById('bulkAgentNewStatus').value;
            if (ids.length === 0) { showMessage('Select agent orders to update', 'error'); return false; }
            if (!newStatus) { showMessage('Select a status', 'error'); return false; }
            if (!confirm(`Update ${ids.length} agent order(s) to ${newStatus}?`)) { return false; }
            fetch('bulk_update_agent_status.php', {
                method: 'POST', headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ order_ids: ids, status: newStatus })
            }).then(async r => {
                let data; try { data = await r.json(); } catch (e) { throw new Error('Invalid JSON response'); }
                if (!r.ok || !data.success) { throw new Error(data && data.message ? data.message : 'Failed to update'); }
                showMessage(data.message, 'success'); setTimeout(() => location.reload(), 1000);
            }).catch((err) => showMessage(err.message || 'Request failed', 'error'));
            return false;
        }

        function bulkUpdateAgentByRange(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) { showMessage('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 agent orders between\n${start} and ${end}\nto ${new_status}?`)) return false;
            const payload = { start, end, status: new_status, current_status, agent_filter, network_type };
            fetch('bulk_update_agent_status_by_time.php', {
                method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload)
            }).then(async r => {
                let data; try { data = await r.json(); } catch (e) { throw new Error('Invalid JSON response'); }
                if (!r.ok || !data.success) { throw new Error(data && data.message ? data.message : 'Failed to update by range'); }
                showMessage(data.message, 'success'); setTimeout(() => location.reload(), 1000);
            }).catch((err) => showMessage(err.message || 'Request failed', 'error'));
            return false;
        }

        // Copy selected agent orders function
        function copySelectedAgentOrders() {
            const checkboxes = document.querySelectorAll('.agent-order-checkbox:checked');

            if (checkboxes.length === 0) {
                alert('Please select at least one agent order to copy.');
                return;
            }

            // Collect data from selected rows
            let copyData = [];
            checkboxes.forEach(checkbox => {
                const row = checkbox.closest('tr');
                const beneficiary = row.getAttribute('data-beneficiary');
                const packageSize = row.getAttribute('data-package-size');
                
                copyData.push({
                    beneficiary: beneficiary,
                    packageSize: packageSize
                });
            });

            // Format data for copying
            let copyText = `Agent Orders - Beneficiary & Package Size:\n\n`;
            copyData.forEach((item, index) => {
                copyText += `${index + 1}. Beneficiary: ${item.beneficiary} | Package: ${item.packageSize}\n`;
            });

            // Copy to clipboard
            navigator.clipboard.writeText(copyText).then(() => {
                showMessage(`Copied ${checkboxes.length} agent order(s) to clipboard`, 'success');
            }).catch(err => {
                console.error('Failed to copy: ', err);
                // Fallback for older browsers
                const textArea = document.createElement('textarea');
                textArea.value = copyText;
                document.body.appendChild(textArea);
                textArea.select();
                document.execCommand('copy');
                document.body.removeChild(textArea);
                showMessage(`Copied ${checkboxes.length} agent order(s) to clipboard`, 'success');
            });
        }

        // Bulk status update function for agent orders
        function bulkUpdateAgentStatus(status) {
            const checkboxes = document.querySelectorAll('.agent-order-checkbox:checked');

            if (checkboxes.length === 0) {
                alert('Please select at least one agent order to update.');
                return;
            }

            const orderIds = Array.from(checkboxes).map(cb => cb.value);
            const statusText = status.charAt(0).toUpperCase() + status.slice(1);
            
            
            if (!confirm(`Are you sure you want to mark ${checkboxes.length} agent order(s) as ${statusText}?`)) {
                return;
            }

            // Show loading state
            const button = event.target;
            const originalText = button.innerHTML;
            button.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i>Updating...';
            button.disabled = true;

            // Make AJAX request
            const requestData = {
                order_ids: orderIds,
                status: status
            };
            
            fetch('bulk_update_agent_status.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(requestData)
            })
            .then(response => {
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    // Show success message
                    showMessage(data.message, 'success');
                    
                    // Reload the page to reflect changes
                    setTimeout(() => {
                        window.location.reload();
                    }, 1500);
                } else {
                    showMessage(data.message || 'Failed to update agent orders', 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showMessage('Network error occurred', 'error');
            })
            .finally(() => {
                // Restore button state
                button.innerHTML = originalText;
                button.disabled = false;
            });
        }


         

   

        

        // Custom Pricing Modal Functions
        function openAddCustomPricingModal() {
            // Remove any existing modal first
            const existingModal = document.getElementById('addCustomPricingModal');
            if (existingModal) {
                existingModal.remove();
            }
            
            // Create modal HTML
            const modalHTML = `
                <div id="addCustomPricingModal" class="fixed inset-0 bg-black bg-opacity-50 z-50">
                    <div class="flex items-center justify-center min-h-screen p-4">
                        <div class="bg-gray-800 rounded-2xl p-6 w-full max-w-md border border-gray-700">
                            <div class="flex justify-between items-center mb-6">
                                <h3 class="text-xl font-bold text-gray-100">Add Custom Pricing</h3>
                                <button onclick="closeAddCustomPricingModal()" class="text-gray-300 hover:text-gray-100">
                                    <i class="fas fa-times text-xl"></i>
                                </button>
                            </div>
                            
                            <form id="addCustomPricingForm" class="space-y-4">
                                <div>
                                    <label class="block text-sm font-medium text-gray-300 mb-2">Package Size</label>
                                    <input type="text" id="custom_package_size" class="w-full bg-gray-700 border-2 border-gray-600 rounded-xl p-3 text-gray-100 placeholder-gray-400 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 transition-all" placeholder="e.g., 1GB, 2GB, 5GB" required>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-300 mb-2">Cost (GHS)</label>
                                    <input type="number" id="custom_cost" class="w-full bg-gray-700 border-2 border-gray-600 rounded-xl p-3 text-gray-100 placeholder-gray-400 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 transition-all" step="0.01" min="0" required>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-300 mb-2">Network Type</label>
                                    <select id="custom_network_type" class="w-full bg-gray-700 border-2 border-gray-600 rounded-xl p-3 text-gray-100 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 transition-all" required>
                                        <option value="">Select Network</option>
                                        <option value="all">All Networks</option>
                                        <option value="mtn">MTN</option>
                                    </select>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-300 mb-2">User Role</label>
                                    <select id="custom_user_role" class="w-full bg-gray-700 border-2 border-gray-600 rounded-xl p-3 text-gray-100 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 transition-all" required>
                                        <option value="">Select Role</option>
                                        <option value="agent">Agent</option>
                                    </select>
                                </div>
                                <div class="flex space-x-3">
                                    <button type="button" onclick="closeAddCustomPricingModal()" class="flex-1 bg-gray-500 text-white py-3 rounded-xl hover:bg-gray-600 transition-colors">
                                        <i class="fas fa-times mr-2"></i>Cancel
                                    </button>
                                    <button type="button" onclick="addCustomPricing()" class="flex-1 bg-green-500 text-white py-3 rounded-xl hover:bg-green-600 transition-colors">
                                        <i class="fas fa-plus mr-2"></i>Add Custom Price
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            `;
            
            // Add modal to page
            document.body.insertAdjacentHTML('beforeend', modalHTML);
        }

        function closeAddCustomPricingModal() {
            const modal = document.getElementById('addCustomPricingModal');
            if (modal) {
                modal.remove();
            }
        }

        function addCustomPricing() {
            const formData = new FormData();
            formData.append('action', 'add_pricing');
            formData.append('package_size', document.getElementById('custom_package_size').value);
            formData.append('cost', document.getElementById('custom_cost').value);
            formData.append('network_type', document.getElementById('custom_network_type').value);
            formData.append('user_role', document.getElementById('custom_user_role').value);

            fetch('custom_pricing_management.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showMessage(data.message, 'success');
                    closeAddCustomPricingModal();
                    setTimeout(() => location.reload(), 1000);
                } else {
                    showMessage(data.message, 'error');
                }
            })
            .catch(error => {
                console.error('Error adding custom pricing:', error);
                showMessage('Error adding custom pricing', 'error');
            });
        }

        function editCustomPricing(id) {
            // Fetch custom pricing details and open edit modal
            fetch(`get_custom_pricing_details.php?id=${id}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    openEditCustomPricingModal(data.pricing);
                } else {
                    showMessage('Failed to fetch pricing details', 'error');
                }
            })
            .catch(error => {
                console.error('Error fetching pricing details:', error);
                showMessage('Error fetching pricing details', 'error');
            });
        }

        function openEditCustomPricingModal(pricing) {
            // Remove any existing modal first
            const existingModal = document.getElementById('editCustomPricingModal');
            if (existingModal) {
                existingModal.remove();
            }
            
            // Create modal HTML
            const modalHTML = `
                <div id="editCustomPricingModal" class="fixed inset-0 bg-black bg-opacity-50 z-50">
                    <div class="flex items-center justify-center min-h-screen p-4">
                        <div class="bg-gray-800 rounded-2xl p-6 w-full max-w-md border border-gray-700">
                            <div class="flex justify-between items-center mb-6">
                                <h3 class="text-xl font-bold text-gray-100">Edit Custom Pricing</h3>
                                <button onclick="closeEditCustomPricingModal()" class="text-gray-300 hover:text-gray-100">
                                    <i class="fas fa-times text-xl"></i>
                                </button>
                            </div>
                            
                            <form id="editCustomPricingForm" class="space-y-4">
                                <input type="hidden" id="edit_pricing_id" value="${pricing.id}">
                                <div>
                                    <label class="block text-sm font-medium text-gray-300 mb-2">Package Size</label>
                                    <input type="text" id="edit_package_size" class="w-full bg-gray-700 border-2 border-gray-600 rounded-xl p-3 text-gray-100 placeholder-gray-400 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 transition-all" value="${pricing.package_size}" required>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-300 mb-2">Cost (GHS)</label>
                                    <input type="number" id="edit_cost" class="w-full bg-gray-700 border-2 border-gray-600 rounded-xl p-3 text-gray-100 placeholder-gray-400 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 transition-all" step="0.01" min="0" value="${pricing.cost}" required>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-300 mb-2">Network Type</label>
                                    <select id="edit_network_type" class="w-full bg-gray-700 border-2 border-gray-600 rounded-xl p-3 text-gray-100 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 transition-all" required>
                                        <option value="all" ${pricing.network_type === 'all' ? 'selected' : ''}>All Networks</option>
                                        <option value="mtn" ${pricing.network_type === 'mtn' ? 'selected' : ''}>MTN</option>
                                        <option value="telecel" ${pricing.network_type === 'telecel' ? 'selected' : ''}>Telecel</option>
                                        <option value="airtel_tigo" ${pricing.network_type === 'airtel_tigo' ? 'selected' : ''}>AirtelTigo</option>
                                    </select>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-300 mb-2">User Role</label>
                                    <select id="edit_user_role" class="w-full bg-gray-700 border-2 border-gray-600 rounded-xl p-3 text-gray-100 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 transition-all" required>
                                        <option value="agent" ${pricing.user_role === 'agent' ? 'selected' : ''}>Agent</option>
                                    </select>
                                </div>
                                <div class="flex space-x-3">
                                    <button type="button" onclick="closeEditCustomPricingModal()" class="flex-1 bg-gray-500 text-white py-3 rounded-xl hover:bg-gray-600 transition-colors">
                                        <i class="fas fa-times mr-2"></i>Cancel
                                    </button>
                                    <button type="button" onclick="updateCustomPricing()" class="flex-1 bg-blue-500 text-white py-3 rounded-xl hover:bg-blue-600 transition-colors">
                                        <i class="fas fa-save mr-2"></i>Update
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            `;
            
            // Add modal to page
            document.body.insertAdjacentHTML('beforeend', modalHTML);
        }

        function closeEditCustomPricingModal() {
            const modal = document.getElementById('editCustomPricingModal');
            if (modal) {
                modal.remove();
            }
        }

        function updateCustomPricing() {
            const formData = new FormData();
            formData.append('action', 'update_pricing');
            formData.append('pricing_id', document.getElementById('edit_pricing_id').value);
            formData.append('package_size', document.getElementById('edit_package_size').value);
            formData.append('cost', document.getElementById('edit_cost').value);
            formData.append('network_type', document.getElementById('edit_network_type').value);
            formData.append('user_role', document.getElementById('edit_user_role').value);

            fetch('custom_pricing_management.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showMessage(data.message, 'success');
                    closeEditCustomPricingModal();
                    setTimeout(() => location.reload(), 1000);
                } else {
                    showMessage(data.message, 'error');
                }
            })
            .catch(error => {
                console.error('Error updating custom pricing:', error);
                showMessage('Error updating custom pricing', 'error');
            });
        }


        function deleteCustomPricing(id) {
            if (confirm('Are you sure you want to delete this custom pricing? This action cannot be undone.')) {
                const formData = new FormData();
                formData.append('action', 'delete_pricing');
                formData.append('pricing_id', id);

                fetch('custom_pricing_management.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok: ' + response.status);
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        showMessage(data.message, 'success');
                        setTimeout(() => location.reload(), 1000);
                    } else {
                        showMessage(data.message || 'Failed to delete custom pricing', 'error');
                    }
                })
                .catch(error => {
                    console.error('Error deleting custom pricing:', error);
                    showMessage('Error deleting custom pricing: ' + error.message, 'error');
                });
            }
        }

        function addPricingRule() {
            const formData = new FormData();
            formData.append('role', document.getElementById('add_role').value);
            formData.append('network_type', document.getElementById('add_network_type').value);
            formData.append('min_size_gb', document.getElementById('add_min_size_gb').value);
            formData.append('max_size_gb', document.getElementById('add_max_size_gb').value);
            formData.append('price_per_gb', document.getElementById('add_price_per_gb').value);
            formData.append('is_active', '1'); // Always set to active by default
            
            
            fetch('add_pricing_rule.php', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    showMessage(data.message, 'success');
                    closeAddPricingRuleModal();
                    setTimeout(() => location.reload(), 1000);
                } else {
                    showMessage(data.message, 'error');
                }
            })
            .catch(error => {
                console.error('Error adding pricing rule:', error);
                showMessage('Error adding pricing rule', 'error');
            });
        }

        function updatePricingRule() {
            const formData = new FormData();
            formData.append('id', document.getElementById('edit_pricing_rule_id').value);
            formData.append('role', document.getElementById('edit_role').value);
            formData.append('network_type', document.getElementById('edit_network_type').value);
            formData.append('min_size_gb', document.getElementById('edit_min_size_gb').value);
            formData.append('max_size_gb', document.getElementById('edit_max_size_gb').value);
            formData.append('price_per_gb', document.getElementById('edit_price_per_gb').value);
            formData.append('is_active', document.getElementById('edit_is_active').checked ? '1' : '0');
            
            
            fetch('update_pricing_rule.php', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                
                // Check if response is JSON
                const contentType = response.headers.get('content-type');
                if (!contentType || !contentType.includes('application/json')) {
                    throw new Error('Response is not JSON. Content-Type: ' + contentType);
                }
                
                return response.text().then(text => {
                    try {
                        return JSON.parse(text);
                    } catch (parseError) {
                        console.error('JSON parse error:', parseError);
                        console.error('Response text:', text);
                        throw new Error('Invalid JSON response: ' + text.substring(0, 200));
                    }
                });
            })
            .then(data => {
                if (data.success) {
                    showMessage(data.message, 'success');
                    closeEditPricingRuleModal();
                    setTimeout(() => location.reload(), 1000);
                } else {
                    showMessage(data.message, 'error');
                }
            })
            .catch(error => {
                console.error('Error updating pricing rule:', error);
                showMessage('Error updating pricing rule: ' + error.message, 'error');
            });
        }

        function togglePricingRuleStatus(id, newStatus) {
            if (confirm('Are you sure you want to ' + (newStatus === 'true' ? 'activate' : 'deactivate') + ' this pricing rule?')) {
                // AJAX call to update pricing rule status
                fetch('update_pricing_rule_status.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ id: id, is_active: newStatus })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showMessage(data.message, 'success');
                        setTimeout(() => location.reload(), 1000);
                    } else {
                        showMessage(data.message, 'error');
                    }
                })
                .catch(error => {
                    showMessage('Error updating pricing rule status', 'error');
                });
            }
        }

        // Show message function
        function showMessage(message, type) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `fixed top-20 left-1/2 transform -translate-x-1/2 z-50 max-w-md w-full mx-4`;
            messageDiv.innerHTML = `
                <div class="bg-${type === 'success' ? 'green' : 'red'}-50 border border-${type === 'success' ? 'green' : 'red'}-200 text-${type === 'success' ? 'green' : 'red'}-700 px-4 py-3 rounded-xl shadow-lg flex items-center">
                    <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'} mr-3"></i>
                    <span>${message}</span>
                </div>
            `;
            
            document.body.appendChild(messageDiv);
            
            // Auto-hide after 5 seconds
            setTimeout(() => {
                messageDiv.style.opacity = '0';
                messageDiv.style.transform = 'translate(-50%, -100%)';
                setTimeout(() => messageDiv.remove(), 300);
            }, 5000);
        }
    </script>


    <!-- JavaScript Functions -->
    <script>
        // Network filtering
        function filterByNetwork(network) {
            // Remove active class from all buttons
            document.querySelectorAll('.network-filter-btn').forEach(btn => {
                btn.classList.remove('bg-blue-500', 'text-white');
                btn.classList.add('bg-gray-100', 'text-gray-700');
            });
            
            // Add active class to clicked button
            event.target.classList.remove('bg-gray-100', 'text-gray-700');
            event.target.classList.add('bg-blue-500', 'text-white');
            
            // Filter orders by network
            const orderCards = document.querySelectorAll('.order-card');
            orderCards.forEach(card => {
                const cardNetwork = card.getAttribute('data-network');
                if (network === 'all' || cardNetwork === network) {
                    card.style.display = 'block';
                } else {
                    card.style.display = 'none';
                }
            });
        }

        // Selection functions for Pending
        function selectAllPending() {
            const checkboxes = document.querySelectorAll('.pending-checkbox');
            
            if (checkboxes.length === 0) {
                showMessage('No pending orders found to select', 'info');
                return;
            }
            
            checkboxes.forEach(cb => {
                cb.checked = true;
            });
            
            // Update any "Select All" checkbox if it exists
            const selectAllCheckbox = document.getElementById('selectAllPending');
            if (selectAllCheckbox) {
                selectAllCheckbox.checked = true;
            }
            
            showMessage(`Selected ${checkboxes.length} pending order(s)`, 'success');
        }

        function clearSelectionPending() {
            const checkboxes = document.querySelectorAll('.pending-checkbox');
            
            if (checkboxes.length === 0) {
                showMessage('No pending orders found to clear', 'info');
                return;
            }
            
            checkboxes.forEach(cb => {
                cb.checked = false;
            });
            
            // Update any "Select All" checkbox if it exists
            const selectAllCheckbox = document.getElementById('selectAllPending');
            if (selectAllCheckbox) {
                selectAllCheckbox.checked = false;
            }
            
            showMessage(`Cleared ${checkboxes.length} pending order(s)`, 'success');
        }

        // Selection functions for Verified
        function selectAllVerified() {
            const checkboxes = document.querySelectorAll('.verified-checkbox');
            
            if (checkboxes.length === 0) {
                showMessage('No verified orders found to select', 'info');
                return;
            }
            
            checkboxes.forEach(cb => {
                cb.checked = true;
            });
            
            // Update any "Select All" checkbox if it exists
            const selectAllCheckbox = document.getElementById('selectAllVerified');
            if (selectAllCheckbox) {
                selectAllCheckbox.checked = true;
            }
            
            showMessage(`Selected ${checkboxes.length} verified order(s)`, 'success');
        }

        function clearSelectionVerified() {
            const checkboxes = document.querySelectorAll('.verified-checkbox');
            
            if (checkboxes.length === 0) {
                showMessage('No verified orders found to clear', 'info');
                return;
            }
            
            checkboxes.forEach(cb => {
                cb.checked = false;
            });
            
            // Update any "Select All" checkbox if it exists
            const selectAllCheckbox = document.getElementById('selectAllVerified');
            if (selectAllCheckbox) {
                selectAllCheckbox.checked = false;
            }
            
            showMessage(`Cleared ${checkboxes.length} verified order(s)`, 'success');
        }

        function deselectAllVerified() {
            clearSelectionVerified();
        }

        // Selection functions for Processing
        function selectAllProcessing() {
            const checkboxes = document.querySelectorAll('.processing-checkbox');
            
            if (checkboxes.length === 0) {
                showMessage('No processing orders found to select', 'info');
                return;
            }
            
            checkboxes.forEach(cb => {
                cb.checked = true;
            });
            
            // Update any "Select All" checkbox if it exists
            const selectAllCheckbox = document.getElementById('selectAllProcessing');
            if (selectAllCheckbox) {
                selectAllCheckbox.checked = true;
            }
            
            showMessage(`Selected ${checkboxes.length} processing order(s)`, 'success');
        }

        function clearSelectionProcessing() {
            const checkboxes = document.querySelectorAll('.processing-checkbox');
            
            if (checkboxes.length === 0) {
                showMessage('No processing orders found to clear', 'info');
                return;
            }
            
            checkboxes.forEach(cb => {
                cb.checked = false;
            });
            
            // Update any "Select All" checkbox if it exists
            const selectAllCheckbox = document.getElementById('selectAllProcessing');
            if (selectAllCheckbox) {
                selectAllCheckbox.checked = false;
            }
            
            showMessage(`Cleared ${checkboxes.length} processing order(s)`, 'success');
        }

        // Action functions
        function verifySelectedOrders() {
            const selected = document.querySelectorAll('.pending-checkbox:checked');
            if (selected.length === 0) {
                showMessage('Please select orders to verify', 'error');
                return;
            }
            
            const orderIds = Array.from(selected).map(cb => cb.value);
            
            // Submit form with selected orders
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = '';
            
            orderIds.forEach(id => {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = 'selected_orders[]';
                input.value = id;
                form.appendChild(input);
            });
            
            const actionInput = document.createElement('input');
            actionInput.type = 'hidden';
            actionInput.name = 'verify_payment';
            actionInput.value = '1';
            form.appendChild(actionInput);
            
            document.body.appendChild(form);
            form.submit();
        }

        function processSelectedOrders() {
            const selected = document.querySelectorAll('.verified-checkbox:checked');
            if (selected.length === 0) {
                showMessage('Please select orders to process', 'error');
                return;
            }
            
            const orderIds = Array.from(selected).map(cb => cb.value);
            
            // Submit form with selected orders
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = '';
            
            orderIds.forEach(id => {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = 'selected_orders[]';
                input.value = id;
                form.appendChild(input);
            });
            
            const actionInput = document.createElement('input');
            actionInput.type = 'hidden';
            actionInput.name = 'process_orders';
            actionInput.value = '1';
            form.appendChild(actionInput);
            
            document.body.appendChild(form);
            form.submit();
        }

        function deliverSelectedOrders() {
            const selected = document.querySelectorAll('.processing-checkbox:checked');
            if (selected.length === 0) {
                showMessage('Please select orders to mark as delivered', 'error');
                return;
            }
            
            const orderIds = Array.from(selected).map(cb => cb.value);
            
            // Submit form with selected orders
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = '';
            
            orderIds.forEach(id => {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = 'selected_orders[]';
                input.value = id;
                form.appendChild(input);
            });
            
            const actionInput = document.createElement('input');
            actionInput.type = 'hidden';
            actionInput.name = 'deliver_orders';
            actionInput.value = '1';
            form.appendChild(actionInput);
            
            document.body.appendChild(form);
            form.submit();
        }

        function exportCompletedOrders() {
            // Export functionality for completed orders
            alert('Export functionality will be implemented');
        }

        // ===========================================
        // AGENT STATISTICS AUTO-REFRESH
        // ===========================================
        
        function refreshAgentStatistics() {
            fetch('get_agent_statistics.php')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        updateAgentStatisticsDisplay(data.data);
                    } else {
                        console.error('Error refreshing agent statistics:', data.message);
                    }
                })
                .catch(error => {
                    console.error('Error fetching agent statistics:', error);
                });
            
        }

        function updateAgentStatisticsDisplay(data) {
            const { agent_stats, last_order_activity } = data;
            
            // Update role statistics cards
            updateRoleCard('agent', agent_stats);
            
            // Update last order activity
            updateLastOrderActivity(last_order_activity);
            
            
            // Update last updated timestamp
            const lastUpdatedElement = document.querySelector('.agent-stats-last-updated');
            if (lastUpdatedElement) {
                lastUpdatedElement.textContent = new Date().toLocaleTimeString();
            }
        }

        function updateRoleCard(role, agent_stats) {
            const roleKey = role;
            const card = document.querySelector(`[data-role="${roleKey}"]`);
            if (!card) return;
            
            const totalElement = card.querySelector('.role-total');
            const totalOrdersElement = card.querySelector('.role-total-orders');
            const todayOrdersElement = card.querySelector('.role-today-orders');
            
            if (totalElement) totalElement.textContent = formatNumber(agent_stats[`total_${roleKey}`] || 0);
            if (totalOrdersElement) totalOrdersElement.textContent = formatNumber(agent_stats[`total_orders_${roleKey}`] || 0);
            if (todayOrdersElement) todayOrdersElement.textContent = formatNumber(agent_stats[`today_orders_${roleKey}`] || 0);
        }

        function updateLastOrderActivity(last_order_activity) {
            const timestampElement = document.querySelector('.last-order-timestamp');
            const timeAgoElement = document.querySelector('.last-order-time-ago');
            
            if (timestampElement) timestampElement.textContent = last_order_activity.formatted;
            if (timeAgoElement) timeAgoElement.textContent = last_order_activity.time_ago;
        }


        function createAgentTableRow(agent) {
            const row = document.createElement('tr');
            row.className = 'border-b border-gray-700 hover:bg-gray-800/30';
            
            const lastOrderTime = agent.last_order_time;
            let lastOrderDisplay = '<span class="text-gray-500">No orders</span>';
            let statusBadge = '<span class="px-2 py-1 rounded-full text-xs font-medium bg-red-600/20 text-red-300">No Activity</span>';
            
            if (lastOrderTime) {
                const timeDiff = Math.floor((Date.now() - new Date(lastOrderTime).getTime()) / 1000);
                if (timeDiff < 3600) {
                    lastOrderDisplay = '<span class="text-green-400">Active now</span>';
                    statusBadge = '<span class="px-2 py-1 rounded-full text-xs font-medium bg-green-600/20 text-green-300">Active</span>';
                } else if (timeDiff < 86400) {
                    const hours = Math.floor(timeDiff / 3600);
                    lastOrderDisplay = `<span class="text-yellow-400">${hours}h ago</span>`;
                    statusBadge = '<span class="px-2 py-1 rounded-full text-xs font-medium bg-yellow-600/20 text-yellow-300">Recent</span>';
                } else {
                    const days = Math.floor(timeDiff / 86400);
                    lastOrderDisplay = `<span class="text-gray-400">${days} days ago</span>`;
                    statusBadge = '<span class="px-2 py-1 rounded-full text-xs font-medium bg-gray-600/20 text-gray-300">Inactive</span>';
                }
            }
            
            const roleClass = 'bg-green-600/20 text-green-300';
            
            const todayOrdersClass = agent.today_orders > 0 ? 'bg-green-600/20 text-green-300' : 'bg-gray-600/20 text-gray-300';
            
            row.innerHTML = `
                <td class="py-3 px-4 font-semibold text-gray-100">${escapeHtml(agent.username)}</td>
                <td class="py-3 px-4">
                    <span class="px-2 py-1 rounded-full text-xs font-medium ${roleClass}">
                        ${agent.role.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase())}
                    </span>
                </td>
                <td class="py-3 px-4 text-gray-100">${formatNumber(agent.total_orders)}</td>
                <td class="py-3 px-4">
                    <span class="px-2 py-1 rounded-full text-xs font-medium ${todayOrdersClass}">
                        ${formatNumber(agent.today_orders)}
                    </span>
                </td>
                <td class="py-3 px-4 text-gray-100">GHS ${formatNumber(agent.total_revenue, 2)}</td>
                <td class="py-3 px-4 text-gray-100">${lastOrderDisplay}</td>
                <td class="py-3 px-4">${statusBadge}</td>
            `;
            
            return row;
        }

        function formatNumber(num, decimals = 0) {
            return new Intl.NumberFormat('en-US', {
                minimumFractionDigits: decimals,
                maximumFractionDigits: decimals
            }).format(num);
        }

        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        // Auto-refresh agent statistics every 30 seconds
        setInterval(refreshAgentStatistics, 30000);
        
        // Initial refresh after page load
        document.addEventListener('DOMContentLoaded', function() {
            setTimeout(refreshAgentStatistics, 1000);
            loadAgents(); // Load agents table
        });

        // Agent Management Functions
        let currentPage = 1;
        let currentLimit = 100;
        let currentSearch = '';
        let currentTypeFilter = '';
        let currentSort = 'id_desc';

        function loadAgents() {
            const params = new URLSearchParams({
                page: currentPage,
                limit: currentLimit,
                search: currentSearch,
                type: currentTypeFilter,
                sort: currentSort
            });

            fetch(`pages/get_agents.php?${params}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayAgents(data.data.agents);
                        updatePagination(data.data.pagination);
                    } else {
                        showMessage(data.message || 'Failed to load agents', 'error');
                    }
                })
                .catch(error => {
                    console.error('Error loading agents:', error);
                    showMessage('Network error occurred', 'error');
                });
        }

        function displayAgents(agents) {
            const tbody = document.getElementById('agentsTableBody');
            tbody.innerHTML = '';

            if (agents.length === 0) {
                tbody.innerHTML = `
                    <tr>
                        <td colspan="6" class="px-4 py-8 text-center text-gray-400">
                            <i class="fas fa-users text-4xl mb-2"></i>
                            <p>No users found</p>
                        </td>
                    </tr>
                `;
                return;
            }

            agents.forEach(agent => {
                const row = document.createElement('tr');
                // Different row styling for store owners vs sub-agents
                const isStoreOwner = agent.is_store_owner == 1 || agent.user_type === 'Store Owner';
                row.className = isStoreOwner 
                    ? 'border-b border-gray-700 hover:bg-purple-900/20 transition-colors bg-purple-900/10' 
                    : 'border-b border-gray-700 hover:bg-gray-800/30 transition-colors';
                
                // Determine type badge color and text
                let typeClass, typeText, storeName;
                if (isStoreOwner) {
                    typeClass = 'bg-purple-600/30 text-purple-300 border border-purple-500/50';
                    typeText = 'Store Owner';
                    storeName = agent.store_name && agent.store_name !== 'N/A' ? agent.store_name : 'N/A';
                } else {
                    typeClass = 'bg-blue-600/20 text-blue-300 border border-blue-500/50';
                    typeText = 'Sub-Agent';
                    storeName = 'N/A';
                }
                
                row.innerHTML = `
                    <td class="px-4 py-3 font-semibold text-gray-100">${escapeHtml(agent.username)}</td>
                    <td class="px-4 py-3 text-gray-400">${escapeHtml(agent.email || 'N/A')}</td>
                    <td class="px-4 py-3 font-semibold text-green-400">GHC ${formatNumber(agent.balance, 2)}</td>
                    <td class="px-4 py-3">
                        <span class="px-3 py-1 rounded-full text-xs font-medium ${typeClass}">
                            <i class="fas ${isStoreOwner ? 'fa-store' : 'fa-user'} mr-1"></i>${typeText}
                        </span>
                    </td>
                    <td class="px-4 py-3 text-gray-300 text-sm">
                        ${escapeHtml(storeName)}
                    </td>
                    <td class="px-4 py-3">
                        <div class="flex space-x-2">
                            <button onclick="openPaymentModal(${agent.id}, '${escapeHtml(agent.username)}', ${agent.balance}, ${isStoreOwner ? 'true' : 'false'})" 
                                    class="bg-green-500 hover:bg-green-600 text-white px-3 py-1 rounded text-sm transition-all">
                                <i class="fas fa-exchange-alt mr-1"></i>Transaction
                            </button>
                            ${!isStoreOwner ? `
                            <button onclick="openRoleChangeModal(${agent.id}, '${escapeHtml(agent.username)}', '${agent.role}')" 
                                    class="bg-blue-500 hover:bg-blue-600 text-white px-3 py-1 rounded text-sm transition-all">
                                <i class="fas fa-user-edit mr-1"></i>Change Role
                            </button>
                            ` : ''}
                            <a href="index.php?page=dashboard&action=delete&id=${agent.id}" 
                               onclick="return confirm('Are you sure you want to delete this ${isStoreOwner ? 'store owner' : 'agent'}? This action cannot be undone.')"
                               class="bg-red-500 hover:bg-red-600 text-white px-3 py-1 rounded text-sm transition-all">
                                <i class="fas fa-trash mr-1"></i>Delete
                            </a>
                        </div>
                    </td>
                `;
                tbody.appendChild(row);
            });
        }

        function updatePagination(pagination) {
            document.getElementById('showingStart').textContent = pagination.showing_start;
            document.getElementById('showingEnd').textContent = pagination.showing_end;
            document.getElementById('totalAgents').textContent = pagination.total_count;
            document.getElementById('pageInfo').textContent = `Page ${pagination.current_page} of ${pagination.total_pages}`;
            
            // Update button states
            document.getElementById('prevPage').disabled = pagination.current_page <= 1;
            document.getElementById('nextPage').disabled = pagination.current_page >= pagination.total_pages;
        }

        function changePage(direction) {
            const newPage = currentPage + direction;
            if (newPage >= 1) {
                currentPage = newPage;
                loadAgents();
            }
        }

        // Search and filter event listeners
        document.addEventListener('DOMContentLoaded', function() {
            const searchInput = document.getElementById('agentSearch');
            const typeFilter = document.getElementById('typeFilter');
            const sortBy = document.getElementById('sortBy');
            const itemsPerPage = document.getElementById('itemsPerPage');

            // Debounced search
            let searchTimeout;
            if (searchInput) {
                searchInput.addEventListener('input', function() {
                    clearTimeout(searchTimeout);
                    searchTimeout = setTimeout(() => {
                        currentSearch = this.value;
                        currentPage = 1; // Reset to first page
                        loadAgents();
                    }, 300);
                });
            }

            // Type filter (Store Owner vs Sub-Agent)
            if (typeFilter) {
                typeFilter.addEventListener('change', function() {
                    currentTypeFilter = this.value;
                    currentPage = 1; // Reset to first page
                    loadAgents();
                });
            }

            // Sort
            sortBy.addEventListener('change', function() {
                currentSort = this.value;
                currentPage = 1; // Reset to first page
                loadAgents();
            });

            // Items per page
            itemsPerPage.addEventListener('change', function() {
                currentLimit = parseInt(this.value);
                currentPage = 1; // Reset to first page
                loadAgents();
            });
        });

        // Toggle store agents view
        function toggleStoreAgents(storeId) {
            const agentsRow = document.getElementById('agents-row-' + storeId);
            if (agentsRow) {
                agentsRow.classList.toggle('hidden');
            }
        }

    </script>

