<?php
// All Orders Management Page Content

// Set timezone
date_default_timezone_set('GMT');

// Set page variables for header
$page_title = 'All Orders';
$page_description = 'View and manage all orders across the platform';
?>

<?php
// Get filter parameters
$filterAgent = isset($_GET['agent_id']) ? intval($_GET['agent_id']) : '';
$startDate = isset($_GET['start_date']) ? $_GET['start_date'] : '';
$endDate = isset($_GET['end_date']) ? $_GET['end_date'] : '';

// Build query with filters
$whereConditions = [];
$params = [];

if ($filterAgent) {
    $whereConditions[] = "o.user_id = ?";
    $params[] = $filterAgent;
}

if ($startDate && $endDate) {
    $whereConditions[] = "DATE(o.created_at) BETWEEN ? AND ?";
    $params[] = $startDate;
    $params[] = $endDate;
} elseif ($startDate) {
    $whereConditions[] = "DATE(o.created_at) >= ?";
    $params[] = $startDate;
} elseif ($endDate) {
    $whereConditions[] = "DATE(o.created_at) <= ?";
    $params[] = $endDate;
}

$whereClause = !empty($whereConditions) ? "WHERE " . implode(" AND ", $whereConditions) : "";

// Get all orders with agent information and balance after each order
$query = "
    SELECT 
        o.id,
        o.user_id,
        o.package_size,
        o.amount,
        o.beneficiary_number,
        o.created_at,
        COALESCE(a.username, CONCAT('Agent #', o.user_id), 'Unknown Agent') as username,
        a.username as uniqueID,
        a.role,
        (
            SELECT COALESCE(SUM(op.total_amount), 0) 
            FROM orders_payments op 
            WHERE op.user_id = o.user_id AND op.payment_date <= o.created_at
        ) - (
            SELECT COALESCE(SUM(ord.amount), 0) 
            FROM orders ord 
            WHERE ord.user_id = o.user_id AND ord.created_at <= o.created_at
        ) AS balance_after_order
    FROM orders o
    LEFT JOIN agents a ON o.user_id = a.id
    $whereClause
    ORDER BY o.created_at DESC
";

$stmt = $conn->prepare($query);
if (!empty($params)) {
    $types = str_repeat('s', count($params));
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result();

// Get all agents for filter dropdown
$agentsQuery = "SELECT id, username, role FROM agents ORDER BY username";
$agentsResult = mysqli_query($conn, $agentsQuery);

// Calculate totals
$totalOrders = 0;
$totalRevenue = 0;
$orders = [];
while ($row = mysqli_fetch_assoc($result)) {
    $orders[] = $row;
    $totalOrders++;
    $totalRevenue += floatval($row['amount']);
}
?>

<!-- Statistics Cards -->
<div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
    <div class="bg-gray-800 rounded-2xl p-6 card-shadow border border-gray-700">
        <div class="flex items-center justify-between">
            <div>
                <p class="text-gray-300 text-sm">Total Orders</p>
                <p class="text-3xl font-bold text-blue-600"><?= number_format($totalOrders) ?></p>
            </div>
            <div class="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center">
                <i class="fas fa-shopping-cart text-blue-600 text-xl"></i>
            </div>
        </div>
    </div>

    <div class="bg-gray-800 rounded-2xl p-6 card-shadow border border-gray-700">
        <div class="flex items-center justify-between">
            <div>
                <p class="text-gray-300 text-sm">Total Revenue</p>
                <p class="text-3xl font-bold text-green-600">GHS <?= number_format($totalRevenue, 2) ?></p>
            </div>
            <div class="w-12 h-12 bg-green-100 rounded-full flex items-center justify-center">
                <i class="fas fa-money-bill-wave text-green-600 text-xl"></i>
            </div>
        </div>
    </div>

    <div class="bg-gray-800 rounded-2xl p-6 card-shadow border border-gray-700">
        <div class="flex items-center justify-between">
            <div>
                <p class="text-gray-300 text-sm">Active Agents</p>
                <p class="text-3xl font-bold text-purple-600"><?= mysqli_num_rows($agentsResult) ?></p>
            </div>
            <div class="w-12 h-12 bg-purple-100 rounded-full flex items-center justify-center">
                <i class="fas fa-users text-purple-600 text-xl"></i>
            </div>
        </div>
    </div>
</div>

<!-- Filters Section -->
<div class="bg-gray-800 rounded-2xl p-6 card-shadow border border-gray-700 mb-8">
    <div class="text-center mb-6">
        <div class="w-16 h-16 bg-gradient-to-r from-orange-500 to-red-600 rounded-full flex items-center justify-center mx-auto mb-4">
            <i class="fas fa-filter text-white text-2xl"></i>
        </div>
        <h2 class="text-2xl font-bold text-gray-100 mb-2">Filter Orders</h2>
        <p class="text-gray-300">Search and filter orders by various criteria</p>
    </div>

    <form method="GET" action="" class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div>
            <label for="agent_id" class="block text-gray-700 font-medium mb-2">
                <i class="fas fa-user mr-2"></i>Agent
            </label>
            <select name="agent_id" id="agent_id" class="w-full border-2 border-gray-600 bg-gray-700 text-gray-100 rounded-xl p-3 input-focus">
                <option value="">All Agents</option>
                <?php 
                mysqli_data_seek($agentsResult, 0);
                while ($agent = mysqli_fetch_assoc($agentsResult)): 
                ?>
                <option value="<?= $agent['id'] ?>" <?= $filterAgent == $agent['id'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars($agent['username']) ?>
                </option>
                <?php endwhile; ?>
            </select>
        </div>

        <div>
            <label for="start_date" class="block text-gray-700 font-medium mb-2">
                <i class="fas fa-calendar mr-2"></i>Start Date
            </label>
            <input type="date" name="start_date" id="start_date" value="<?= htmlspecialchars($startDate) ?>" 
                    class="w-full border-2 border-gray-600 bg-gray-700 text-gray-100 rounded-xl p-3 input-focus">
        </div>

        <div>
            <label for="end_date" class="block text-gray-700 font-medium mb-2">
                <i class="fas fa-calendar mr-2"></i>End Date
            </label>
            <input type="date" name="end_date" id="end_date" value="<?= htmlspecialchars($endDate) ?>" 
                    class="w-full border-2 border-gray-600 bg-gray-700 text-gray-100 rounded-xl p-3 input-focus">
        </div>

        <div class="flex items-end">
            <button type="submit" class="w-full bg-gradient-to-r from-blue-500 to-purple-600 text-white py-3 rounded-xl font-medium hover:from-blue-600 hover:to-purple-700 transition-all">
                <i class="fas fa-search mr-2"></i>Filter
            </button>
        </div>
    </form>

    <!-- Quick Date Range Buttons -->
    <div class="mt-4 text-center">
        <p class="text-gray-300 mb-3">Quick Date Ranges:</p>
        <div class="flex flex-wrap justify-center gap-2">
            <button type="button" onclick="setDateRange('today')" class="bg-blue-100 text-blue-700 px-4 py-2 rounded-lg hover:bg-blue-200 transition-all text-sm">
                <i class="fas fa-calendar-day mr-1"></i>Today
            </button>
            <button type="button" onclick="setDateRange('yesterday')" class="bg-blue-100 text-blue-700 px-4 py-2 rounded-lg hover:bg-blue-200 transition-all text-sm">
                <i class="fas fa-calendar-minus mr-1"></i>Yesterday
            </button>
            <button type="button" onclick="setDateRange('last7days')" class="bg-green-100 text-green-700 px-4 py-2 rounded-lg hover:bg-green-200 transition-all text-sm">
                <i class="fas fa-calendar-week mr-1"></i>Last 7 Days
            </button>
            <button type="button" onclick="setDateRange('last30days')" class="bg-green-100 text-green-700 px-4 py-2 rounded-lg hover:bg-green-200 transition-all text-sm">
                <i class="fas fa-calendar-alt mr-1"></i>Last 30 Days
            </button>
            <button type="button" onclick="setDateRange('thisMonth')" class="bg-purple-100 text-purple-700 px-4 py-2 rounded-lg hover:bg-purple-200 transition-all text-sm">
                <i class="fas fa-calendar mr-1"></i>This Month
            </button>
            <button type="button" onclick="setDateRange('lastMonth')" class="bg-purple-100 text-purple-700 px-4 py-2 rounded-lg hover:bg-purple-200 transition-all text-sm">
                <i class="fas fa-calendar-check mr-1"></i>Last Month
            </button>
        </div>
    </div>

    <!-- Clear Filters -->
    <div class="mt-4 text-center">
        <a href="index.php?page=all_orders" class="bg-gray-500 text-white px-6 py-2 rounded-xl hover:bg-gray-600 transition-all">
            <i class="fas fa-times mr-2"></i>Clear All Filters
        </a>
    </div>
</div>

<!-- Orders Table -->
<div class="bg-gray-800 rounded-2xl p-6 card-shadow border border-gray-700">
    <div class="text-center mb-6">
        <div class="w-16 h-16 bg-gradient-to-r from-green-500 to-blue-600 rounded-full flex items-center justify-center mx-auto mb-4">
            <i class="fas fa-table text-white text-2xl"></i>
        </div>
        <h2 class="text-2xl font-bold text-gray-100 mb-2">Orders List</h2>
        <p class="text-gray-300">Search and filter orders using the search box below</p>
    </div>

    <div class="overflow-x-auto">
        <table id="ordersTable" class="w-full">
            <thead>
                <tr>
                    <th>Order ID</th>
                    <th>Agent</th>
                    <th>Unique ID</th>
                    <th>Role</th>
                    <th>Package</th>
                    <th>Amount (GHS)</th>
                    <th>Beneficiary</th>
                    <th>Balance After</th>
                    <th>Date & Time</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($orders as $order): ?>
                <tr>
                    <td>
                        <span class="font-bold text-blue-600">#<?= $order['id'] ?></span>
                    </td>
                    <td>
                        <span class="font-medium text-gray-100"><?= htmlspecialchars($order['username']) ?></span>
                    </td>
                    <td>
                        <span class="text-gray-300"><?= htmlspecialchars($order['uniqueID'] ?: 'N/A') ?></span>
                    </td>
                    <td>
                        <span class="px-2 py-1 rounded-full text-xs font-medium 
                            <?= $order['role'] == 'dealer' ? 'bg-red-100 text-red-800' : 
                               ($order['role'] == 'super_agent' ? 'bg-yellow-100 text-yellow-800' : 
                               'bg-blue-100 text-blue-800') ?>">
                            <?= ucfirst(str_replace('_', ' ', $order['role'] ?: 'agent')) ?>
                        </span>
                    </td>
                    <td>
                        <span class="font-medium text-gray-700"><?= htmlspecialchars($order['package_size']) ?></span>
                    </td>
                    <td>
                        <span class="font-bold text-green-600"><?= number_format($order['amount'], 2) ?></span>
                    </td>
                    <td>
                        <span class="font-medium text-gray-100"><?= htmlspecialchars($order['beneficiary_number']) ?></span>
                    </td>
                    <td>
                        <span class="font-bold <?= floatval($order['balance_after_order']) >= 0 ? 'text-green-600' : 'text-red-600' ?>">
                            GHS <?= number_format($order['balance_after_order'], 2) ?>
                        </span>
                    </td>
                    <td>
                        <span class="text-gray-300"><?= date('Y-m-d H:i:s', strtotime($order['created_at'] . ' +4 hours')) ?></span>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Export Section -->
<div class="bg-gray-800 rounded-2xl p-6 card-shadow border border-gray-700 mt-8">
    <div class="text-center mb-6">
        <div class="w-16 h-16 bg-gradient-to-r from-purple-500 to-pink-600 rounded-full flex items-center justify-center mx-auto mb-4">
            <i class="fas fa-download text-white text-2xl"></i>
        </div>
        <h2 class="text-2xl font-bold text-gray-100 mb-2">Export Data</h2>
        <p class="text-gray-300">Download orders data in various formats</p>
    </div>

    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
        <button onclick="exportToCSV()" class="bg-green-500 text-white py-3 rounded-xl font-medium hover:bg-green-600 transition-all">
            <i class="fas fa-file-csv mr-2"></i>Export to CSV
        </button>
        <button onclick="exportToExcel()" class="bg-blue-500 text-white py-3 rounded-xl font-medium hover:bg-blue-600 transition-all">
            <i class="fas fa-file-excel mr-2"></i>Export to Excel
        </button>
        <button onclick="printOrders()" class="bg-purple-500 text-white py-3 rounded-xl font-medium hover:bg-purple-600 transition-all">
            <i class="fas fa-print mr-2"></i>Print Orders
        </button>
    </div>
</div>

<script>
$(document).ready(function() {
    $('#ordersTable').DataTable({
        "paging": true,
        "searching": true,
        "order": [[8, "desc"]], // Sort by date descending (column 8 is Date & Time)
        "pageLength": 25,
        "responsive": true,
        "language": {
            search: "Search orders:",
            lengthMenu: "Show _MENU_ orders per page",
            info: "Showing _START_ to _END_ of _TOTAL_ orders",
            paginate: {
                first: "First",
                last: "Last",
                next: "Next",
                previous: "Previous"
            }
        }
    });
});

// Export functions
function exportToCSV() {
    const table = document.getElementById('ordersTable');
    const rows = table.querySelectorAll('tr');
    let csv = [];
    
    for (let i = 0; i < rows.length; i++) {
        const row = rows[i];
        const cols = row.querySelectorAll('td, th');
        let csvRow = [];
        
        for (let j = 0; j < cols.length; j++) {
            let text = cols[j].innerText.replace(/"/g, '""');
            csvRow.push('"' + text + '"');
        }
        
        csv.push(csvRow.join(','));
    }
    
    const csvContent = csv.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_<?= date('Y-m-d') ?>.csv';
    a.click();
}

function exportToExcel() {
    // This would require a server-side implementation
    alert('Excel export feature requires server-side implementation');
}

function printOrders() {
    window.print();
}

// Date range functions
function setDateRange(range) {
    const today = new Date();
    const startDateInput = document.getElementById('start_date');
    const endDateInput = document.getElementById('end_date');
    
    let startDate, endDate;
    
    switch(range) {
        case 'today':
            startDate = today.toISOString().split('T')[0];
            endDate = today.toISOString().split('T')[0];
            break;
        case 'yesterday':
            const yesterday = new Date(today);
            yesterday.setDate(today.getDate() - 1);
            startDate = yesterday.toISOString().split('T')[0];
            endDate = yesterday.toISOString().split('T')[0];
            break;
        case 'last7days':
            const last7Days = new Date(today);
            last7Days.setDate(today.getDate() - 7);
            startDate = last7Days.toISOString().split('T')[0];
            endDate = today.toISOString().split('T')[0];
            break;
        case 'last30days':
            const last30Days = new Date(today);
            last30Days.setDate(today.getDate() - 30);
            startDate = last30Days.toISOString().split('T')[0];
            endDate = today.toISOString().split('T')[0];
            break;
        case 'thisMonth':
            startDate = new Date(today.getFullYear(), today.getMonth(), 1).toISOString().split('T')[0];
            endDate = today.toISOString().split('T')[0];
            break;
        case 'lastMonth':
            const lastMonth = new Date(today.getFullYear(), today.getMonth() - 1, 1);
            const lastMonthEnd = new Date(today.getFullYear(), today.getMonth(), 0);
            startDate = lastMonth.toISOString().split('T')[0];
            endDate = lastMonthEnd.toISOString().split('T')[0];
            break;
    }
    
    startDateInput.value = startDate;
    endDateInput.value = endDate;
    
    // Auto-submit the form
    document.querySelector('form').submit();
}
</script>
