<?php
/**
 * Store Orders - View all orders from your store
 */

session_start();
require_once '../config.php';
require_once '../app/classes/StoreManager.php';
require_once '../app/classes/StorePricingManager.php';

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

$userId = $_SESSION['user_id'];

// Load store
$storeManager = new StoreManager($conn);
$store = $storeManager->getStoreByOwnerId($userId);

if (!$store) {
    header("Location: store_dashboard.php");
    exit();
}

// Include reusable navigation
require_once 'includes/store_nav.php';

// Get search parameter
$searchQuery = isset($_GET['search']) ? trim($_GET['search']) : '';
$hasSearch = !empty($searchQuery);

// Get date filter parameters
$dateFrom = isset($_GET['date_from']) ? trim($_GET['date_from']) : '';
$dateTo = isset($_GET['date_to']) ? trim($_GET['date_to']) : '';
$hasDateFilter = !empty($dateFrom) || !empty($dateTo);

// Get ALL orders for this store (from both orders and agent_orders tables)
$orders = [];

// Build WHERE conditions for direct orders
$directWhereConditions = ["o.store_id = ?"];

// Add date filter - prioritize date filter over default 1 day
if ($hasDateFilter) {
    if (!empty($dateFrom)) {
        $directWhereConditions[] = "DATE(o.created_at) >= ?";
    }
    if (!empty($dateTo)) {
        $directWhereConditions[] = "DATE(o.created_at) <= ?";
    }
} elseif (!$hasSearch) {
    // Default to last 1 day only if no search and no date filter
    $directWhereConditions[] = "o.created_at >= DATE_SUB(NOW(), INTERVAL 1 DAY)";
}

// Add search conditions if search is provided
if ($hasSearch) {
    $directWhereConditions[] = "(o.order_reference LIKE ? OR o.beneficiary_number LIKE ? OR o.id = ?)";
}

$directWhereClause = "WHERE " . implode(" AND ", $directWhereConditions);

// Get direct customer orders from 'orders' table
$directOrdersQuery = $conn->prepare("
    SELECT 
        o.id,
        o.order_reference,
        o.network_type,
        o.package_size,
        o.beneficiary_number as recipient_number,
        o.amount,
        o.status,
        o.created_at,
        a.username as agent_username,
        'direct' as order_type
    FROM orders o
    LEFT JOIN agents a ON o.agent_id = a.id
    $directWhereClause
    ORDER BY 
        CASE WHEN o.status = 'pending' THEN 0 ELSE 1 END,
        o.created_at DESC
");

// Build bind parameters dynamically
$paramTypes = "i";
$paramValues = [$store['id']];

if ($hasDateFilter) {
    if (!empty($dateFrom)) {
        $paramTypes .= "s";
        $paramValues[] = $dateFrom;
    }
    if (!empty($dateTo)) {
        $paramTypes .= "s";
        $paramValues[] = $dateTo;
    }
}

if ($hasSearch) {
    $searchPattern = '%' . $searchQuery . '%';
    $searchAsInt = intval($searchQuery);
    $searchAsInt = $searchAsInt > 0 ? $searchAsInt : 0;
    $paramTypes .= "ssi";
    $paramValues[] = $searchPattern;
    $paramValues[] = $searchPattern;
    $paramValues[] = $searchAsInt;
}

$directOrdersQuery->bind_param($paramTypes, ...$paramValues);

$directOrdersQuery->execute();
$directResult = $directOrdersQuery->get_result();
while ($row = $directResult->fetch_assoc()) {
    $orders[] = $row;
}
$directOrdersQuery->close();

// Build WHERE conditions for agent orders
$agentWhereConditions = ["ao.store_id = ?"];

// Add date filter - prioritize date filter over default 1 day
if ($hasDateFilter) {
    if (!empty($dateFrom)) {
        $agentWhereConditions[] = "DATE(ao.created_at) >= ?";
    }
    if (!empty($dateTo)) {
        $agentWhereConditions[] = "DATE(ao.created_at) <= ?";
    }
} elseif (!$hasSearch) {
    // Default to last 1 day only if no search and no date filter
    $agentWhereConditions[] = "ao.created_at >= DATE_SUB(NOW(), INTERVAL 1 DAY)";
}

// Add search conditions if search is provided
if ($hasSearch) {
    $agentWhereConditions[] = "(ao.beneficiary_number LIKE ? OR ao.id = ? OR a.username LIKE ?)";
}

$agentWhereClause = "WHERE " . implode(" AND ", $agentWhereConditions);

// Get agent orders from 'agent_orders' table
$agentOrdersQuery = $conn->prepare("
    SELECT 
        ao.id,
        ao.network_type,
        ao.package_size,
        ao.beneficiary_number as recipient_number,
        ao.amount,
        ao.status,
        ao.created_at,
        a.username as agent_username,
        'agent' as order_type
    FROM agent_orders ao
    INNER JOIN agents a ON ao.agent_id = a.id
    $agentWhereClause
    ORDER BY ao.created_at DESC
");

// Build bind parameters dynamically for agent orders
$agentParamTypes = "i";
$agentParamValues = [$store['id']];

if ($hasDateFilter) {
    if (!empty($dateFrom)) {
        $agentParamTypes .= "s";
        $agentParamValues[] = $dateFrom;
    }
    if (!empty($dateTo)) {
        $agentParamTypes .= "s";
        $agentParamValues[] = $dateTo;
    }
}

if ($hasSearch) {
    $searchPattern = '%' . $searchQuery . '%';
    $searchAsInt = intval($searchQuery);
    $searchAsInt = $searchAsInt > 0 ? $searchAsInt : 0;
    $agentParamTypes .= "sis";
    $agentParamValues[] = $searchPattern;
    $agentParamValues[] = $searchAsInt;
    $agentParamValues[] = $searchPattern;
}

$agentOrdersQuery->bind_param($agentParamTypes, ...$agentParamValues);

$agentOrdersQuery->execute();
$agentResult = $agentOrdersQuery->get_result();
while ($row = $agentResult->fetch_assoc()) {
    $orders[] = $row;
}
$agentOrdersQuery->close();

// Sort all orders by created_at DESC
usort($orders, function($a, $b) {
    return strtotime($b['created_at']) - strtotime($a['created_at']);
});

// Calculate profit for each order
function parsePackageSizeToGb($packageSize) {
    if (empty($packageSize)) return 0;
    $packageSize = trim($packageSize);
    
    if (stripos($packageSize, 'MB') !== false) {
        $num = floatval(preg_replace('/[^0-9.]/', '', $packageSize));
        return round($num / 1024, 4);
    }
    
    if (stripos($packageSize, 'GB') !== false) {
        $num = floatval(preg_replace('/[^0-9.]/', '', $packageSize));
        return round($num, 4);
    }
    
    $num = floatval(preg_replace('/[^0-9.]/', '', $packageSize));
    return round($num, 4);
}

// Get admin pricing for reference
$adminPricingRules = [];
$adminRulesStmt = $conn->prepare("SELECT min_size_gb, max_size_gb, price_per_gb FROM agent_pricing_rules WHERE network_type = 'mtn' AND role = 'agent' AND is_active = 1 ORDER BY min_size_gb");
if ($adminRulesStmt) {
    $adminRulesStmt->execute();
    $adminRulesResult = $adminRulesStmt->get_result();
    while ($row = $adminRulesResult->fetch_assoc()) {
        $adminPricingRules[] = $row;
    }
    $adminRulesStmt->close();
}

// Get store pricing manager
$storePricingManager = new StorePricingManager($conn);

// Calculate profit for each order
foreach ($orders as &$order) {
    $packageSizeGb = parsePackageSizeToGb($order['package_size']);
    $storePrice = $order['amount']; // What customer paid (store's price)
    
    // Get admin base price for this package from tiered pricing only
    $adminPrice = null;
    
        // Check tiered pricing
        foreach ($adminPricingRules as $rule) {
            if ($packageSizeGb >= $rule['min_size_gb'] && $packageSizeGb <= $rule['max_size_gb']) {
                $adminPrice = $rule['price_per_gb'] * $packageSizeGb;
                break;
        }
    }
    
    // Calculate profit
    if ($adminPrice !== null && $adminPrice > 0) {
        $order['profit'] = round($storePrice - $adminPrice, 2);
        $order['admin_price'] = $adminPrice;
    } else {
        $order['profit'] = null; // Can't calculate if admin price not found
        $order['admin_price'] = null;
    }
}
unset($order); // Break reference

// Calculate today's total profit
$today = date('Y-m-d');
$todayTotalProfit = 0;
foreach ($orders as $order) {
    if (isset($order['profit']) && $order['profit'] !== null && date('Y-m-d', strtotime($order['created_at'])) == $today) {
        $todayTotalProfit += $order['profit'];
    }
}

// Limit to most recent 100
$orders = array_slice($orders, 0, 100);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    
    <title>Store Orders - <?php echo htmlspecialchars($store['store_name']); ?></title>
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap');
        body { font-family: 'Poppins', sans-serif; background: linear-gradient(180deg, #0f172a 0%, #1e293b 100%); min-height: 100vh; }
    </style>
</head>

<body class="bg-gray-900">
    <?php renderStoreNav($store, 'orders'); ?>
    
    <!-- Back to Dashboard Button (Mobile) -->
    <div class="md:hidden bg-gray-800 border-b border-gray-700 px-3 py-2">
        <a href="store_dashboard.php" class="inline-flex items-center gap-2 text-blue-400 hover:text-blue-300 text-sm font-medium btn-touch">
            <i class="fas fa-arrow-left"></i>
            <span>Back to Dashboard</span>
        </a>
    </div>

    <div class="container mx-auto px-2 sm:px-4 py-3 sm:py-8">
        <!-- Order Statistics -->
        <div class="grid grid-cols-2 md:grid-cols-4 gap-2 sm:gap-4 mb-4 sm:mb-8">
            <?php
            $totalOrders = count($orders);
            $totalRevenue = array_sum(array_column($orders, 'amount'));
            $agentOrders = count(array_filter($orders, function($o) { return $o['order_type'] == 'agent'; }));
            $customerOrders = count(array_filter($orders, function($o) { return $o['order_type'] == 'direct'; }));
            $completedOrders = count(array_filter($orders, function($o) { return $o['status'] == 'completed'; }));
            ?>
            
            <div class="bg-gray-800 rounded-lg p-2 sm:p-4 border border-gray-700">
                <div class="text-gray-400 text-xs sm:text-sm mb-1">Total Orders</div>
                <div class="text-xl sm:text-3xl font-bold text-white"><?php echo $totalOrders; ?></div>
            </div>
            
            <div class="bg-gray-800 rounded-lg p-2 sm:p-4 border border-gray-700">
                <div class="text-gray-400 text-xs sm:text-sm mb-1">Total Revenue</div>
                <div class="text-xl sm:text-3xl font-bold text-green-400">GH₵<?php echo number_format($totalRevenue, 2); ?></div>
            </div>
            
            <div class="bg-gray-800 rounded-lg p-2 sm:p-4 border border-gray-700">
                <div class="text-gray-400 text-xs sm:text-sm mb-1">Agent Orders</div>
                <div class="text-xl sm:text-3xl font-bold text-blue-400"><?php echo $agentOrders; ?></div>
            </div>
            
            <div class="bg-gray-800 rounded-lg p-2 sm:p-4 border border-gray-700">
                <div class="text-gray-400 text-xs sm:text-sm mb-1">Customer Orders</div>
                <div class="text-xl sm:text-3xl font-bold text-purple-400"><?php echo $customerOrders; ?></div>
            </div>
        </div>
        
        <div class="bg-gray-800 rounded-lg p-3 sm:p-6 border border-gray-700">
            <div class="flex flex-col gap-4 mb-4 sm:mb-6">
                <!-- Search Bar and Date Filter -->
                <div class="flex flex-col gap-3">
                    <form method="GET" action="" class="flex flex-col sm:flex-row gap-2 sm:gap-3">
                        <!-- Search Input -->
                        <div class="flex-1 relative">
                            <input type="text" 
                                   name="search" 
                                   value="<?php echo htmlspecialchars($searchQuery); ?>" 
                                   placeholder="Search by order ID, reference, phone number, or agent name..." 
                                   class="w-full bg-gray-700 text-white px-4 py-2 pl-10 rounded-lg border border-gray-600 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 text-sm sm:text-base">
                            <i class="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                        </div>
                        
                        <!-- Date From -->
                        <div class="flex-shrink-0">
                            <input type="date" 
                                   name="date_from" 
                                   value="<?php echo htmlspecialchars($dateFrom); ?>" 
                                   placeholder="From Date"
                                   class="w-full bg-gray-700 text-white px-4 py-2 rounded-lg border border-gray-600 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 text-sm sm:text-base">
                        </div>
                        
                        <!-- Date To -->
                        <div class="flex-shrink-0">
                            <input type="date" 
                                   name="date_to" 
                                   value="<?php echo htmlspecialchars($dateTo); ?>" 
                                   placeholder="To Date"
                                   class="w-full bg-gray-700 text-white px-4 py-2 rounded-lg border border-gray-600 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 text-sm sm:text-base">
                        </div>
                        
                        <!-- Submit Button -->
                        <button type="submit" 
                                class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors text-sm sm:text-base font-semibold min-h-[44px] whitespace-nowrap">
                            <i class="fas fa-filter mr-1"></i><span class="hidden sm:inline">Filter</span><span class="sm:hidden">Go</span>
                        </button>
                        
                        <!-- Clear Button -->
                        <?php if ($hasSearch || $hasDateFilter): ?>
                        <a href="store_orders.php" 
                           class="px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition-colors text-sm sm:text-base font-semibold min-h-[44px] flex items-center justify-center whitespace-nowrap">
                            <i class="fas fa-times mr-1"></i><span class="hidden sm:inline">Clear</span><span class="sm:hidden">X</span>
                        </a>
                        <?php endif; ?>
                    </form>
                </div>
                
                <!-- Header and Filters -->
                <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
                    <h2 class="text-lg sm:text-2xl font-bold text-white">
                        <i class="fas fa-shopping-cart mr-2"></i>
                        All Store Orders
                        <?php if (!$hasSearch && !$hasDateFilter): ?>
                        <span class="text-sm text-gray-400 font-normal">(Last 24 hours)</span>
                        <?php elseif ($hasDateFilter): ?>
                        <span class="text-sm text-gray-400 font-normal">
                            (<?php echo !empty($dateFrom) ? date('M j, Y', strtotime($dateFrom)) : 'All time'; ?>
                            <?php if (!empty($dateFrom) && !empty($dateTo)): ?> - <?php endif; ?>
                            <?php echo !empty($dateTo) ? date('M j, Y', strtotime($dateTo)) : ''; ?>)
                        </span>
                        <?php endif; ?>
                    </h2>
                    <div class="flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-4">
                        <div class="text-xs sm:text-sm text-gray-400">
                            Showing: <?php echo count($orders); ?> orders
                        </div>
                        <div class="flex gap-1 sm:gap-2 flex-wrap">
                            <button onclick="filterOrders('all')" id="filter-all" 
                                    class="px-2 py-1 sm:px-3 sm:py-1 bg-gray-700 text-white rounded text-xs sm:text-sm hover:bg-gray-600">
                                All
                            </button>
                            <button onclick="filterOrders('pending')" id="filter-pending"
                                    class="px-2 py-1 sm:px-3 sm:py-1 bg-yellow-600 text-white rounded text-xs sm:text-sm hover:bg-yellow-700">
                                <i class="fas fa-clock mr-1"></i><span class="hidden sm:inline">Pending</span><span class="sm:hidden">Pend</span>
                            </button>
                            <button onclick="filterOrders('agent')" id="filter-agent"
                                    class="px-2 py-1 sm:px-3 sm:py-1 bg-gray-700 text-gray-300 rounded text-xs sm:text-sm hover:bg-gray-600">
                                <span class="hidden sm:inline">Agents</span><span class="sm:hidden">Agt</span>
                            </button>
                            <button onclick="filterOrders('direct')" id="filter-direct"
                                    class="px-2 py-1 sm:px-3 sm:py-1 bg-gray-700 text-gray-300 rounded text-xs sm:text-sm hover:bg-gray-600">
                                <span class="hidden sm:inline">Customers</span><span class="sm:hidden">Cust</span>
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <?php if (empty($orders)): ?>
            <div class="text-center py-8 sm:py-12">
                <i class="fas fa-<?php echo $hasSearch ? 'search' : 'shopping-cart'; ?> text-4xl sm:text-5xl text-gray-600 mb-3 sm:mb-4"></i>
                <?php if ($hasSearch): ?>
                <p class="text-sm sm:text-base text-gray-400 mb-3 sm:mb-4">No orders found matching "<?php echo htmlspecialchars($searchQuery); ?>".</p>
                <p class="text-xs sm:text-sm text-gray-500 mb-4">Try searching by order ID, reference number, phone number, or agent name.</p>
                <a href="store_orders.php" class="inline-block px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors text-sm sm:text-base">
                    <i class="fas fa-arrow-left mr-2"></i>View Recent Orders
                </a>
                <?php else: ?>
                <p class="text-sm sm:text-base text-gray-400 mb-3 sm:mb-4">No orders in the last 24 hours. Start getting orders by:</p>
                <div class="grid md:grid-cols-2 gap-3 sm:gap-4 max-w-lg mx-auto">
                    <div class="bg-blue-900 border border-blue-700 p-3 sm:p-4 rounded-lg text-left">
                        <div class="font-bold text-blue-300 mb-2 text-sm sm:text-base">
                            <i class="fas fa-users mr-2"></i>Invite Agents
                        </div>
                        <p class="text-xs sm:text-sm text-blue-200">Your agents place orders using your pricing</p>
                    </div>
                    <div class="bg-purple-900 border border-purple-700 p-3 sm:p-4 rounded-lg text-left">
                        <div class="font-bold text-purple-300 mb-2 text-sm sm:text-base">
                            <i class="fas fa-share-alt mr-2"></i>Share Store Link
                        </div>
                        <p class="text-xs sm:text-sm text-purple-200">Customers buy directly from your store</p>
                    </div>
                </div>
                <?php endif; ?>
            </div>
            <?php else: ?>
            <!-- Desktop Table View -->
            <div class="hidden md:block 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 text-sm">Order ID</th>
                            <th class="pb-3 text-gray-400 font-medium text-sm">Reference</th>
                            <th class="pb-3 text-gray-400 font-medium text-sm">Type</th>
                            <th class="pb-3 text-gray-400 font-medium text-sm">Agent/Customer</th>
                            <th class="pb-3 text-gray-400 font-medium text-sm">Package</th>
                            <th class="pb-3 text-gray-400 font-medium text-sm">Phone</th>
                            <th class="pb-3 text-gray-400 font-medium text-sm">Amount</th>
                            <th class="pb-3 text-gray-400 font-medium text-sm">Profit</th>
                            <th class="pb-3 text-gray-400 font-medium text-sm">Status</th>
                            <th class="pb-3 text-gray-400 font-medium text-sm">Actions</th>
                            <th class="pb-3 text-gray-400 font-medium text-sm">Date</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($orders as $index => $order): ?>
                        <tr class="border-b border-gray-700 hover:bg-gray-700/30 order-row <?php echo $order['status'] == 'pending' ? 'bg-yellow-900/20' : ''; ?>" data-type="<?php echo $order['order_type']; ?>" data-status="<?php echo $order['status']; ?>">
                            <td class="py-3 text-white text-sm">
                                #<?php echo $order['id']; ?>
                                <span class="text-xs text-gray-500"><?php echo strtoupper($order['order_type'][0]); ?></span>
                            </td>
                            <td class="py-3">
                                <?php if (!empty($order['order_reference'])): ?>
                                    <span class="px-2 py-1 bg-blue-900 text-blue-300 rounded text-xs font-mono font-bold">
                                        <?php echo htmlspecialchars($order['order_reference']); ?>
                                    </span>
                                <?php else: ?>
                                    <span class="text-gray-500 text-xs">N/A</span>
                                <?php endif; ?>
                            </td>
                            <td class="py-3">
                                <?php if ($order['order_type'] == 'agent'): ?>
                                <span class="px-2 py-1 bg-blue-900 text-blue-300 rounded text-xs">
                                    <i class="fas fa-user-tie mr-1"></i>Agent
                                </span>
                                <?php else: ?>
                                <span class="px-2 py-1 bg-purple-900 text-purple-300 rounded text-xs">
                                    <i class="fas fa-shopping-bag mr-1"></i>Customer
                                </span>
                                <?php endif; ?>
                            </td>
                            <td class="py-3 text-gray-300 text-sm">
                                <?php echo $order['agent_username'] ? htmlspecialchars($order['agent_username']) : 'Direct Customer'; ?>
                            </td>
                            <td class="py-3 text-white text-sm">
                                <i class="fas fa-mobile-alt text-yellow-400 mr-1"></i>
                                <?php echo htmlspecialchars($order['package_size']); ?>
                            </td>
                            <td class="py-3 text-gray-300 text-sm"><?php echo htmlspecialchars($order['recipient_number']); ?></td>
                            <td class="py-3 text-white font-bold text-sm">GH₵ <?php echo number_format($order['amount'], 2); ?></td>
                            <td class="py-3">
                                <?php if (isset($order['profit']) && $order['profit'] !== null): ?>
                                    <span class="font-bold text-sm <?php echo $order['profit'] >= 0 ? 'text-green-400' : 'text-red-400'; ?>">
                                        GH₵ <?php echo number_format($order['profit'], 2); ?>
                                    </span>
                                    <div class="text-xs text-gray-500 mt-1">
                                        Admin: GH₵ <?php echo number_format($order['admin_price'], 2); ?>
                                    </div>
                                <?php else: ?>
                                    <span class="text-gray-500 text-xs">N/A</span>
                                <?php endif; ?>
                            </td>
                            <td class="py-3">
                                <span class="px-2 py-1 rounded-full text-xs font-medium 
                                    <?php 
                                    if ($order['status'] == 'completed' || $order['status'] == 'delivered') echo 'bg-green-900 text-green-300';
                                    elseif ($order['status'] == 'pending') echo 'bg-yellow-900 text-yellow-300';
                                    else echo 'bg-red-900 text-red-300';
                                    ?>">
                                    <?php echo ucfirst($order['status']); ?>
                                </span>
                            </td>
                            <td class="py-3">
                                <?php if ($order['status'] == 'pending' && $order['order_type'] == 'direct'): ?>
                                    <div class="flex gap-2">
                                        <button onclick="processOrder(event, <?php echo $order['id']; ?>, '<?php echo htmlspecialchars($order['order_reference'] ?? ''); ?>')" 
                                                class="px-3 py-1.5 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors text-xs font-semibold">
                                            <i class="fas fa-check-circle mr-1"></i>Process
                                        </button>
                                        <button onclick="cancelOrder(event, <?php echo $order['id']; ?>, '<?php echo htmlspecialchars($order['order_reference'] ?? ''); ?>')" 
                                                class="px-3 py-1.5 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors text-xs font-semibold">
                                            <i class="fas fa-times-circle mr-1"></i>Cancel
                                        </button>
                                    </div>
                                <?php else: ?>
                                    <span class="text-gray-500 text-xs">-</span>
                                <?php endif; ?>
                            </td>
                            <td class="py-3 text-gray-300 text-xs">
                                <?php echo date('M d, Y', strtotime($order['created_at'])); ?>
                                <div class="text-xs text-gray-500"><?php echo date('H:i', strtotime($order['created_at'])); ?></div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            
            <!-- Mobile Card View -->
            <div class="md:hidden space-y-3">
                <?php foreach ($orders as $index => $order): ?>
                <div class="order-row bg-gray-700/50 rounded-lg p-3 border border-gray-600 <?php echo $order['status'] == 'pending' ? 'bg-yellow-900/20 border-yellow-700' : ''; ?>" data-type="<?php echo $order['order_type']; ?>" data-status="<?php echo $order['status']; ?>">
                    <div class="flex items-start justify-between mb-2">
                        <div class="flex-1 min-w-0">
                            <div class="flex items-center gap-2 mb-1">
                                <span class="text-white font-bold text-sm">#<?php echo $order['id']; ?></span>
                                <span class="text-xs text-gray-400"><?php echo strtoupper($order['order_type'][0]); ?></span>
                                <?php if ($order['order_type'] == 'agent'): ?>
                                <span class="px-1.5 py-0.5 bg-blue-900 text-blue-300 rounded text-xs">
                                    <i class="fas fa-user-tie mr-0.5"></i>Agent
                                </span>
                                <?php else: ?>
                                <span class="px-1.5 py-0.5 bg-purple-900 text-purple-300 rounded text-xs">
                                    <i class="fas fa-shopping-bag mr-0.5"></i>Customer
                                </span>
                                <?php endif; ?>
                                <span class="px-1.5 py-0.5 rounded-full text-xs font-medium 
                                    <?php 
                                    if ($order['status'] == 'completed' || $order['status'] == 'delivered') echo 'bg-green-900 text-green-300';
                                    elseif ($order['status'] == 'pending') echo 'bg-yellow-900 text-yellow-300';
                                    else echo 'bg-red-900 text-red-300';
                                    ?>">
                                    <?php echo ucfirst($order['status']); ?>
                                </span>
                            </div>
                            <?php if (!empty($order['order_reference'])): ?>
                            <div class="mb-1">
                                <span class="px-2 py-0.5 bg-blue-900 text-blue-300 rounded text-xs font-mono font-bold">
                                    <?php echo htmlspecialchars($order['order_reference']); ?>
                                </span>
                            </div>
                            <?php endif; ?>
                        </div>
                        <?php if ($order['status'] == 'pending' && $order['order_type'] == 'direct'): ?>
                        <div class="flex gap-2 flex-shrink-0 ml-2">
                            <button onclick="processOrder(event, <?php echo $order['id']; ?>, '<?php echo htmlspecialchars($order['order_reference'] ?? ''); ?>')" 
                                    class="px-4 py-2.5 bg-green-600 text-white rounded-lg text-sm font-semibold hover:bg-green-700 transition-colors min-h-[44px] flex items-center justify-center gap-1.5 flex-1">
                                <i class="fas fa-check-circle"></i>
                                <span>Process</span>
                            </button>
                            <button onclick="cancelOrder(event, <?php echo $order['id']; ?>, '<?php echo htmlspecialchars($order['order_reference'] ?? ''); ?>')" 
                                    class="px-4 py-2.5 bg-red-600 text-white rounded-lg text-sm font-semibold hover:bg-red-700 transition-colors min-h-[44px] flex items-center justify-center gap-1.5 flex-1">
                                <i class="fas fa-times-circle"></i>
                                <span>Cancel</span>
                            </button>
                        </div>
                        <?php endif; ?>
                    </div>
                    
                    <div class="grid grid-cols-2 gap-2 text-xs mb-2">
                        <div>
                            <span class="text-gray-400">Customer:</span>
                            <div class="text-white font-medium truncate"><?php echo $order['agent_username'] ? htmlspecialchars($order['agent_username']) : 'Direct'; ?></div>
                        </div>
                        <div>
                            <span class="text-gray-400">Phone:</span>
                            <div class="text-white font-mono"><?php echo htmlspecialchars($order['recipient_number']); ?></div>
                        </div>
                        <div>
                            <span class="text-gray-400">Package:</span>
                            <div class="text-white">
                                <i class="fas fa-mobile-alt text-yellow-400 mr-1"></i>
                                <?php echo htmlspecialchars($order['package_size']); ?>
                            </div>
                        </div>
                        <div>
                            <span class="text-gray-400">Amount:</span>
                            <div class="text-white font-bold">GH₵ <?php echo number_format($order['amount'], 2); ?></div>
                        </div>
                        <?php if (isset($order['profit']) && $order['profit'] !== null): ?>
                        <div>
                            <span class="text-gray-400">Profit:</span>
                            <div class="font-bold <?php echo $order['profit'] >= 0 ? 'text-green-400' : 'text-red-400'; ?>">
                                GH₵ <?php echo number_format($order['profit'], 2); ?>
                            </div>
                        </div>
                        <?php endif; ?>
                        <div>
                            <span class="text-gray-400">Date:</span>
                            <div class="text-white"><?php echo date('M d, H:i', strtotime($order['created_at'])); ?></div>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <script>
        function filterOrders(type) {
            const rows = document.querySelectorAll('.order-row');
            const buttons = document.querySelectorAll('[id^="filter-"]');
            
            // Reset all button styles
            buttons.forEach(btn => {
                btn.classList.remove('bg-blue-600', 'bg-yellow-600', 'text-white');
                btn.classList.add('bg-gray-700', 'text-gray-300');
            });
            
            // Highlight active filter
            const activeBtn = document.getElementById('filter-' + type);
            if (activeBtn) {
                activeBtn.classList.remove('bg-gray-700', 'text-gray-300');
                if (type === 'pending') {
                    activeBtn.classList.add('bg-yellow-600', 'text-white');
                } else {
                    activeBtn.classList.add('bg-blue-600', 'text-white');
                }
            }
            
            // Filter rows
            rows.forEach(row => {
                if (type === 'all') {
                    row.style.display = '';
                } else if (type === 'pending') {
                    row.style.display = row.dataset.status === 'pending' ? '' : 'none';
                } else {
                    row.style.display = row.dataset.type === type ? '' : 'none';
                }
            });
        }
        
        // Track processing orders to prevent duplicate requests
        const processingOrders = new Set();
        const cancellingOrders = new Set();
        
        function processOrder(event, orderId, orderReference) {
            // Prevent event bubbling
            if (event) {
                event.preventDefault();
                event.stopPropagation();
            }
            
            // Check if this order is already being processed
            if (processingOrders.has(orderId)) {
                alert('This order is already being processed. Please wait...');
                return;
            }
            
            if (!confirm(`Process order ${orderReference || '#' + orderId}?\n\nThis will:\n- Deduct from your balance\n- Send order to API (if enabled)\n- Process the data bundle`)) {
                return;
            }
            
            // Get the button that was clicked
            const btn = event ? event.target.closest('button') : null;
            if (!btn) {
                console.error('Could not find button element');
                return;
            }
            
            // Mark order as processing
            processingOrders.add(orderId);
            
            // Disable all process buttons for this order (desktop and mobile)
            const allProcessBtns = document.querySelectorAll(`button[onclick*="processOrder"][onclick*="${orderId}"]`);
            allProcessBtns.forEach(button => {
                button.disabled = true;
                button.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i>Processing...';
                button.classList.add('opacity-75', 'cursor-not-allowed');
            });
            
            fetch('../process_pending_order.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `order_id=${orderId}`
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                // Remove from processing set
                processingOrders.delete(orderId);
                
                if (data.success) {
                    alert('Order processed successfully! ' + (data.message || ''));
                    location.reload();
                } else {
                    alert('Failed to process order: ' + (data.message || 'Unknown error'));
                    // Re-enable buttons
                    allProcessBtns.forEach(button => {
                        button.disabled = false;
                        button.innerHTML = '<i class="fas fa-check-circle mr-1"></i>Process';
                        button.classList.remove('opacity-75', 'cursor-not-allowed');
                    });
                }
            })
            .catch(error => {
                console.error('Error:', error);
                // Remove from processing set
                processingOrders.delete(orderId);
                alert('An error occurred. Please try again.');
                // Re-enable buttons
                allProcessBtns.forEach(button => {
                    button.disabled = false;
                    button.innerHTML = '<i class="fas fa-check-circle mr-1"></i>Process';
                    button.classList.remove('opacity-75', 'cursor-not-allowed');
                });
            });
        }
        
        function cancelOrder(event, orderId, orderReference) {
            // Prevent event bubbling
            if (event) {
                event.preventDefault();
                event.stopPropagation();
            }
            
            // Check if this order is already being cancelled
            if (cancellingOrders.has(orderId)) {
                alert('This order is already being cancelled. Please wait...');
                return;
            }
            
            if (!confirm(`Cancel order ${orderReference || '#' + orderId}?\n\nThis will mark the order as failed.\n\nOnly cancel if you have confirmed that the customer did NOT make payment.`)) {
                return;
            }
            
            // Get the button that was clicked
            const btn = event ? event.target.closest('button') : null;
            if (!btn) {
                console.error('Could not find button element');
                return;
            }
            
            // Mark order as cancelling
            cancellingOrders.add(orderId);
            
            // Disable all cancel buttons for this order (desktop and mobile)
            const allCancelBtns = document.querySelectorAll(`button[onclick*="cancelOrder"][onclick*="${orderId}"]`);
            allCancelBtns.forEach(button => {
                button.disabled = true;
                button.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i>Cancelling...';
                button.classList.add('opacity-75', 'cursor-not-allowed');
            });
            
            fetch('../cancel_order.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `order_id=${orderId}`
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                // Remove from cancelling set
                cancellingOrders.delete(orderId);
                
                if (data.success) {
                    alert('Order cancelled successfully! ' + (data.message || ''));
                    location.reload();
                } else {
                    alert('Failed to cancel order: ' + (data.message || 'Unknown error'));
                    // Re-enable buttons
                    allCancelBtns.forEach(button => {
                        button.disabled = false;
                        button.innerHTML = '<i class="fas fa-times-circle mr-1"></i>Cancel';
                        button.classList.remove('opacity-75', 'cursor-not-allowed');
                    });
                }
            })
            .catch(error => {
                console.error('Error:', error);
                // Remove from cancelling set
                cancellingOrders.delete(orderId);
                alert('An error occurred. Please try again.');
                // Re-enable buttons
                allCancelBtns.forEach(button => {
                    button.disabled = false;
                    button.innerHTML = '<i class="fas fa-times-circle mr-1"></i>Cancel';
                    button.classList.remove('opacity-75', 'cursor-not-allowed');
                });
            });
        }
    </script>
    
    <script>
        // Mobile menu toggle
        document.getElementById('mobileMenuBtn').addEventListener('click', function() {
            const menu = document.getElementById('mobileMenu');
            menu.classList.toggle('hidden');
        });
        
        // Close mobile menu when clicking outside
        document.addEventListener('click', function(e) {
            const menu = document.getElementById('mobileMenu');
            const btn = document.getElementById('mobileMenuBtn');
            if (!menu.contains(e.target) && !btn.contains(e.target)) {
                menu.classList.add('hidden');
            }
        });
    </script>
    
    <style>
        .btn-touch {
            min-height: 44px;
            min-width: 44px;
        }
        
        /* Mobile-specific styles */
        @media (max-width: 768px) {
            .order-row {
                font-size: 0.875rem;
            }
        }
    </style>
</body>
</html>

