<?php
require_once __DIR__ . '/includes/base.php';

$breadcrumbs = [['title' => 'Orders', 'url' => '']];

// Fetch orders
try {
    $sql = "SELECT o.*, 
            p.product_name, p.category,
            buyer.full_name as buyer_name, buyer.phone_number as buyer_phone,
            seller.full_name as seller_name, seller.phone_number as seller_phone
            FROM orders o
            JOIN products p ON o.product_id = p.id
            JOIN users buyer ON o.buyer_id = buyer.id
            JOIN users seller ON o.seller_id = seller.id
            ORDER BY o.created_at DESC";
    
    $stmt = $db->query($sql);
    $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $stats = [
        'total' => count($orders),
        'pending' => count(array_filter($orders, fn($o) => $o['status'] === 'pending')),
        'confirmed' => count(array_filter($orders, fn($o) => $o['status'] === 'confirmed')),
        'completed' => count(array_filter($orders, fn($o) => $o['status'] === 'completed')),
        'cancelled' => count(array_filter($orders, fn($o) => $o['status'] === 'cancelled')),
        'total_value' => array_sum(array_column($orders, 'total_amount'))
    ];
    
} catch (PDOException $e) {
    $orders = [];
    $stats = ['total' => 0, 'pending' => 0, 'confirmed' => 0, 'completed' => 0, 'cancelled' => 0, 'total_value' => 0];
}

renderAdminHeader('Orders', $breadcrumbs);
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="mb-1 fw-bold">Order Management</h2>
        <p class="text-muted mb-0">Monitor and intervene in marketplace transactions</p>
    </div>
</div>

<!-- Stats -->
<div class="row mb-4">
    <div class="col-md-2 mb-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body text-center">
                <h5 class="text-primary mb-0"><?php echo $stats['total']; ?></h5>
                <small class="text-muted">Total</small>
            </div>
        </div>
    </div>
    <div class="col-md-2 mb-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body text-center">
                <h5 class="text-warning mb-0"><?php echo $stats['pending']; ?></h5>
                <small class="text-muted">Pending</small>
            </div>
        </div>
    </div>
    <div class="col-md-2 mb-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body text-center">
                <h5 class="text-info mb-0"><?php echo $stats['confirmed']; ?></h5>
                <small class="text-muted">Confirmed</small>
            </div>
        </div>
    </div>
    <div class="col-md-2 mb-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body text-center">
                <h5 class="text-success mb-0"><?php echo $stats['completed']; ?></h5>
                <small class="text-muted">Completed</small>
            </div>
        </div>
    </div>
    <div class="col-md-2 mb-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body text-center">
                <h5 class="text-danger mb-0"><?php echo $stats['cancelled']; ?></h5>
                <small class="text-muted">Cancelled</small>
            </div>
        </div>
    </div>
    <div class="col-md-2 mb-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body text-center">
                <h6 class="text-success mb-0">UGX <?php echo number_format($stats['total_value']); ?></h6>
                <small class="text-muted">Value</small>
            </div>
        </div>
    </div>
</div>

<!-- Orders Table -->
<div class="card shadow-sm border-0">
    <div class="card-header bg-white py-3">
        <h5 class="mb-0 fw-bold"><i class="bi bi-cart3 me-2"></i>All Orders</h5>
    </div>
    <div class="card-body p-0">
        <table class="table table-hover mb-0" id="ordersTable">
            <thead class="table-light">
                <tr>
                    <th>Order #</th>
                    <th>Product</th>
                    <th>Buyer</th>
                    <th>Seller</th>
                    <th>Quantity</th>
                    <th>Amount</th>
                    <th>Payment</th>
                    <th>Status</th>
                    <th>Date</th>
                    <th class="text-end">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($orders as $order): ?>
                <tr>
                    <td class="fw-semibold">#<?php echo htmlspecialchars($order['order_number']); ?></td>
                    <td>
                        <div><?php echo htmlspecialchars($order['product_name']); ?></div>
                        <small class="text-muted"><?php echo ucfirst($order['category']); ?></small>
                    </td>
                    <td>
                        <small>
                            <?php echo htmlspecialchars($order['buyer_name']); ?><br>
                            <span class="text-muted"><?php echo htmlspecialchars($order['buyer_phone']); ?></span>
                        </small>
                    </td>
                    <td>
                        <small>
                            <?php echo htmlspecialchars($order['seller_name']); ?><br>
                            <span class="text-muted"><?php echo htmlspecialchars($order['seller_phone']); ?></span>
                        </small>
                    </td>
                    <td><?php echo $order['quantity']; ?></td>
                    <td><strong class="text-success">UGX <?php echo number_format($order['total_amount']); ?></strong></td>
                    <td>
                        <span class="badge bg-<?php 
                            echo $order['payment_status'] === 'paid' ? 'success' : 
                                ($order['payment_status'] === 'partial' ? 'warning' : 'danger'); 
                        ?>">
                            <?php echo ucfirst($order['payment_status']); ?>
                        </span>
                    </td>
                    <td>
                        <span class="badge bg-<?php 
                            echo $order['status'] === 'completed' ? 'success' : 
                                ($order['status'] === 'cancelled' ? 'danger' : 
                                ($order['status'] === 'confirmed' ? 'info' : 'warning')); 
                        ?>">
                            <?php echo ucfirst($order['status']); ?>
                        </span>
                    </td>
                    <td><small class="text-muted"><?php echo date('M d, Y', strtotime($order['created_at'])); ?></small></td>
                    <td class="text-end">
                        <div class="btn-group btn-group-sm">
                            <button class="btn btn-outline-info" onclick='viewOrder(<?php echo json_encode($order); ?>)'>
                                <i class="bi bi-eye"></i>
                            </button>
                            <button class="btn btn-outline-warning" onclick="interveneOrder(<?php echo $order['id']; ?>)">
                                <i class="bi bi-exclamation-triangle"></i>
                            </button>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Order Details Modal -->
<div class="modal fade" id="detailsModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-receipt me-2"></i>Order Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="orderDetails"></div>
        </div>
    </div>
</div>

<!-- Intervention Modal -->
<div class="modal fade" id="interveneModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-warning">
                <h5 class="modal-title"><i class="bi bi-shield-exclamation me-2"></i>Admin Intervention</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="interveneForm">
                <div class="modal-body">
                    <input type="hidden" name="order_id" id="intervene_order_id">
                    
                    <div class="alert alert-warning">
                        <i class="bi bi-info-circle me-2"></i>
                        Use this when disputes or issues arise between buyer and seller
                    </div>
                    
                    <div class="mb-3">
                        <label>Action *</label>
                        <select class="form-select" name="action" required>
                            <option value="">Select action...</option>
                            <option value="cancel">Cancel Order</option>
                            <option value="refund">Issue Refund</option>
                            <option value="resolve">Mark as Resolved</option>
                            <option value="escalate">Escalate Issue</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label>Admin Notes *</label>
                        <textarea class="form-control" name="notes" rows="4" required placeholder="Explain the reason for intervention..."></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="notify_parties" id="notifyParties" checked>
                            <label class="form-check-label" for="notifyParties">
                                Notify both buyer and seller
                            </label>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-warning">Submit Intervention</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    $('#ordersTable').DataTable({
        pageLength: 25,
        order: [[8, 'desc']]
    });
});

function viewOrder(order) {
    const html = `
        <div class="row">
            <div class="col-md-6 mb-3">
                <h6 class="text-muted mb-2">ORDER INFORMATION</h6>
                <table class="table table-sm">
                    <tr><th>Order #:</th><td>${order.order_number}</td></tr>
                    <tr><th>Product:</th><td>${order.product_name}</td></tr>
                    <tr><th>Category:</th><td>${order.category}</td></tr>
                    <tr><th>Quantity:</th><td>${order.quantity}</td></tr>
                    <tr><th>Unit Price:</th><td>UGX ${Number(order.unit_price).toLocaleString()}</td></tr>
                    <tr><th>Total:</th><td><strong class="text-success">UGX ${Number(order.total_amount).toLocaleString()}</strong></td></tr>
                </table>
            </div>
            <div class="col-md-6 mb-3">
                <h6 class="text-muted mb-2">PARTIES</h6>
                <table class="table table-sm">
                    <tr><th>Buyer:</th><td>${order.buyer_name}<br><small>${order.buyer_phone}</small></td></tr>
                    <tr><th>Seller:</th><td>${order.seller_name}<br><small>${order.seller_phone}</small></td></tr>
                    <tr><th>Status:</th><td><span class="badge bg-info">${order.status}</span></td></tr>
                    <tr><th>Payment:</th><td><span class="badge bg-success">${order.payment_status}</span></td></tr>
                    <tr><th>Date:</th><td>${new Date(order.created_at).toLocaleString()}</td></tr>
                </table>
            </div>
        </div>
        ${order.delivery_address ? `<div class="alert alert-info"><strong>Delivery:</strong> ${order.delivery_address}</div>` : ''}
        ${order.notes ? `<div class="alert alert-secondary"><strong>Notes:</strong> ${order.notes}</div>` : ''}
    `;
    
    document.getElementById('orderDetails').innerHTML = html;
    new bootstrap.Modal(document.getElementById('detailsModal')).show();
}

function interveneOrder(orderId) {
    $('#intervene_order_id').val(orderId);
    new bootstrap.Modal(document.getElementById('interveneModal')).show();
}

$('#interveneForm').submit(function(e) {
    e.preventDefault();
    
    const btn = $(this).find('button[type="submit"]');
    btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2"></span>Processing...');
    
    $.post(APP_URL + '/api/admin.php', $(this).serialize() + '&action=intervene_order')
    .done(function(r) {
        if (r.success) {
            showToast(r.message, 'success');
            $('#interveneModal').modal('hide');
            setTimeout(() => location.reload(), 1000);
        } else {
            showToast(r.message, 'error');
            btn.prop('disabled', false).html('Submit Intervention');
        }
    })
    .fail(function() {
        showToast('Connection error', 'error');
        btn.prop('disabled', false).html('Submit Intervention');
    });
});
</script>

<?php renderAdminFooter(); ?>