<?php
// Get filter parameters
$filter_date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');
$filter_date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$filter_date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';
$filter_phone = isset($_GET['phone']) ? trim($_GET['phone']) : '';
$filter_status = isset($_GET['status']) ? $_GET['status'] : '';
$filter_network = isset($_GET['network']) ? $_GET['network'] : '';
$filter_type = isset($_GET['type']) ? $_GET['type'] : 'all'; // all, agent_orders, regular_orders

// Build queries based on user role
$orders_data = [];
$total_stats = [
    'total_orders' => 0,
    'delivered_orders' => 0,
    'pending_orders' => 0,
    'failed_orders' => 0,
    'total_amount' => 0,
    'total_package_size_gb' => 0
];

// Build WHERE conditions
$where_conditions = [];
$params = [];
$param_types = '';

// Date filtering
if (!empty($filter_date_from) && !empty($filter_date_to)) {
    $where_conditions[] = "DATE(created_at) BETWEEN ? AND ?";
    $params[] = $filter_date_from;
    $params[] = $filter_date_to;
    $param_types .= 'ss';
} elseif (!empty($filter_date)) {
    $where_conditions[] = "DATE(created_at) = ?";
    $params[] = $filter_date;
    $param_types .= 's';
}

// Phone filtering
if (!empty($filter_phone)) {
    $where_conditions[] = "beneficiary_number LIKE ?";
    $params[] = '%' . $filter_phone . '%';
    $param_types .= 's';
}

// Status filtering
if (!empty($filter_status)) {
    $where_conditions[] = "status = ?";
    $params[] = $filter_status;
    $param_types .= 's';
}

// Network filtering
if (!empty($filter_network)) {
    $where_conditions[] = "network_type = ?";
    $params[] = $filter_network;
    $param_types .= 's';
}

// User-specific filtering (only show their own orders)
$where_conditions[] = "agent_id = ?";
$params[] = $user_id;
$param_types .= 'i';

$where_clause = !empty($where_conditions) ? 'WHERE ' . implode(' AND ', $where_conditions) : '';

// Get orders data
$orders_query = "SELECT * FROM agent_orders $where_clause ORDER BY created_at DESC LIMIT 100";
$orders_stmt = $conn->prepare($orders_query);

if (!empty($params)) {
    $orders_stmt->bind_param($param_types, ...$params);
}

$orders_stmt->execute();
$orders_result = $orders_stmt->get_result();

while ($order = $orders_result->fetch_assoc()) {
    $orders_data[] = $order;
    
    // Update statistics
    $total_stats['total_orders']++;
    $total_stats['total_amount'] += floatval($order['amount']);
    
    // Extract package size in GB
    $package_size = floatval(str_replace(['GB', 'gb'], '', $order['package_size']));
    $total_stats['total_package_size_gb'] += $package_size;
    
    // Count by status
    switch ($order['status']) {
        case 'delivered':
            $total_stats['delivered_orders']++;
            break;
        case 'pending':
        case 'processing':
            $total_stats['pending_orders']++;
            break;
        case 'failed':
        case 'api_failed':
            $total_stats['failed_orders']++;
            break;
    }
}

$orders_stmt->close();
?>

<!-- Today's Orders Section -->
<div class="glass-card rounded-2xl p-6 mb-6 shadow-lg border border-slate-600/50">
    <div class="flex items-center justify-between mb-6">
        <h2 class="text-xl font-bold text-white">
            <i class="fas fa-chart-line mr-2 text-amber-400"></i>Order History
        </h2>
        <div class="flex items-center space-x-2">
            <span class="px-3 py-1 bg-blue-500/20 text-blue-400 border border-blue-500/30 rounded-full text-sm font-medium">
                <?php echo $total_stats['total_orders']; ?> orders
            </span>
        </div>
    </div>

    <!-- Statistics Cards -->
    <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
        <div class="glass-card-light rounded-xl p-4 border border-slate-600/50">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-blue-400 font-medium">Total Orders</p>
                    <p class="text-2xl font-bold text-white"><?php echo $total_stats['total_orders']; ?></p>
                </div>
                <div class="w-10 h-10 bg-blue-500 rounded-lg flex items-center justify-center shadow-lg">
                    <i class="fas fa-shopping-cart text-white"></i>
                </div>
            </div>
        </div>
        
        <div class="glass-card-light rounded-xl p-4 border border-slate-600/50">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-green-400 font-medium">Delivered</p>
                    <p class="text-2xl font-bold text-white"><?php echo $total_stats['delivered_orders']; ?></p>
                </div>
                <div class="w-10 h-10 bg-green-500 rounded-lg flex items-center justify-center shadow-lg">
                    <i class="fas fa-check-circle text-white"></i>
                </div>
            </div>
        </div>
        
        <div class="glass-card-light rounded-xl p-4 border border-slate-600/50">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-yellow-400 font-medium">Pending</p>
                    <p class="text-2xl font-bold text-white"><?php echo $total_stats['pending_orders']; ?></p>
                </div>
                <div class="w-10 h-10 bg-yellow-500 rounded-lg flex items-center justify-center shadow-lg">
                    <i class="fas fa-clock text-white"></i>
                </div>
            </div>
        </div>
        
        <div class="glass-card-light rounded-xl p-4 border border-slate-600/50">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-red-400 font-medium">Failed</p>
                    <p class="text-2xl font-bold text-white"><?php echo $total_stats['failed_orders']; ?></p>
                </div>
                <div class="w-10 h-10 bg-red-500 rounded-lg flex items-center justify-center shadow-lg">
                    <i class="fas fa-times-circle text-white"></i>
                </div>
            </div>
        </div>
    </div>

    <!-- Summary Stats -->
    <div class="glass-card-light rounded-xl p-4 mb-6 border border-slate-600/50">
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div class="text-center">
                <p class="text-2xl font-bold text-white"><?php echo number_format($total_stats['total_amount'], 2); ?> GHS</p>
                <p class="text-sm text-gray-400">Total Amount</p>
            </div>
            <div class="text-center">
                <p class="text-2xl font-bold text-white"><?php echo number_format($total_stats['total_package_size_gb'], 1); ?> GB</p>
                <p class="text-sm text-gray-400">Total Data</p>
            </div>
            <div class="text-center">
                <p class="text-2xl font-bold text-white"><?php echo $total_stats['total_orders'] > 0 ? number_format(($total_stats['delivered_orders'] / $total_stats['total_orders']) * 100, 1) : 0; ?>%</p>
                <p class="text-sm text-gray-400">Success Rate</p>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="glass-card-light rounded-xl p-4 mb-6 border border-slate-600/50">
        <h3 class="text-lg font-semibold text-white mb-4">
            <i class="fas fa-filter mr-2 text-amber-400"></i>Filters
        </h3>
        
        <form method="GET" class="space-y-4">
            <input type="hidden" name="page" value="today_orders">
            
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                <!-- Date Range -->
                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-2">Date From</label>
                    <input type="date" name="date_from" value="<?php echo htmlspecialchars($filter_date_from); ?>" 
                           class="w-full border border-slate-600 rounded-lg px-3 py-2 bg-slate-800/50 text-white focus:ring-2 focus:ring-amber-500 focus:border-amber-500">
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-2">Date To</label>
                    <input type="date" name="date_to" value="<?php echo htmlspecialchars($filter_date_to); ?>" 
                           class="w-full border border-slate-600 rounded-lg px-3 py-2 bg-slate-800/50 text-white focus:ring-2 focus:ring-amber-500 focus:border-amber-500">
                </div>
                
                <!-- Phone Number -->
                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-2">Phone Number</label>
                    <input type="text" name="phone" value="<?php echo htmlspecialchars($filter_phone); ?>" 
                           placeholder="Search by phone..."
                           class="w-full border border-slate-600 rounded-lg px-3 py-2 bg-slate-800/50 text-white placeholder-gray-500 focus:ring-2 focus:ring-amber-500 focus:border-amber-500">
                </div>
                
                <!-- Status -->
                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-2">Status</label>
                    <select name="status" class="w-full border border-slate-600 rounded-lg px-3 py-2 bg-slate-800/50 text-white focus:ring-2 focus:ring-amber-500 focus:border-amber-500">
                        <option value="">All Statuses</option>
                        <option value="pending" <?php echo $filter_status === 'pending' ? 'selected' : ''; ?>>Pending</option>
                        <option value="processing" <?php echo $filter_status === 'processing' ? 'selected' : ''; ?>>Processing</option>
                        <option value="delivered" <?php echo $filter_status === 'delivered' ? 'selected' : ''; ?>>Delivered</option>
                        <option value="failed" <?php echo $filter_status === 'failed' ? 'selected' : ''; ?>>Failed</option>
                        <option value="api_failed" <?php echo $filter_status === 'api_failed' ? 'selected' : ''; ?>>API Failed</option>
                    </select>
                </div>
            </div>
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <!-- Network -->
                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-2">Network</label>
                    <select name="network" class="w-full border border-slate-600 rounded-lg px-3 py-2 bg-slate-800/50 text-white focus:ring-2 focus:ring-amber-500 focus:border-amber-500">
                        <option value="">All Orders</option>
                        <option value="mtn" <?php echo $filter_network === 'mtn' ? 'selected' : ''; ?>>MTN</option>
                    </select>
                </div>
                
                <!-- Action Buttons -->
                <div class="flex items-end space-x-2">
                    <button type="submit" class="bg-gradient-to-r from-amber-500 to-yellow-600 text-white px-6 py-2 rounded-lg font-medium hover:from-amber-600 hover:to-yellow-700 transition-all hover-glow">
                        <i class="fas fa-search mr-2"></i>Apply Filters
                    </button>
                    <a href="?page=today_orders" class="border border-slate-600 text-gray-300 px-6 py-2 rounded-lg font-medium hover:bg-slate-700/50 hover:text-white transition-colors">
                        <i class="fas fa-times mr-2"></i>Clear
                    </a>
                </div>
            </div>
        </form>
    </div>

    <!-- Orders Cards -->
    <div class="space-y-4">
        <?php if (empty($orders_data)): ?>
            <div class="glass-card-light rounded-xl p-8 text-center border border-slate-600/50">
                <i class="fas fa-inbox text-gray-600 text-5xl mb-4"></i>
                <p class="text-lg text-white font-medium">No orders found</p>
                <p class="text-sm text-gray-400 mt-2">Try adjusting your filters or check back later</p>
            </div>
        <?php else: ?>
            <?php foreach ($orders_data as $order): ?>
            <div class="glass-card-light rounded-xl p-3 border border-slate-600/50 hover:border-amber-500/50 transition-all duration-300">
                <div class="flex flex-wrap items-center gap-3 md:gap-6">
                    <!-- Order ID -->
                    <div class="flex items-center gap-2">
                        <span class="font-mono text-xs bg-slate-800/50 text-amber-400 px-2 py-1 rounded border border-slate-600">#<?php echo $order['id']; ?></span>
                    </div>
                    
                    <!-- Status -->
                    <div>
                        <span class="inline-flex items-center px-2.5 py-1 text-xs font-medium rounded-full
                            <?php 
                            switch($order['status']) {
                                case 'delivered': echo 'bg-green-500/20 text-green-400 border border-green-500/30'; break;
                                case 'pending': echo 'bg-yellow-500/20 text-yellow-400 border border-yellow-500/30'; break;
                                case 'processing': echo 'bg-blue-500/20 text-blue-400 border border-blue-500/30'; break;
                                case 'failed': 
                                case 'api_failed': echo 'bg-red-500/20 text-red-400 border border-red-500/30'; break;
                                default: echo 'bg-gray-500/20 text-gray-400 border border-gray-500/30';
                            }
                            ?>">
                            <i class="fas fa-circle text-xs mr-1"></i>
                            <?php echo ucfirst(str_replace('_', ' ', $order['status'])); ?>
                        </span>
                    </div>
                    
                    <!-- Phone -->
                    <div class="flex items-center gap-2">
                        <i class="fas fa-phone text-amber-400 text-xs"></i>
                        <span class="text-white text-sm font-medium"><?php echo htmlspecialchars($order['beneficiary_number']); ?></span>
                    </div>
                    
                    <!-- Network -->
                    <div>
                        <span class="inline-flex items-center px-2 py-1 text-xs font-medium rounded-full
                            <?php 
                            switch($order['network_type']) {
                                case 'mtn': echo 'bg-yellow-500/20 text-yellow-400 border border-yellow-500/30'; break;
                                case 'telecel': echo 'bg-red-500/20 text-red-400 border border-red-500/30'; break;
                                case 'airtel_tigo': echo 'bg-orange-500/20 text-orange-400 border border-orange-500/30'; break;
                                default: echo 'bg-gray-500/20 text-gray-400 border border-gray-500/30';
                            }
                            ?>">
                            <?php echo strtoupper($order['network_type']); ?>
                        </span>
                    </div>
                    
                    <!-- Package -->
                    <div class="flex items-center gap-2">
                        <i class="fas fa-database text-blue-400 text-xs"></i>
                        <span class="text-white text-sm font-medium"><?php echo htmlspecialchars($order['package_size']); ?></span>
                    </div>
                    
                    <!-- Amount -->
                    <div class="flex items-center gap-1">
                        <span class="text-green-400 font-bold text-sm"><?php echo number_format($order['amount'], 2); ?> GHS</span>
                    </div>
                    
                    <!-- Date & Time -->
                    <div class="flex items-center gap-3 ml-auto">
                        <div class="flex items-center gap-1 text-gray-400 text-xs">
                            <i class="fas fa-calendar text-purple-400"></i>
                            <span><?php echo date('M j, Y', strtotime($order['created_at'])); ?></span>
                        </div>
                        <div class="flex items-center gap-1 text-gray-400 text-xs">
                            <i class="fas fa-clock"></i>
                            <span><?php echo date('g:i A', strtotime($order['created_at'])); ?></span>
                        </div>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>

    <!-- Pagination Info -->
    <?php if (!empty($orders_data)): ?>
    <div class="mt-6 text-center">
        <p class="text-sm text-gray-400">
            <i class="fas fa-info-circle mr-1"></i>
            Showing <?php echo count($orders_data); ?> orders (limited to 100 most recent)
        </p>
    </div>
    <?php endif; ?>
</div>

<!-- Export Options -->
<?php if (!empty($orders_data)): ?>
<div class="glass-card rounded-2xl p-6 shadow-lg border border-slate-600/50">
    <h3 class="text-lg font-bold text-white mb-4">
        <i class="fas fa-download mr-2 text-amber-400"></i>Export Data
    </h3>
    
    <div class="flex flex-wrap gap-3">
        <button onclick="exportToCSV()" class="bg-green-500 text-white px-4 py-2 rounded-lg font-medium hover:bg-green-600 transition-all hover-glow">
            <i class="fas fa-file-csv mr-2"></i>Export as CSV
        </button>
        <button onclick="printOrders()" class="bg-blue-500 text-white px-4 py-2 rounded-lg font-medium hover:bg-blue-600 transition-all hover-glow">
            <i class="fas fa-print mr-2"></i>Print Orders
        </button>
    </div>
</div>
<?php endif; ?>

<script>
    function exportToCSV() {
        const orders = <?php echo json_encode($orders_data); ?>;
        const headers = ['Order ID', 'Phone Number', 'Package Size', 'Network', 'Amount (GHS)', 'Status', 'Date'];
        
        let csvContent = headers.join(',') + '\n';
        
        orders.forEach(order => {
            const row = [
                order.id,
                order.beneficiary_number,
                order.package_size,
                order.network_type.toUpperCase(),
                order.amount,
                order.status.replace('_', ' '),
                new Date(order.created_at).toLocaleString()
            ];
            csvContent += row.join(',') + '\n';
        });
        
        const blob = new Blob([csvContent], { type: 'text/csv' });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'orders_<?php echo date('Y-m-d'); ?>.csv';
        a.click();
        window.URL.revokeObjectURL(url);
    }
    
    function printOrders() {
        window.print();
    }
</script>
