<style>
.order-detail-header {
    background: linear-gradient(135deg, #72A565 0%, #91A134 100%);
    color: white;
    padding: 2rem;
    border-radius: 15px;
    margin-bottom: 2rem;
    box-shadow: 0 10px 30px rgba(0,0,0,0.1);
}

.detail-card {
    background: white;
    border-radius: 15px;
    box-shadow: 0 5px 15px rgba(0,0,0,0.08);
    margin-bottom: 1.5rem;
    transition: transform 0.3s ease, box-shadow 0.3s ease;
    border: none;
    overflow: hidden;
}

.detail-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 10px 25px rgba(0,0,0,0.12);
}

.detail-card .card-header {
    background: linear-gradient(135deg, #f7fafc 0%, #edf2f7 100%);
    border-bottom: 2px solid #e2e8f0;
    padding: 1.25rem 1.5rem;
    font-weight: 600;
    color: #2d3748;
}

.detail-card .card-body {
    padding: 1.5rem;
}

.info-item {
    padding: 1rem;
    background: #f7fafc;
    border-radius: 10px;
    margin-bottom: 1rem;
    border-left: 4px solid #667eea;
    transition: all 0.3s ease;
}

.info-item:hover {
    background: #edf2f7;
    transform: translateX(5px);
}

.info-item-label {
    font-size: 0.75rem;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    color: #718096;
    font-weight: 600;
    margin-bottom: 0.5rem;
}

.info-item-value {
    font-size: 1rem;
    color: #2d3748;
    font-weight: 500;
}

.badge-lg-modern {
    padding: 0.75rem 1.5rem;
    border-radius: 25px;
    font-weight: 600;
    font-size: 0.875rem;
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
}

.item-card {
    background: white;
    border: 2px solid #e2e8f0;
    border-radius: 10px;
    padding: 1rem;
    margin-bottom: 0.75rem;
    transition: all 0.3s ease;
}

.item-card:hover {
    border-color: #667eea;
    box-shadow: 0 5px 15px rgba(102, 126, 234, 0.1);
    transform: translateX(5px);
}

.item-card.cannabus {
    border-left: 4px solid #4299e1;
}

.item-card.storefront {
    border-left: 4px solid #ed8936;
}

.action-btn-modern {
    border-radius: 10px;
    padding: 0.75rem 1.5rem;
    font-weight: 500;
    transition: all 0.3s ease;
    box-shadow: 0 4px 6px rgba(0,0,0,0.1);
    width: 100%;
    margin-bottom: 0.5rem;
}

.action-btn-modern:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 12px rgba(0,0,0,0.15);
}

.alert-modern {
    border-radius: 10px;
    border: none;
    padding: 1.25rem;
    box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}

.distance-badge {
    background: linear-gradient(135deg, #72A565 0%, #91A134 100%);
    color: white;
    padding: 0.5rem 1rem;
    border-radius: 20px;
    font-weight: 600;
    font-size: 1.1rem;
    display: inline-block;
    margin-top: 0.5rem;
}

.logic-box {
    background: #f7fafc;
    border-left: 4px solid #667eea;
    padding: 1rem;
    border-radius: 8px;
    margin-top: 1rem;
}

.form-control-modern {
    border-radius: 10px;
    border: 2px solid #e2e8f0;
    padding: 0.75rem 1rem;
    transition: all 0.3s ease;
}

.form-control-modern:focus {
    border-color: #667eea;
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
    outline: none;
}
</style>

<!-- Header -->
<div class="order-detail-header">
    <div class="d-flex justify-content-between align-items-center">
        <div>
            <h2 class="mb-2">
                <i class="fa-solid fa-shopping-cart"></i> Order Details
            </h2>
            <p class="mb-0 opacity-75">Order #ORD-<?php echo substr($orderId, 0, 8); ?> - Complete order information and fulfillment details</p>
        </div>
        <div>
            <a href="<?php echo base_url('orders'); ?>" class="btn btn-light btn-modern">
                <i class="fa-solid fa-arrow-left"></i> Back to Orders
            </a>
        </div>
    </div>
</div>

<?php if (isset($order['isBlocked']) && $order['isBlocked']): ?>
<div class="alert alert-modern alert-danger mb-4">
    <h5 class="mb-2">
        <i class="fa-solid fa-exclamation-triangle"></i> Order Blocked
    </h5>
    <p class="mb-0"><strong>Reason:</strong> <?php echo isset($order['blockReason']) ? $order['blockReason'] : 'Minimum order requirement not met'; ?></p>
</div>
<?php endif; ?>

<div class="row">
    <!-- Main Content -->
    <div class="col-md-8">
        <!-- Order Information -->
        <div class="detail-card">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fa-solid fa-info-circle text-primary"></i> Order Information
                </h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="info-item">
                            <div class="info-item-label">Order Number</div>
                            <div class="info-item-value">ORD-<?php echo substr($orderId, 0, 8); ?></div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="info-item">
                            <div class="info-item-label">Status</div>
                            <div>
                                <?php 
                                $status = isset($order['orderStatus']) ? $order['orderStatus'] : 'pending';
                                $statusColors = array(
                                    'pending' => 'warning-modern',
                                    'accepted' => 'info-modern',
                                    'picked' => 'primary-modern',
                                    'delivered' => 'success-modern',
                                    'deliver' => 'success-modern',
                                    'cancelled' => 'danger-modern'
                                );
                                $statusColor = isset($statusColors[$status]) ? $statusColors[$status] : 'secondary-modern';
                                ?>
                                <span class="badge-lg-modern badge-<?php echo $statusColor; ?>">
                                    <?php echo ucfirst(str_replace('_', ' ', $status)); ?>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6">
                        <div class="info-item">
                            <div class="info-item-label">Order Date</div>
                            <div class="info-item-value">
                                <?php echo isset($order['date']) ? date('Y-m-d H:i:s', $order['date'] / 1000) : 'N/A'; ?>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="info-item">
                            <div class="info-item-label">City</div>
                            <div class="info-item-value">
                                <?php echo isset($city['cityName']) ? $city['cityName'] : 'N/A'; ?>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-12">
                        <div class="info-item">
                            <div class="info-item-label">Customer Address</div>
                            <div class="info-item-value">
                                <?php echo isset($order['customerAddress']) ? $order['customerAddress'] : 'N/A'; ?>
                            </div>
                        </div>
                    </div>
                </div>

                <?php if (isset($order['customerLatitude']) && isset($order['customerLongitude'])): ?>
                <div class="row">
                    <div class="col-md-6">
                        <div class="info-item">
                            <div class="info-item-label">Customer Latitude</div>
                            <div class="info-item-value"><?php echo $order['customerLatitude']; ?></div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="info-item">
                            <div class="info-item-label">Customer Longitude</div>
                            <div class="info-item-value"><?php echo $order['customerLongitude']; ?></div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Distance & Zone Information -->
        <div class="detail-card">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fa-solid fa-route text-primary"></i> Distance & Zone Calculation
                </h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-4">
                        <div class="info-item">
                            <div class="info-item-label">Chargeable Distance</div>
                            <div class="distance-badge">
                                <i class="fa-solid fa-route"></i> 
                                <?php echo isset($order['chargeableDistance']) ? number_format($order['chargeableDistance'], 2) : '0.00'; ?> miles
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="info-item">
                            <div class="info-item-label">Assigned Zone</div>
                            <div>
                                <?php if (isset($order['zone'])): ?>
                                    <span class="badge-lg-modern badge-primary-modern">
                                        <?php echo strtoupper($order['zone']); ?>
                                    </span>
                                <?php else: ?>
                                    <span class="text-muted">Not assigned</span>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="info-item">
                            <div class="info-item-label">Delivery Fee</div>
                            <div class="info-item-value">
                                <strong>$<?php echo isset($order['deliveryFee']) ? number_format($order['deliveryFee'], 2) : '0.00'; ?></strong>
                            </div>
                        </div>
                    </div>
                </div>

                <?php if (isset($order['hasMultipleVendors']) && $order['hasMultipleVendors']): ?>
                <div class="logic-box">
                    <h6 class="mb-2">
                        <i class="fa-solid fa-info-circle text-primary"></i> Multi-Vendor Order Detected
                    </h6>
                    <p class="mb-0 small">
                        This order contains items from multiple storefront vendors. The distance calculation uses the <strong>farthest vendor</strong> from the city HQ to determine the chargeable distance.
                    </p>
                </div>
                <?php endif; ?>

                <?php if (!empty($order['cannabusItems']) && !empty($order['storefrontItems'])): ?>
                <div class="logic-box">
                    <h6 class="mb-2">
                        <i class="fa-solid fa-info-circle text-primary"></i> Mixed Fulfillment Type
                    </h6>
                    <p class="mb-0 small">
                        This order contains both <strong>Cannabus inventory</strong> and <strong>storefront vendor</strong> items. Only the storefront vendor distance is used in the calculation (Cannabus inventory never adds distance).
                    </p>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Order Items -->
        <div class="detail-card">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fa-solid fa-box text-primary"></i> Order Items
                </h5>
            </div>
            <div class="card-body">
                <?php if (!empty($order['cannabusItems'])): ?>
                <h6 class="mb-3">
                    <i class="fa-solid fa-box text-info"></i> Cannabus Inventory Items
                </h6>
                <?php foreach ($order['cannabusItems'] as $item): ?>
                <div class="item-card cannabus">
                    <div class="row align-items-center">
                        <div class="col-md-6">
                            <strong><?php echo isset($item['productName']) ? $item['productName'] : 'Product ID: ' . (isset($item['productId']) ? $item['productId'] : 'N/A'); ?></strong>
                            <br><small class="text-muted">Cannabus Inventory - No distance added</small>
                        </div>
                        <div class="col-md-2 text-center">
                            <strong>Qty:</strong> <?php echo isset($item['quantity']) ? $item['quantity'] : 1; ?>
                        </div>
                        <div class="col-md-2 text-center">
                            <strong>Price:</strong> $<?php echo isset($item['price']) ? number_format($item['price'], 2) : '0.00'; ?>
                        </div>
                        <div class="col-md-2 text-end">
                            <strong>$<?php echo isset($item['quantity']) && isset($item['price']) ? number_format($item['quantity'] * $item['price'], 2) : '0.00'; ?></strong>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
                <?php endif; ?>

                <?php if (!empty($order['storefrontItems'])): ?>
                <h6 class="mb-3 mt-4">
                    <i class="fa-solid fa-store text-warning"></i> Storefront Vendor Items
                </h6>
                <?php foreach ($order['storefrontItems'] as $item): ?>
                <div class="item-card storefront">
                    <div class="row align-items-center">
                        <div class="col-md-6">
                            <strong><?php echo isset($item['productName']) ? $item['productName'] : 'Product ID: ' . (isset($item['productId']) ? $item['productId'] : 'N/A'); ?></strong>
                            <br><small class="text-muted">
                                <i class="fa-solid fa-store"></i> Vendor: <?php echo isset($item['vendorName']) ? $item['vendorName'] : 'Unknown'; ?>
                            </small>
                            <br><small class="text-info">Distance: HQ → Vendor → Customer</small>
                        </div>
                        <div class="col-md-2 text-center">
                            <strong>Qty:</strong> <?php echo isset($item['quantity']) ? $item['quantity'] : 1; ?>
                        </div>
                        <div class="col-md-2 text-center">
                            <strong>Price:</strong> $<?php echo isset($item['price']) ? number_format($item['price'], 2) : '0.00'; ?>
                        </div>
                        <div class="col-md-2 text-end">
                            <strong>$<?php echo isset($item['quantity']) && isset($item['price']) ? number_format($item['quantity'] * $item['price'], 2) : '0.00'; ?></strong>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
                <?php endif; ?>

                <?php if (empty($order['cannabusItems']) && empty($order['storefrontItems']) && isset($order['items'])): ?>
                <h6 class="mb-3">All Items</h6>
                <?php foreach ($order['items'] as $item): ?>
                <div class="item-card">
                    <div class="row align-items-center">
                        <div class="col-md-6">
                            <strong><?php echo isset($item['productName']) ? $item['productName'] : 'Product ID: ' . (isset($item['productId']) ? $item['productId'] : 'N/A'); ?></strong>
                            <?php if (isset($item['vendorName'])): ?>
                                <br><small class="text-muted">Vendor: <?php echo $item['vendorName']; ?></small>
                            <?php endif; ?>
                        </div>
                        <div class="col-md-2 text-center">
                            <strong>Qty:</strong> <?php echo isset($item['quantity']) ? $item['quantity'] : 1; ?>
                        </div>
                        <div class="col-md-2 text-center">
                            <strong>Price:</strong> $<?php echo isset($item['price']) ? number_format($item['price'], 2) : '0.00'; ?>
                        </div>
                        <div class="col-md-2 text-end">
                            <strong>$<?php echo isset($item['quantity']) && isset($item['price']) ? number_format($item['quantity'] * $item['price'], 2) : '0.00'; ?></strong>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>

        <!-- Minimum Order Validation -->
        <?php if (isset($order['zone']) && isset($zones) && !empty($zones)): ?>
        <div class="detail-card">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fa-solid fa-check-circle text-primary"></i> Minimum Order Validation
                </h5>
            </div>
            <div class="card-body">
                <?php
                $zoneKey = $order['zone'];
                $isStorefront = !empty($order['storefrontItems']);
                $this->load->helper('delivery');
                $zonePricing = get_zone_pricing($zoneKey, $zones, $isStorefront);
                
                $cartTotal = isset($order['cartTotal']) ? $order['cartTotal'] : 0;
                $minimumOrder = isset($zonePricing['minimumOrder']) ? $zonePricing['minimumOrder'] : 0;
                
                if ($isStorefront && $zoneKey == 'zone2' && isset($zonePricing['storefrontMinimumOrder'])) {
                    $minimumOrder = $zonePricing['storefrontMinimumOrder'];
                }
                
                $meetsMinimum = $cartTotal >= $minimumOrder;
                ?>
                <div class="row">
                    <div class="col-md-6">
                        <div class="info-item">
                            <div class="info-item-label">Cart Total</div>
                            <div class="info-item-value">
                                <strong>$<?php echo number_format($cartTotal, 2); ?></strong>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="info-item">
                            <div class="info-item-label">Required Minimum</div>
                            <div class="info-item-value">
                                <strong>$<?php echo number_format($minimumOrder, 2); ?></strong>
                                <?php if ($isStorefront && $zoneKey == 'zone2'): ?>
                                    <br><small class="text-muted">(Zone 2 Storefront Minimum)</small>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
                
                <?php if ($meetsMinimum): ?>
                <div class="alert alert-modern alert-success mt-3 mb-0">
                    <i class="fa-solid fa-check-circle"></i> <strong>Minimum order requirement met.</strong>
                </div>
                <?php else: ?>
                <div class="alert alert-modern alert-danger mt-3 mb-0">
                    <i class="fa-solid fa-exclamation-triangle"></i> <strong>Minimum order requirement NOT met.</strong> 
                    Order is blocked. Required: $<?php echo number_format($minimumOrder, 2); ?>, Current: $<?php echo number_format($cartTotal, 2); ?>
                </div>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <!-- Sidebar -->
    <div class="col-md-4">
        <!-- Pricing Summary -->
        <div class="detail-card">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fa-solid fa-dollar-sign text-primary"></i> Pricing Summary
                </h5>
            </div>
            <div class="card-body">
                <div class="info-item">
                    <div class="info-item-label">Cart Total</div>
                    <div class="info-item-value">$<?php echo isset($order['cartTotal']) ? number_format($order['cartTotal'], 2) : '0.00'; ?></div>
                </div>
                <div class="info-item">
                    <div class="info-item-label">Delivery Fee</div>
                    <div class="info-item-value">$<?php echo isset($order['deliveryFee']) ? number_format($order['deliveryFee'], 2) : '0.00'; ?></div>
                </div>
                <hr>
                <div class="info-item" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: none;">
                    <div class="info-item-label" style="color: rgba(255,255,255,0.8);">Total Amount</div>
                    <div class="info-item-value" style="color: white; font-size: 1.5rem;">
                        <strong>$<?php echo isset($order['totalAmount']) ? number_format($order['totalAmount'], 2) : '0.00'; ?></strong>
                    </div>
                </div>
            </div>
        </div>

        <!-- Update Status -->
        <div class="detail-card">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fa-solid fa-sync text-primary"></i> Update Status
                </h5>
            </div>
            <div class="card-body">
                <form method="post" action="<?php echo base_url('orders/updatestatus'); ?>" id="statusForm">
                    <input type="hidden" name="orderId" value="<?php echo $orderId; ?>">
                    <div class="form-group-modern">
                        <label class="form-label-modern">Order Status</label>
                        <select name="status" class="form-control form-control-modern" required>
                            <option value="pending" <?php echo (isset($order['orderStatus']) && $order['orderStatus'] == 'pending') ? 'selected' : ''; ?>>Pending</option>
                            <option value="accepted" <?php echo (isset($order['orderStatus']) && $order['orderStatus'] == 'accepted') ? 'selected' : ''; ?>>Accepted</option>
                            <option value="picked" <?php echo (isset($order['orderStatus']) && $order['orderStatus'] == 'picked') ? 'selected' : ''; ?>>Picked</option>
                            <option value="delivered" <?php echo (isset($order['orderStatus']) && ($order['orderStatus'] == 'delivered' || $order['orderStatus'] == 'deliver')) ? 'selected' : ''; ?>>Delivered</option>
                            <option value="cancelled" <?php echo (isset($order['orderStatus']) && $order['orderStatus'] == 'cancelled') ? 'selected' : ''; ?>>Cancelled</option>
                        </select>
                    </div>
                    <button type="submit" class="btn btn-primary action-btn-modern">
                        <i class="fa-solid fa-save"></i> Update Status
                    </button>
                </form>
            </div>
        </div>

        <!-- Customer Information -->
        <?php if (isset($customer) && !empty($customer)): ?>
        <div class="detail-card">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fa-solid fa-user text-primary"></i> Customer Information
                </h5>
            </div>
            <div class="card-body">
                <div class="info-item">
                    <div class="info-item-label">Name</div>
                    <div class="info-item-value">
                        <?php echo isset($customer['firstName']) ? $customer['firstName'] . ' ' . (isset($customer['lastName']) ? $customer['lastName'] : '') : 'N/A'; ?>
                    </div>
                </div>
                <div class="info-item">
                    <div class="info-item-label">Email</div>
                    <div class="info-item-value"><?php echo isset($customer['email']) ? $customer['email'] : 'N/A'; ?></div>
                </div>
                <div class="info-item">
                    <div class="info-item-label">Phone</div>
                    <div class="info-item-value"><?php echo isset($customer['phoneNumber']) ? $customer['phoneNumber'] : (isset($customer['phone']) ? $customer['phone'] : 'N/A'); ?></div>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- SweetAlert2 -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="<?php echo base_url('assets/js/jquery.min.js'); ?>"></script>
<script>
$(document).ready(function() {
    $('#statusForm').on('submit', function(e) {
        e.preventDefault();
        
        var form = $(this);
        var formData = form.serialize();
        var url = form.attr('action');
        
        var submitBtn = form.find('button[type="submit"]');
        var originalText = submitBtn.html();
        submitBtn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Updating...');
        
        $.ajax({
            url: url,
            type: 'POST',
            data: formData,
            dataType: 'json',
            success: function(response) {
                submitBtn.prop('disabled', false).html(originalText);
                
                if (response.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Success!',
                        text: response.message,
                        confirmButtonText: 'OK',
                        timer: 2000,
                        timerProgressBar: true
                    }).then(function() {
                        location.reload();
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error!',
                        text: response.message,
                        confirmButtonText: 'OK'
                    });
                }
            },
            error: function() {
                submitBtn.prop('disabled', false).html(originalText);
                // Fallback to regular form submission
                form.off('submit').submit();
            }
        });
    });
});
</script>
