<?php
$pageTitle = 'Order Details';
require_once __DIR__ . '/includes/header.php';

$orderId = (int)($_GET['id'] ?? 0);
$order = $db->query("
    SELECT o.*, t.table_number, c.name as customer_name_full, c.phone as customer_phone_full, c.email as customer_email_full
    FROM orders o
    LEFT JOIN tables t ON o.table_id = t.id
    LEFT JOIN customers c ON o.customer_id = c.id
    WHERE o.id = ? AND o.restaurant_id = ?
", [$orderId, $restaurantId])->fetch();

if (!$order) {
    redirect($baseUrl . '/restaurant-admin/orders.php');
    exit;
}

$orderItems = $db->query("SELECT * FROM order_items WHERE order_id = ? ORDER BY id ASC", [$orderId])->fetchAll();

foreach ($orderItems as &$oi) {
    $oi['addons'] = $db->query("SELECT * FROM order_item_addons WHERE order_item_id = ?", [$oi['id']])->fetchAll();
}
unset($oi);

$statusHistory = $db->query("
    SELECT osh.*, u.name as changed_by_name
    FROM order_status_history osh
    LEFT JOIN users u ON osh.changed_by = u.id
    WHERE osh.order_id = ?
    ORDER BY osh.created_at ASC
", [$orderId])->fetchAll();
?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <div>
        <h6 class="mb-0">Order <?php echo sanitize($order['order_number']); ?></h6>
        <small class="text-muted">Placed <?php echo formatDateTime($order['created_at']); ?></small>
    </div>
    <div>
        <a href="<?php echo $baseUrl; ?>/restaurant-admin/orders.php" class="btn btn-outline-secondary btn-sm me-1"><i class="fas fa-arrow-left me-1"></i>Back</a>
        <button class="btn btn-outline-secondary btn-sm" onclick="window.print()"><i class="fas fa-print me-1"></i>Print</button>
    </div>
</div>

<div class="row">
    <div class="col-lg-8">
        <div class="form-card">
            <div class="card-title"><i class="fas fa-list me-2"></i>Order Items</div>
            <div class="table-responsive">
                <table class="table mb-0">
                    <thead class="table-light">
                        <tr><th>Item</th><th>Variation</th><th>Qty</th><th>Unit Price</th><th>Addons</th><th>Total</th></tr>
                    </thead>
                    <tbody>
                        <?php foreach ($orderItems as $oi): ?>
                        <tr>
                            <td><strong><?php echo sanitize($oi['item_name']); ?></strong></td>
                            <td><?php echo sanitize($oi['variation_name'] ?? '-'); ?></td>
                            <td><?php echo $oi['quantity']; ?></td>
                            <td><?php echo formatCurrency($oi['unit_price'], $currency); ?></td>
                            <td>
                                <?php if (!empty($oi['addons'])): ?>
                                    <?php foreach ($oi['addons'] as $ad): ?>
                                        <small><?php echo sanitize($ad['addon_name']); ?> (<?php echo formatCurrency($ad['addon_price'], $currency); ?>)</small><br>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <small class="text-muted">-</small>
                                <?php endif; ?>
                            </td>
                            <td><strong><?php echo formatCurrency($oi['item_total'], $currency); ?></strong></td>
                        </tr>
                        <?php if ($oi['item_notes']): ?>
                        <tr><td colspan="6"><small class="text-muted"><i class="fas fa-sticky-note me-1"></i><?php echo sanitize($oi['item_notes']); ?></small></td></tr>
                        <?php endif; ?>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="form-card">
            <div class="card-title"><i class="fas fa-history me-2"></i>Order Timeline</div>
            <?php if (empty($statusHistory)): ?>
                <div class="text-muted small">No status history</div>
            <?php else: ?>
                <div class="timeline">
                    <?php foreach ($statusHistory as $sh): ?>
                    <div class="d-flex mb-3">
                        <div class="me-3">
                            <div class="bg-primary text-white rounded-circle d-flex align-items-center justify-content-center" style="width:32px;height:32px;font-size:12px;">
                                <i class="fas fa-circle"></i>
                            </div>
                        </div>
                        <div>
                            <div class="fw-bold small"><?php echo ucfirst($sh['to_status']); ?></div>
                            <div class="text-muted" style="font-size:12px;"><?php echo formatDateTime($sh['created_at']); ?> <?php echo $sh['changed_by_name'] ? 'by ' . sanitize($sh['changed_by_name']) : ''; ?></div>
                            <?php if ($sh['notes']): ?>
                                <div class="small mt-1"><?php echo sanitize($sh['notes']); ?></div>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <div class="col-lg-4">
        <div class="form-card">
            <div class="card-title"><i class="fas fa-info-circle me-2"></i>Order Summary</div>
            <table class="table table-borderless mb-2">
                <tr><td class="text-muted small">Order #</td><td class="small fw-bold"><?php echo sanitize($order['order_number']); ?></td></tr>
                <tr><td class="text-muted small">Type</td><td class="small"><span class="badge bg-secondary"><?php echo ucfirst(str_replace('_', ' ', $order['order_type'])); ?></span></td></tr>
                <tr><td class="text-muted small">Table</td><td class="small"><?php echo sanitize($order['table_number'] ?? 'N/A'); ?></td></tr>
                <tr><td class="text-muted small">Status</td><td class="small"><span class="badge order-status-<?php echo $order['order_status']; ?>"><?php echo ucfirst($order['order_status']); ?></span></td></tr>
                <tr><td class="text-muted small">Payment</td><td class="small"><span class="badge bg-<?php echo $order['payment_status'] === 'paid' ? 'success' : 'warning'; ?>"><?php echo ucfirst($order['payment_status']); ?></span></td></tr>
                <tr><td class="text-muted small">Method</td><td class="small"><?php echo sanitize(ucfirst($order['payment_method'] ?? 'N/A')); ?></td></tr>
            </table>
            <hr>
            <table class="table table-borderless mb-2 small">
                <tr><td class="text-muted">Subtotal</td><td class="text-end"><?php echo formatCurrency($order['subtotal'], $currency); ?></td></tr>
                <?php if ($order['discount'] > 0): ?>
                <tr><td class="text-muted">Discount</td><td class="text-end text-danger">-<?php echo formatCurrency($order['discount'], $currency); ?></td></tr>
                <?php endif; ?>
                <tr><td class="text-muted">Tax</td><td class="text-end"><?php echo formatCurrency($order['tax'], $currency); ?></td></tr>
                <tr><td class="text-muted">Service Charge</td><td class="text-end"><?php echo formatCurrency($order['service_charge'], $currency); ?></td></tr>
                <?php if ($order['delivery_charge'] > 0): ?>
                <tr><td class="text-muted">Delivery</td><td class="text-end"><?php echo formatCurrency($order['delivery_charge'], $currency); ?></td></tr>
                <?php endif; ?>
                <tr class="border-top fw-bold"><td>Total</td><td class="text-end"><?php echo formatCurrency($order['grand_total'], $currency); ?></td></tr>
            </table>
            <?php if ($order['order_notes']): ?>
            <hr>
            <div class="small"><strong>Notes:</strong> <?php echo sanitize($order['order_notes']); ?></div>
            <?php endif; ?>
        </div>

        <div class="form-card">
            <div class="card-title"><i class="fas fa-user me-2"></i>Customer</div>
            <table class="table table-borderless mb-0 small">
                <tr><td class="text-muted">Name</td><td><?php echo sanitize($order['customer_name'] ?? 'Walk-in'); ?></td></tr>
                <tr><td class="text-muted">Phone</td><td><?php echo sanitize($order['customer_phone'] ?? '-'); ?></td></tr>
                <?php if ($order['order_type'] === 'delivery'): ?>
                <tr><td class="text-muted">Address</td><td><?php echo sanitize($order['customer_address'] ?? '-'); ?></td></tr>
                <?php endif; ?>
            </table>
        </div>

        <div class="form-card">
            <div class="card-title"><i class="fas fa-cog me-2"></i>Actions</div>
            <div class="d-grid gap-2">
                <?php if ($order['order_status'] === 'new'): ?>
                    <button class="btn btn-success order-act" data-action="confirmed"><i class="fas fa-check me-1"></i>Accept Order</button>
                    <button class="btn btn-danger order-act" data-action="rejected"><i class="fas fa-times me-1"></i>Reject Order</button>
                <?php elseif ($order['order_status'] === 'confirmed'): ?>
                    <button class="btn btn-warning order-act" data-action="preparing"><i class="fas fa-fire me-1"></i>Start Preparing</button>
                <?php elseif ($order['order_status'] === 'preparing'): ?>
                    <button class="btn btn-success order-act" data-action="ready"><i class="fas fa-bell me-1"></i>Mark Ready</button>
                <?php elseif ($order['order_status'] === 'ready'): ?>
                    <button class="btn btn-info order-act" data-action="served"><i class="fas fa-concierge-bell me-1"></i>Mark Served</button>
                <?php elseif ($order['order_status'] === 'served'): ?>
                    <button class="btn btn-success order-act" data-action="completed"><i class="fas fa-check-double me-1"></i>Complete Order</button>
                <?php endif; ?>
                <?php if (!in_array($order['order_status'], ['completed', 'cancelled', 'rejected'])): ?>
                    <button class="btn btn-outline-danger order-act" data-action="cancelled"><i class="fas fa-ban me-1"></i>Cancel Order</button>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="rejectModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header"><h5 class="modal-title">Reason Required</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <input type="hidden" id="rejectAction">
                <textarea class="form-control" id="rejectReason" rows="3" placeholder="Enter reason..." required></textarea>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger" id="confirmRejectBtn">Confirm</button>
            </div>
        </div>
    </div>
</div>

<script>
document.querySelectorAll('.order-act').forEach(function(btn) {
    btn.addEventListener('click', function() {
        var action = this.dataset.action;
        if (action === 'rejected' || action === 'cancelled') {
            document.getElementById('rejectAction').value = action;
            document.getElementById('rejectReason').value = '';
            new bootstrap.Modal(document.getElementById('rejectModal')).show();
        } else {
            if (confirm('Change status to "' + action + '"?')) {
                ajaxPost(BASE_URL + '/restaurant-admin/order_action.php', 'order_id=<?php echo $orderId; ?>&order_status=' + action + '&csrf_token=' + encodeURIComponent(CSRF_TOKEN), function(data) {
                    if (data.success) { showAlert('success', data.message); setTimeout(function(){location.reload();},1000); }
                    else showAlert('danger', data.message);
                });
            }
        }
    });
});

document.getElementById('confirmRejectBtn').addEventListener('click', function() {
    var action = document.getElementById('rejectAction').value;
    var reason = document.getElementById('rejectReason').value.trim();
    if (!reason) { showAlert('danger', 'Please enter a reason'); return; }
    ajaxPost(BASE_URL + '/restaurant-admin/order_action.php', 'order_id=<?php echo $orderId; ?>&order_status=' + action + '&reason=' + encodeURIComponent(reason) + '&csrf_token=' + encodeURIComponent(CSRF_TOKEN), function(data) {
        if (data.success) { showAlert('success', data.message); setTimeout(function(){location.reload();},1000); }
        else showAlert('danger', data.message);
    });
});
</script>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
