

<?php $__env->startSection('title', 'Order #' . $order->id); ?>

<?php $__env->startSection('content'); ?>
<div class="admin-page-header d-block">
    <div class="d-flex justify-content-between align-items-center">
        <div>
            <h1 class="admin-page-title">Order #<?php echo e($order->id); ?></h1>
            <p class="admin-page-subtitle">Order details and management</p>
        </div>
        <div>
            <a href="<?php echo e(route('admin.orders.index')); ?>" class="btn btn-outline-secondary">
                <i class="bi bi-arrow-left"></i> Back to Orders
            </a>
        </div>
    </div>
</div>

<div class="admin-content">
    <!-- Order Status & Quick Info -->
    <div class="row g-4 mb-4">
        <div class="col-md-6 col-lg-3  ">
            <div class="admin-stat-card stat-primary">
                <div class="admin-stat-icon bg-primary">
                    <i class="bi bi-info-circle"></i>
                </div>
                <div class="admin-stat-content">
                    <h3 class="text-primary">#<?php echo e($order->id); ?></h3>
                    <p>Order ID</p>
                </div>
            </div>
        </div>
        <div class="col-md-6  col-lg-3">
            <div class="admin-stat-card stat-<?php echo e($order->status == 'delivered' ? 'success' : ($order->status == 'cancelled' ? 'danger' : ($order->status == 'placed' || $order->status == 'awaiting_payment' ? 'warning' : 'info'))); ?>">
                <div class="admin-stat-icon bg-<?php echo e($order->status == 'delivered' ? 'success' : ($order->status == 'cancelled' ? 'danger' : ($order->status == 'placed' || $order->status == 'awaiting_payment' ? 'warning' : 'info'))); ?>">
                    <i class="bi bi-<?php echo e($order->status == 'delivered' ? 'check-circle' : ($order->status == 'cancelled' ? 'x-circle' : ($order->status == 'placed' ? 'clock' : ($order->status == 'awaiting_payment' ? 'hourglass-split' : 'truck')))); ?>"></i>
                </div>
                <div class="admin-stat-content">
                    <h3><?php echo e(ucfirst($order->status_label)); ?></h3>
                    <p>Order Status</p>
                </div>
            </div>
        </div>
        <div class="col-md-6 col-lg-3">
            <div class="admin-stat-card stat-<?php echo e($order->payment_status == 'paid' ? 'success' : ($order->payment_status == 'failed' ? 'danger' : ($order->isCodOrder() ? 'info' : 'warning'))); ?>">
                <div class="admin-stat-icon bg-<?php echo e($order->payment_status == 'paid' ? 'success' : ($order->payment_status == 'failed' ? 'danger' : ($order->isCodOrder() ? 'info' : 'warning'))); ?>">
                    <?php if($order->isCodOrder()): ?>
                        <i class="bi bi-cash-coin"></i>
                    <?php elseif($order->isAbandonedPayment()): ?>
                        <i class="bi bi-x-circle"></i>
                    <?php elseif($order->payment_status == 'paid'): ?>
                        <i class="bi bi-check-circle"></i>
                    <?php elseif($order->payment_status == 'failed'): ?>
                        <i class="bi bi-exclamation-triangle"></i>
                    <?php else: ?>
                        <i class="bi bi-clock"></i>
                    <?php endif; ?>
                </div>
                <div class="admin-stat-content">
                    <h3 style="font-size: 0.9rem; line-height: 1.3;"><?php echo e($order->getPaymentStatusDisplay()); ?></h3>
                    <p>Payment Status</p>
                </div>
            </div>
        </div>
        <div class="col-md-6  col-lg-3">
            <div class="admin-stat-card stat-success">
                <div class="admin-stat-icon bg-success">
                    <i class="bi bi-currency-dollar"></i>
                </div>
                <div class="admin-stat-content">
                    <h3 class="text-success">₹<?php echo e(number_format($order->total_payable, 2)); ?></h3>
                    <p>Total Amount</p>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <!-- Left Column - Main Content -->
        <div class="col-lg-8">
            <?php 
                $addr = $order->address_snapshot ?? null;
                $canEditAddress = in_array($order->status, [
                    \App\Models\Order::STATUS_AWAITING_PAYMENT,
                    \App\Models\Order::STATUS_PLACED,
                    \App\Models\Order::STATUS_CONFIRMED,
                    \App\Models\Order::STATUS_PACKED,
                ], true);
            ?>
            <div class="row g-4 mb-4">
                <div class="col-xl-12">
                    <!-- Order Status Update -->
                    <div class="admin-card h-100">
                        <div class="card-header">
                            <h5 class="mb-0">
                                <i class="bi bi-pencil-square me-2"></i>Update Order Status
                            </h5>
                        </div>
                        <div class="card-body">
                            <?php
                                $hasManualCarrierShipment = isset($order->shipments) && $order->shipments->isNotEmpty()
                                    && $order->shipments->contains(fn ($s) => $s->carrier && $s->carrier->isManual());
                            ?>
                            <?php if($hasManualCarrierShipment && $order->status !== 'delivered' && $order->status !== 'cancelled'): ?>
                                <div class="alert alert-secondary mb-3">
                                    <i class="bi bi-truck me-2"></i>
                                    <strong>Manual carrier:</strong> This order was shipped via a manual carrier (e.g. India Postal, Other). Order status will be automatically set to <strong>Delivered</strong> 5 days after the tracking number was saved.
                                </div>
                            <?php endif; ?>
                            <?php
                                $isAdmin = auth()->user()->isAdmin();
                                $currentStatus = $order->status;
                                $statusLocked = $currentStatus === 'cancelled' || $currentStatus === 'returned'
                                    || (in_array($currentStatus, ['delivered'], true) && !$isAdmin);

                                $statusSequence = [
                                    'awaiting_payment' => 1,
                                    'placed' => 2,
                                    'confirmed' => 3,
                                    'packed' => 4,
                                    'awaiting_pickup' => 5,
                                    'shipped' => 6,
                                    'delivery_failed' => 7,
                                    'delivered' => 8,
                                ];

                                $currentOrder = $statusSequence[$currentStatus] ?? 0;

                                $allStatuses = [
                                    'awaiting_payment' => 'Awaiting Payment',
                                    'placed' => 'Placed',
                                    'confirmed' => 'Confirmed',
                                    'packed' => 'Packed',
                                    'awaiting_pickup' => 'Awaiting Pickup',
                                    'shipped' => 'Shipped',
                                    'delivery_failed' => 'Delivery Failed',
                                    'delivered' => 'Delivered',
                                    'cancelled' => 'Cancelled',
                                    'returned' => 'Returned',
                                    'lost' => 'Lost',
                                ];

                                $availableStatuses = [];
                                if ($isAdmin && in_array($currentStatus, ['shipped', 'delivered'], true)) {
                                    $availableStatuses[$currentStatus] = $allStatuses[$currentStatus];
                                    if ($currentStatus === 'shipped') {
                                        $availableStatuses['delivered'] = $allStatuses['delivered'];
                                    }
                                    $availableStatuses['cancelled'] = $allStatuses['cancelled'];
                                    $availableStatuses['returned'] = $allStatuses['returned'];
                                } else {
                                    foreach ($allStatuses as $status => $label) {
                                        if ($isAdmin) {
                                            if ($status === 'returned' && !in_array($currentStatus, ['shipped', 'delivered'], true)) {
                                                continue;
                                            }
                                            $availableStatuses[$status] = $label;
                                        } else {
                                            if ($status === 'returned' && $currentStatus === 'delivered') {
                                                $availableStatuses[$status] = $label;
                                            } elseif (isset($statusSequence[$status])) {
                                                $statusOrder = $statusSequence[$status];
                                                if ($statusOrder >= $currentOrder) {
                                                    $availableStatuses[$status] = $label;
                                                }
                                            }
                                        }
                                    }
                                }
                            ?>
                            <form action="<?php echo e(route('admin.orders.update-status', $order->id)); ?>" method="POST" class="row g-3">
                                <?php echo csrf_field(); ?>
                                <?php echo method_field('PUT'); ?>
                                <?php if($statusLocked): ?>
                                    <div class="alert alert-info mb-0">
                                        <i class="bi bi-info-circle me-2"></i>
                                        This order has been <?php echo e(str_replace('_', ' ', $currentStatus)); ?> and its status cannot be changed.
                                    </div>
                                <?php else: ?>
                                <?php if($isAdmin && in_array($currentStatus, ['shipped', 'delivered'], true)): ?>
                                    <div class="alert alert-warning">
                                        <i class="bi bi-box-arrow-in-down me-2"></i>
                                        Changing this order to <strong>Cancelled</strong> or <strong>Returned</strong> will automatically restock the sold products.
                                    </div>
                                <?php endif; ?>
                                <div class="col-md-8">
                                    <select name="status" class="form-select" required>
                                        <?php $__currentLoopData = $availableStatuses; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $status => $label): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <option value="<?php echo e($status); ?>" <?php echo e($order->status == $status ? 'selected' : ''); ?>><?php echo e($label); ?></option>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </select>
                                </div>
                                <div class="col-md-4">
                                    <button type="submit" class="btn btn-primary w-100">
                                        <i class="bi bi-check-circle me-2"></i>Update Status
                                    </button>
                                </div>
                                <?php endif; ?>
                            </form>
                        </div>
                    </div>
                </div>

                <?php if(!empty($addr['line1']) || !empty($addr['line2']) || !empty($addr['city']) || !empty($addr['state']) || !empty($addr['pin'])): ?>
                    <div class="col-xl-12">
                        <div class="admin-card h-100">
                            <div class="card-header">
                                <div class="d-flex justify-content-between align-items-center">
                                    <h5 class="mb-0">
                                        <i class="bi bi-geo-alt me-2"></i>
                                        Shipping Address
                                    </h5>
                                    <?php if($canEditAddress): ?>
                                        <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#editAddressModal">
                                            <i class="bi bi-pencil"></i> Edit Address
                                        </button>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <div class="card-body" id="shippingAddressDisplay">
                                <?php if($order->address_snapshot): ?>
                                    <?php
                                        $addr = $order->address_snapshot;
                                        $displayMobileDigits = preg_replace('/\D/', '', (string) ($addr['mobile'] ?? ''));
                                        $displayMobileDigits = preg_replace('/^(?:91|0)?/', '', $displayMobileDigits);
                                        if (strlen($displayMobileDigits) > 10) {
                                            $displayMobileDigits = substr($displayMobileDigits, -10);
                                        }
                                        $displayMobileFormatted = strlen($displayMobileDigits) === 10
                                            ? '+91 ' . $displayMobileDigits
                                            : ($addr['mobile'] ?? 'N/A');
                                    ?>
                                    <div class="row g-3">
                                        <div class="col-md-6">
                                            <p class="mb-2"><strong>Name:</strong>
                                            <span class="text-muted" id="addr-name"><?php echo e($addr['name'] ?? 'N/A'); ?></span></p>
                                        </div>
                                        <div class="col-md-6">
                                            <p class="mb-2"><strong>Mobile:</strong>
                                            <span class="text-muted" id="addr-mobile"><?php echo e($displayMobileFormatted); ?></span></p>
                                        </div>
                                        <div class="col-12">
                                            <p class="mb-2"><strong>Address:</strong></p>
                                            <p class="text-muted mb-0" id="addr-full">
                                                <?php echo e($addr['line1'] ?? ''); ?><br>
                                                <?php if(!empty($addr['line2'])): ?>
                                                    <?php echo e($addr['line2']); ?><br>
                                                <?php endif; ?>
                                                <?php echo e(($addr['city'] ?? '')); ?>, <?php echo e(($addr['state'] ?? '')); ?> - <?php echo e(($addr['pin'] ?? '')); ?>

                                            </p>
                                        </div>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>
            </div>

            <!-- Shipping Panel -->
            <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('manage shipping')): ?>
            <?php if(($order->status === 'delivery_failed' || $order->status === 'packed') && (!$order->shipments || $order->shipments->isEmpty() || $order->shipments?->where('tracking_id', null)->isNotEmpty())): ?>
            <div class="admin-card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="bi bi-truck me-2"></i>Initiate Shipment
                    </h5>
                </div>
                <div class="card-body">
                    <form id="shipmentForm" method="POST" action="<?php echo e(route('admin.orders.shipments.store', $order->id)); ?>">
                        <?php echo csrf_field(); ?>
                        <div class="mb-3">
                            <label for="carrier_id" class="form-label fw-bold">Select Carrier *</label>
                            <select name="carrier_id" id="carrier_id" class="form-select" required onchange="loadCarrierFields()">
                                <option value="">-- Select Carrier --</option>
                                <?php $__currentLoopData = $carriers; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $carrier): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <option value="<?php echo e($carrier->id); ?>" data-schema="<?php echo e(json_encode($carrier->config_schema ?? [])); ?>" data-process-type="<?php echo e($carrier->process_type ?? 'automatic'); ?>">
                                        <?php echo e($carrier->name); ?>

                                    </option>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </select>
                            <?php if($carriers->isEmpty()): ?>
                                <small class="text-muted">No enabled carriers available. Please configure carriers in Settings.</small>
                            <?php endif; ?>
                        </div>

                        <!-- Manual carrier: tracking number only -->
                        <div id="manualTrackingContainer" class="mb-3" style="display: none;">
                            <label for="tracking_number" class="form-label fw-bold">Tracking Number *</label>
                            <input type="text" name="tracking_number" id="tracking_number" class="form-control" placeholder="Enter tracking number">
                            <small class="text-muted">Staff will send the order manually; enter the tracking number here.</small>
                            <div class="mt-3">
                                <button type="submit" class="btn btn-success">
                                    <i class="bi bi-check-lg me-2"></i>Save Tracking Number
                                </button>
                            </div>
                        </div>
                        
                        <div id="dynamicFields"></div>
                        
                        <!-- Delivery Availability Warning -->
                        <div id="deliveryAvailabilityWarning" class="alert alert-warning mt-3" style="display: none;">
                            <i class="bi bi-exclamation-triangle me-2"></i>
                            <span id="deliveryAvailabilityMessage"></span>
                        </div>
                        
                        <div class="col-12 mb-3" id="deliveryFieldsContainer" style="display:none;">
                            <input type="hidden" name="orderid" value="<?php echo e($order->id); ?>" />
                                <div class="row border-top py-3 border-sm-bottom my-3">
                                    <div class="col-sm-3">
                                        <label>
                                            length in cms
                                        </label>
                                        <input type="text" class="form-control col-md-12" id=""  name="shipping_length"  value="10" required>
                                        <input type="hidden" class="form-control col-md-12" id=""  name="product_desc"  value="<?php echo e(isset($product_name) ? $product_name : ''); ?>">
                                    </div>
                        
                                    <div class="col-sm-3">
                                        <label >
                                            Width in cms
                                        </label>
                                        <input type="text" class="form-control col-md-12"  name="shipping_width"  value="5" required>
                                    </div>

                                    <div class="col-sm-3">
                                        <label>
                                            Height in cms
                                        </label>
                                        <input type="text" class="form-control col-md-12" id=""   name="shipping_height" value="3" required>
                                        <small>Length + Breadth + Height should be at-least 15 cm</small>
                                    </div>

                                    <div class="col-sm-3">
                                        <label>
                                            Package weight in grams
                                        </label>
                                            <input type="text" class="form-control col-md-12" id="shipping_weight"  name="shipping_weight" value="55" required>
                                            <small>Packaged weight should be at least 50 grams</small>
                                    </div>
                                </div>
                                <div class="row border-sm-bottom pb-3 mb-3">
                                    <div class="col-sm-4">                       
                                        <label> Shipping Mode : </label>
                                        <select class="form-control aiz-selectpicker" name="shipping_mode" id="shipping_mode" data-live-search="true" required>                                      -->
                                            <option value="surface">Surface</option>     
                                            <option value="express">Express</option>   
                                        </select>
                                    </div>

                                    <div class="col-sm-4">
                                    <label>
                                        Package Type 
                                    </label>
                                        <select class="form-control aiz-selectpicker" name="package_type" id="package_type" data-live-search="true" required>
                                            <!-- <option value="">Package Type</option> -->
                                            <option value="cover">Plastic cover/Flyer</option>     
                                            <option value="board">Cardboard Box</option>   
                                        </select>
                                    </div>

                                     
                                </div>
                                <div class="mt-3">
                                    <button type="submit" class="btn btn-success">
                                        <i class="bi bi-truck me-2"></i>Initiate Shipment
                                    </button>
                                </div>
                        </div>
                    </form>
                </div>
            </div>

            <div class="modal fade" id="shipmentErrorModal" tabindex="-1" aria-labelledby="shipmentErrorModalLabel" aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered">
                    <div class="modal-content border-0 shadow">
                        <div class="modal-header bg-warning text-dark">
                            <h5 class="modal-title" id="shipmentErrorModalLabel">
                                <i class="bi bi-exclamation-triangle-fill me-2"></i>
                                <span id="shipmentErrorModalTitle">Shipment Failed</span>
                            </h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <p class="mb-2 fw-semibold" id="shipmentErrorModalMessage"></p>
                            <p class="mb-0 text-muted" id="shipmentErrorModalAction"></p>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-primary" data-bs-dismiss="modal">OK, choose another carrier</button>
                        </div>
                    </div>
                </div>
            </div>
            <?php endif; ?>
            <?php endif; ?>

            <!-- Shipment Details -->
            <?php if(isset($order->shipments) && $order->shipments->isNotEmpty()): ?>
                <?php $__currentLoopData = $order->shipments; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $shipment): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <div class="admin-card mb-4">
                        <div class="card-header">
                            <h5 class="mb-0">
                                <i class="bi bi-box-seam me-2"></i>Shipment Information - <?php echo e($shipment->carrier->name ?? 'N/A'); ?>

                            </h5>
                        </div>
                        <div class="card-body">
                            <div class="row g-3">
                                <div class="col-md-6  col-lg-3">
                                    <p class="mb-2"><strong>Carrier:</strong>
                                    <span class="text-muted"><?php echo e($shipment->carrier->name ?? 'N/A'); ?></span></p>
                                </div>
                                <div class="col-md-6  col-lg-3">
                                    <p class="mb-2"><strong>Status:</strong>
                                    <span class="badge bg-<?php echo e($shipment->status === 'created' ? 'success' : ($shipment->status === 'failed' ? 'danger' : 'warning')); ?>">
                                        <?php echo e(ucwords($shipment->status)); ?>

                                    </span></p>
                                </div>
                                <?php if($shipment->tracking_id || $order->delhivery_awb): ?>
                                <div class="col-md-6 col-lg-3">
                                    <p class="mb-2"><strong>Tracking ID:</strong>
                                    <span class="text-muted"><?php echo e($shipment->tracking_id ?? $order->delhivery_awb); ?></span></p>
                                </div>
                                <?php endif; ?>
                                <?php if($shipment->carrier && ($shipment->tracking_id || $order->delhivery_awb)): ?>
                                    <div class="col-md-6  col-lg-3">
                                        <p class="mb-2"><strong>Label:</strong>
                                        <a href="<?php echo e(route('admin.orderlabel.genarate', encrypt($order->id))); ?>" target="_blank" class="btn btn-success">
                                            <i class="bi bi-file-pdf me-1"></i>View Label
                                        </a></p>
                                    </div>
                                <?php endif; ?>
                                <div class="col-12">
                                    <p class="mb-0 text-muted small">
                                        <i class="bi bi-calendar me-1"></i>Created: <?php echo e($shipment->created_at->format('M d, Y h:i A')); ?>

                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            <?php endif; ?>

            <!-- Order Items -->
            <div class="admin-card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="bi bi-cart me-2"></i>Order Items (<?php echo e($order->items->count()); ?>)
                    </h5>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table admin-table mb-0">
                            <thead>
                                <tr class="border-bottom">
                                    <th>Product</th>
                                    <th>Barcode</th>
                                    <th>Quantity</th>
                                    <th>Unit Price</th>
                                    <th>Tax</th>
                                    <th>Total</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php $__currentLoopData = $order->items; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $item): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <tr>
                                        <td>
                                            <div class="d-flex align-items-center">
                                                <?php if($item->product && ($item->product->image_path || $item->product->image)): ?>
                                                    <?php if (isset($component)) { $__componentOriginala58dde406db9207f2e2c58e1c4a3d690 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginala58dde406db9207f2e2c58e1c4a3d690 = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'components.product-image','data' => ['product' => $item->product,'context' => 'thumb','class' => 'admin-image-preview me-3','style' => 'width: 60px; height: 60px;','alt' => ''.e($item->name).'']] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('product-image'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['product' => \Illuminate\View\Compilers\BladeCompiler::sanitizeComponentAttribute($item->product),'context' => 'thumb','class' => 'admin-image-preview me-3','style' => 'width: 60px; height: 60px;','alt' => ''.e($item->name).'']); ?>
<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginala58dde406db9207f2e2c58e1c4a3d690)): ?>
<?php $attributes = $__attributesOriginala58dde406db9207f2e2c58e1c4a3d690; ?>
<?php unset($__attributesOriginala58dde406db9207f2e2c58e1c4a3d690); ?>
<?php endif; ?>
<?php if (isset($__componentOriginala58dde406db9207f2e2c58e1c4a3d690)): ?>
<?php $component = $__componentOriginala58dde406db9207f2e2c58e1c4a3d690; ?>
<?php unset($__componentOriginala58dde406db9207f2e2c58e1c4a3d690); ?>
<?php endif; ?>
                                                <?php else: ?>
                                                    <div class="admin-image-preview me-3 d-flex align-items-center justify-content-center bg-light" style="width: 60px; height: 60px;">
                                                        <i class="bi bi-image text-muted"></i>
                                                    </div>
                                                <?php endif; ?>
                                                <div>
                                                    <strong><?php echo e($item->name); ?></strong>
                                                </div>
                                            </div>
                                        </td>
                                        <td><code><?php echo e($item->product->barcode ?? ''); ?></code></td>
                                        <td>
                                            <span class="badge bg-primary"><?php echo e($item->qty); ?></span>
                                        </td>
                                        <td>₹<?php echo e(number_format($item->price, 2)); ?></td>
                                        <td>
                                            <?php if($item->tax_amount > 0): ?>
                                                <span class="text-muted">₹<?php echo e(number_format($item->tax_amount, 2)); ?></span>
                                            <?php else: ?>
                                                <span class="text-muted">₹0.00</span>
                                            <?php endif; ?>
                                        </td>
                                        <td><strong>₹<?php echo e(number_format($item->line_total, 2)); ?></strong></td>
                                    </tr>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </tbody>
                            <tfoot>
                                <tr class="border-top">
                                    <td colspan="4" class="text-end"><strong>Total Tax:</strong></td>
                                    <td><strong>₹<?php echo e(number_format($order->items->sum('tax_amount'), 2)); ?></strong></td>
                                    <td><strong>₹<?php echo e(number_format($order->items->sum('line_total'), 2)); ?></strong></td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                </div>
            </div>

            <!-- POS Info -->
            <?php if($order->source === 'pos'): ?>
            <div class="admin-card">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="bi bi-shop me-2"></i>
                        POS Sale Information
                    </h5>
                </div>
                <div class="card-body">
                    <?php 
                        $addr = $order->address_snapshot;
                        $deliveryType = $addr['delivery_type'] ?? 'store_pickup';
                    ?>
                    <div class="row g-3">
                        <div class="col-md-6  col-lg-3">
                            <p class="mb-2"><strong>Sale Type:</strong>
                            <span class="text-muted">Point of Sale <?php if($deliveryType === 'courier'): ?> (Courier Delivery) <?php else: ?> <?php endif; ?></span></p>
                        </div>
                        <?php if($order->staff): ?>
                        <div class="col-md-6  col-lg-3">
                            <p class="mb-2"><strong>Processed by:</strong>
                            <span class="text-muted"><?php echo e($order->staff->name); ?></span></p>
                        </div>
                        <?php endif; ?>
                        <div class="col-md-6  col-lg-3">
                            <p class="mb-2"><strong>Payment Method:</strong>
                            <span class="text-muted"><?php echo e(ucfirst(str_replace('_', ' ', $order->payment_method ?? 'N/A'))); ?></span></p>
                        </div>
                    </div>
                </div>
            </div>
            <?php endif; ?>
        </div>

        <!-- Right Column - Sidebar -->
        <div class="col-lg-4">
            <!-- Order Summary -->
            <div class="admin-card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="bi bi-receipt me-2"></i>Order Summary
                    </h5>
                </div>
                <div class="card-body">
                    <div class="d-flex justify-content-between mb-1 py-1 border-bottom">
                        <span class="text-muted">Subtotal:</span>
                        <strong>₹<?php echo e(number_format($order->subtotal, 2)); ?></strong>
                    </div>
                    <?php if($order->discount_total > 0): ?>
                        <div class="d-flex justify-content-between mb-1 py-1 border-bottom">
                            <span class="text-success">
                                <i class="bi bi-tag me-1"></i>Discount:
                            </span>
                            <strong class="text-success">-₹<?php echo e(number_format($order->discount_total, 2)); ?></strong>
                        </div>
                    <?php endif; ?>
                    <div class="d-flex justify-content-between mb-1 py-1 border-bottom">
                        <span class="text-muted">Shipping:</span>
                        <strong>₹<?php echo e(number_format($order->shipping_total, 2)); ?></strong>
                    </div>
                    <div class="d-flex justify-content-between pt-3 border-bottom">
                        <span class="h5 mb-0">Total:</span>
                        <strong class="h5 mb-0 text-success">₹<?php echo e(number_format($order->total_payable, 2)); ?></strong>
                    </div>
                    <?php if($order->tax_total > 0): ?>
                        <div class="d-flex justify-content-between mb-1 py-2">
                            <i class="text-muted">Tax Charged on This Order: </i>
                            <i><strong>₹<?php echo e(number_format($order->tax_total, 2)); ?></strong></i>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Customer Details -->
            <div class="admin-card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="bi bi-person me-2"></i>Customer Details
                    </h5>
                </div>
                <div class="card-body">
                    <div class="d-flex align-items-center mb-3">
                        <div class="avatar-sm me-3">
                            <span class="avatar-title bg-primary rounded-circle" style="width: 50px; height: 50px; display: flex; align-items: center; justify-content: center; font-size: 1.25rem; font-weight: 600;">
                                <?php echo e(substr($order->user->name ?? 'G', 0, 1)); ?>

                            </span>
                        </div>
                        <div>
                            <strong><?php echo e($order->user->name ?? 'Guest User'); ?></strong>
                            <br><small class="text-muted"><?php echo e($order->user->email ?? 'N/A'); ?></small>
                        </div>
                    </div>
                    <div class="border-top pt-3">
                        <p class="mb-2">
                            <i class="bi bi-telephone me-2 text-muted"></i>
                            <strong>Mobile:</strong> <?php echo e($order->user->mobile ?? 'N/A'); ?>

                        </p>
                        <?php if($order->user->email): ?>
                        <p class="mb-0">
                            <i class="bi bi-envelope me-2 text-muted"></i>
                            <strong>Email:</strong> <?php echo e($order->user->email); ?>

                        </p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Order Information -->
            <div class="admin-card">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="bi bi-info-circle me-2"></i>Order Information
                    </h5>
                </div>
                <div class="card-body">
                    <div class="mb-3 pb-3 border-bottom">
                        <p class="mb-2"><strong>Source:</strong>
                        <span class="badge bg-<?php echo e($order->source === 'pos' ? 'info' : 'primary'); ?>">
                            <i class="bi bi-<?php echo e($order->source === 'pos' ? 'shop' : 'globe'); ?> me-1"></i>
                            <?php echo e(strtoupper($order->source ?? 'online')); ?>

                        </span></p>
                    </div>
                    <div class="mb-3 pb-3 border-bottom">
                        <p class="mb-2"><strong>Order ID:</strong>
                        <span class="text-muted mb-0">#<?php echo e($order->id); ?></span></p>
                    </div>
                    <div class="mb-3 pb-3 border-bottom">
                        <p class="mb-2"><strong>Placed At:</strong>
                        <span class="text-muted mb-0">
                            <i class="bi bi-calendar me-1"></i>
                            <?php echo e($order->placed_at ? $order->placed_at->format('M d, Y') : $order->created_at->format('M d, Y')); ?>

                            <small>
                                <i class="bi bi-clock me-1"></i>
                                <?php echo e($order->placed_at ? $order->placed_at->format('h:i A') : $order->created_at->format('h:i A')); ?>

                            </small>
                        </span></p>
                    </div>
                    <div class="mb-3 pb-3 border-bottom">
                        <p class="mb-2"><strong>Payment Method:</strong>
                        <span class="text-muted mb-2"><?php echo e($order->getPaymentTypeLabel()); ?></span></p>
                        <?php if($order->payment_method === 'online'): ?>
                            <p class="mb-1"><strong>Razorpay Order ID:</strong>
                                <code><?php echo e($order->razorpay_order_id ?: 'N/A'); ?></code>
                            </p>
                            <p class="mb-0"><strong>Razorpay Payment ID:</strong>
                                <code><?php echo e($order->razorpay_payment_id ?: 'N/A'); ?></code>
                            </p>
                        <?php endif; ?>
                        <?php if($order->payment_method === 'offline' && $order->payment_screenshot_path): ?>
                            <p class="mb-1 mt-2"><strong>Payment screenshot:</strong></p>
                            <a href="<?php echo e(asset('storage/' . $order->payment_screenshot_path)); ?>" target="_blank" rel="noopener" class="d-inline-block">
                                <img src="<?php echo e(asset('storage/' . $order->payment_screenshot_path)); ?>" alt="Payment screenshot" class="img-thumbnail" style="max-width: 200px; max-height: 200px;">
                            </a>
                            <p class="small text-muted mb-0"><a href="<?php echo e(asset('storage/' . $order->payment_screenshot_path)); ?>" target="_blank" rel="noopener">View full size</a></p>
                        <?php endif; ?>
                    </div>
                    <div class="mb-3 pb-3 border-bottom">
                        <p class="mb-2"><strong>Payment Status:</strong>
                        <span class="badge <?php echo e($order->getPaymentStatusBadgeClass()); ?>" style="
                            <?php if($order->isCodOrder()): ?>
                                background-color: #DBEAFE; color: #1E40AF; border: 1px solid #93C5FD;
                            <?php elseif($order->isAbandonedPayment()): ?>
                                background-color: #FEE2E2; color: #991B1B; border: 1px solid #FCA5A5;
                            <?php elseif($order->payment_status == 'paid'): ?>
                                background-color: #D1FAE5; color: #065F46;
                            <?php elseif($order->payment_status == 'failed'): ?>
                                background-color: #FEE2E2; color: #991B1B;
                            <?php elseif($order->payment_status == 'pending'): ?>
                                background-color: #FEF3C7; color: #92400E;
                            <?php else: ?>
                                background-color: #E0E7FF; color: #3730A3;
                            <?php endif; ?>
                        ">
                            <?php if($order->isCodOrder()): ?>
                                <i class="bi bi-cash-coin"></i>
                            <?php elseif($order->isAbandonedPayment()): ?>
                                <i class="bi bi-x-circle"></i>
                            <?php elseif($order->payment_status == 'paid'): ?>
                                <i class="bi bi-check-circle"></i>
                            <?php elseif($order->payment_status == 'failed'): ?>
                                <i class="bi bi-exclamation-triangle"></i>
                            <?php else: ?>
                                <i class="bi bi-clock"></i>
                            <?php endif; ?>
                            <?php echo e($order->getPaymentStatusDisplay()); ?>

                        </span></p>
                        <?php if($order->isCodOrder() && $order->payment_status == 'pending'): ?>
                            <p class="text-muted small mt-2 mb-0">
                                <i class="bi bi-info-circle"></i> Payment will be collected on delivery
                            </p>
                        <?php elseif($order->isAbandonedPayment()): ?>
                            <p class="text-warning small mt-2 mb-0">
                                <i class="bi bi-exclamation-triangle"></i> Payment was not completed
                            </p>
                        <?php endif; ?>
                    </div>
                    <div>
                        <p class="mb-2"><strong>Order Status:</strong>
                        <span class="badge bg-<?php echo e($order->status == 'delivered' ? 'success' : ($order->status == 'placed' ? 'warning' : ($order->status == 'cancelled' ? 'danger' : 'primary'))); ?>">
                            <?php echo e(ucfirst($order->status)); ?>

                        </span></p>
                    </div>
                    <?php if($order->coupon): ?>
                    <div class="mt-3 pt-3 border-top">
                        <p class="mb-2"><strong>Coupon Used:</strong>
                        <span class="badge bg-secondary"><?php echo e($order->coupon->code); ?></span></p>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Edit Address Modal -->
    <?php if($canEditAddress && $order->address_snapshot): ?>
    <div class="modal fade mt-5" id="editAddressModal" tabindex="-1" aria-labelledby="editAddressModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editAddressModalLabel">
                        <i class="bi bi-pencil me-2"></i>Edit Shipping Address
                    </h5>
                    <button type="button" class="btn p-0 text-white" data-bs-dismiss="modal" aria-label="Close"><i class="bi-x-lg"></i></button>
                </div>
                <form id="editAddressForm"
                      data-initial-country-id="<?php echo e($order->address_snapshot['country_id'] ?? ''); ?>"
                      data-initial-state-id="<?php echo e($order->address_snapshot['state_id'] ?? ''); ?>"
                      data-initial-city-id="<?php echo e($order->address_snapshot['city_id'] ?? ''); ?>"
                      data-initial-city-name="<?php echo e($order->address_snapshot['city'] ?? ''); ?>">
                    <?php echo csrf_field(); ?>
                    <?php echo method_field('PUT'); ?>
                    <div class="modal-body">
                        <?php
                            $addr = $order->address_snapshot;
                            $editMobileDigits = preg_replace('/\D/', '', (string) ($addr['mobile'] ?? ''));
                            $editMobileDigits = preg_replace('/^(?:91|0)?/', '', $editMobileDigits);
                            if (strlen($editMobileDigits) > 10) {
                                $editMobileDigits = substr($editMobileDigits, -10);
                            }
                        ?>
                        <div class="row g-3">
                            <div class="col-md-6  col-lg-3">
                                <label for="edit_name" class="form-label">Name <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="edit_name" name="name" value="<?php echo e($addr['name'] ?? ''); ?>" required>
                            </div>
                            <div class="col-md-6  col-lg-3">
                                <label for="edit_mobile" class="form-label">Mobile <span class="text-danger">*</span></label>
                                <div class="input-group">
                                    <span class="input-group-text">+91</span>
                                    <input type="text" class="form-control" id="edit_mobile" name="mobile"
                                           value="<?php echo e($editMobileDigits); ?>"
                                           placeholder="9876543210"
                                           pattern="[6-9]\d{9}"
                                           maxlength="10"
                                           inputmode="numeric"
                                           autocomplete="tel-national"
                                           required>
                                </div>
                            </div>
                            <div class="col-12">
                                <label for="edit_line1" class="form-label">Address Line 1 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="edit_line1" name="line1" value="<?php echo e($addr['line1'] ?? ''); ?>" required>
                            </div>
                            <div class="col-12">
                                <label for="edit_line2" class="form-label">Address Line 2</label>
                                <input type="text" class="form-control" id="edit_line2" name="line2" value="<?php echo e($addr['line2'] ?? ''); ?>">
                            </div>
                            <div class="col-md-4">
                                <label for="edit_country_id" class="form-label">Country <span class="text-danger">*</span></label>
                                <select name="country_id" id="edit_country_id" class="form-select no-select2" required data-country-select>
                                    <option value="">Select country</option>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label for="edit_state_id" class="form-label">State <span class="text-danger">*</span></label>
                                <select name="state_id" id="edit_state_id" class="form-select no-select2" required data-state-select disabled>
                                    <option value="">Select state</option>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label for="edit_city_id" class="form-label">City <span class="text-danger">*</span></label>
                                <select name="city_id" id="edit_city_id" class="form-select no-select2" required data-city-select disabled>
                                    <option value="">Select city</option>
                                </select>
                                <div class="d-none mt-2" data-city-custom-wrap>
                                    <label class="form-label small mb-1">Enter city *</label>
                                    <input type="text" name="city_custom" class="form-control" maxlength="100" data-city-custom>
                                </div>
                            </div>
                            <div class="col-12">
                                <?php echo $__env->make('partials.address-city-help', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
                            </div>
                            <div class="col-md-4">
                                <label for="edit_pin" class="form-label">Pincode <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="edit_pin" name="pin" value="<?php echo e($addr['pin'] ?? ''); ?>" pattern="[1-9]\d{5}" maxlength="6" inputmode="numeric" required>
                            </div>
                        </div>
                        <div id="addressEditError" class="alert alert-danger mt-3" style="display: none;"></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-primary" id="saveAddressBtn">
                            <span class="spinner-border spinner-border-sm d-none" role="status" aria-hidden="true"></span>
                            <span class="btn-text">Update Address</span>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <?php endif; ?>
</div>

<?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('manage shipping')): ?>
<?php $__env->startPush('scripts'); ?>
<script>
function loadCarrierFields() {
    const carrierSelect = document.getElementById('carrier_id');
    if (!carrierSelect) {
        return;
    }
    const selectedOption = carrierSelect.options[carrierSelect.selectedIndex];
    const manualContainer = document.getElementById('manualTrackingContainer');
    const dynamicFields = document.getElementById('dynamicFields');
    const deliveryFieldsContainer = document.getElementById('deliveryFieldsContainer');
    const deliveryWarning = document.getElementById('deliveryAvailabilityWarning');
    const trackingInput = document.getElementById('tracking_number');

    if (!selectedOption.value) {
        if (manualContainer) manualContainer.style.display = 'none';
        if (dynamicFields) dynamicFields.innerHTML = '';
        if (deliveryFieldsContainer) deliveryFieldsContainer.style.display = 'none';
        if (deliveryWarning) deliveryWarning.style.display = 'none';
        if (trackingInput) trackingInput.removeAttribute('required');
        return;
    }

    const processType = selectedOption.getAttribute('data-process-type') || 'automatic';
    if (processType === 'manual') {
        if (manualContainer) manualContainer.style.display = 'block';
        if (trackingInput) { trackingInput.setAttribute('required', 'required'); trackingInput.value = ''; }
        if (dynamicFields) dynamicFields.innerHTML = '';
        if (deliveryFieldsContainer) deliveryFieldsContainer.style.display = 'none';
        if (deliveryWarning) deliveryWarning.style.display = 'none';
        return;
    }

    if (manualContainer) manualContainer.style.display = 'none';
    if (trackingInput) { trackingInput.removeAttribute('required'); trackingInput.value = ''; }
    checkDeliveryAvailability(carrierSelect.value);
}

function checkDeliveryAvailability(carrierId) {
    const deliveryFieldsContainer = document.getElementById('deliveryFieldsContainer');
    const warningDiv = document.getElementById('deliveryAvailabilityWarning');
    const warningMessage = document.getElementById('deliveryAvailabilityMessage');

    if (!carrierId) {
        // Hide button and warning if no carrier selected
        if (deliveryFieldsContainer) deliveryFieldsContainer.style.display = 'none';
        if (warningDiv) warningDiv.style.display = 'none';
        return;
    }

    // Show loading state
    if (warningDiv) {
        warningDiv.className = 'alert alert-info mt-3';
        warningDiv.style.display = 'block';
        if (warningMessage) {
            warningMessage.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Checking delivery availability...';
        }
    }
    if (deliveryFieldsContainer) deliveryFieldsContainer.style.display = 'none';

    // Make AJAX call to check delivery availability
    fetch('<?php echo e(route("admin.orders.check-delivery", $order->id)); ?>', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content || document.querySelector('input[name="_token"]')?.value,
            'Accept': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: JSON.stringify({
            carrier_id: carrierId
        })
    })
    .then(response => {
        if (!response.ok) {
            return response.json().then(data => {
                throw new Error((data && data.error) ? data.error : 'Failed to check delivery availability');
            });
        }
        return response.json();
    })
    .then(data => {
        if (data.available) {
            // Delivery is available - show button, hide warning
            if (deliveryFieldsContainer) deliveryFieldsContainer.style.display = 'block';
            if (warningDiv) warningDiv.style.display = 'none';
        } else {
            // Delivery not available - hide button, show warning
            if (deliveryFieldsContainer) deliveryFieldsContainer.style.display = 'none';
            if (warningDiv) {
                warningDiv.className = 'alert alert-warning mt-3';
                warningDiv.style.display = 'block';
                if (warningMessage) {
                    const carrierName = data.carrier_name || 'This carrier';
                    const pincode = data.pincode ? ` (PIN: ${data.pincode})` : '';
                    const action = data.action || 'Please choose another shipping service from the carrier dropdown.';
                    warningMessage.innerHTML = `<strong>${carrierName} cannot deliver to this customer pincode${pincode}.</strong> ${action}`;
                }
            }
        }
    })
    .catch(error => {
        console.error('Error checking delivery availability:', error);
        // On error, show button but also show warning
        if (deliveryFieldsContainer) deliveryFieldsContainer.style.display = 'none';
        if (warningDiv) {
            warningDiv.className = 'alert alert-warning mt-3';
            warningDiv.style.display = 'block';
            if (warningMessage) {
                warningMessage.textContent = 'Unable to verify delivery availability. Please proceed with caution.';
            }
        }
    });
}

function showShipmentFailure(payload) {
    const data = payload && typeof payload === 'object' ? payload : { error: String(payload || 'Failed to initiate shipment') };
    const modalEl = document.getElementById('shipmentErrorModal');

    if (modalEl && (data.title || data.failure_reason === 'non_serviceable_pincode' || data.failure_reason === 'insufficient_balance')) {
        const titleEl = document.getElementById('shipmentErrorModalTitle');
        const messageEl = document.getElementById('shipmentErrorModalMessage');
        const actionEl = document.getElementById('shipmentErrorModalAction');

        if (titleEl) titleEl.textContent = data.title || 'Shipment could not be created';
        if (messageEl) messageEl.textContent = data.message || data.error || 'Shipment could not be created.';
        if (actionEl) actionEl.textContent = data.action || 'The order is still packed. You can try again.';

        bootstrap.Modal.getOrCreateInstance(modalEl).show();
        return;
    }

    alert(data.message || data.error || 'Failed to initiate shipment');
}

document.addEventListener('DOMContentLoaded', function() {
    const shipmentForm = document.getElementById('shipmentForm');

    if (!shipmentForm) {
        return;
    }

    shipmentForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        const carrierSelect = document.getElementById('carrier_id');
        const selectedOption = carrierSelect ? carrierSelect.options[carrierSelect.selectedIndex] : null;
        const processType = selectedOption ? (selectedOption.getAttribute('data-process-type') || 'automatic') : 'automatic';

        const submitData = new FormData();
        submitData.append('carrier_id', formData.get('carrier_id'));
        submitData.append('_token', formData.get('_token'));

        if (processType === 'manual') {
            submitData.append('tracking_number', formData.get('tracking_number') || '');
        } else {
            submitData.append('orderid', formData.get('orderid'));
            submitData.append('length', formData.get('shipping_length'));
            submitData.append('width', formData.get('shipping_width'));
            submitData.append('height', formData.get('shipping_height'));
            submitData.append('weight', formData.get('shipping_weight'));
            submitData.append('shipping_mode', formData.get('shipping_mode'));
            submitData.append('package_type', formData.get('package_type'));
            const formDataObj = {};
            formData.forEach((value, key) => {
                if (key.startsWith('form_data[')) {
                    const m = key.match(/form_data\[(.*?)\]/);
                    if (m) formDataObj[m[1]] = value;
                }
            });
            if (Object.keys(formDataObj).length > 0) {
                submitData.append('form_data', JSON.stringify(formDataObj));
            }
        }

        const submitBtn = this.querySelector('button[type="submit"]');
        const originalText = submitBtn.innerHTML;
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Processing...';

        fetch(this.action, {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': formData.get('_token'),
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: submitData
        })
        .then(response => response.text().then(text => {
            let parsed = null;

            if (text) {
                try {
                    parsed = JSON.parse(text);
                } catch (e) {
                    parsed = { error: text.trim() };
                }
            }

            if (!response.ok) {
                const payload = parsed || { error: 'Failed to initiate shipment. Server returned ' + response.status };
                throw payload;
            }

            if (!parsed) {
                throw { error: 'Invalid response from server' };
            }

            return parsed;
        }))
        .then(data => {
            if (data && data.success) {
                location.reload();
            } else {
                showShipmentFailure(data);
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalText;
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showShipmentFailure(error);
            submitBtn.disabled = false;
            submitBtn.innerHTML = originalText;
        });
    });
});
</script>
<?php $__env->stopPush(); ?>
<?php endif; ?>

<?php $__env->startPush('scripts'); ?>
<script src="<?php echo e(asset('js/address-location.js')); ?>"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const editAddressForm = document.getElementById('editAddressForm');
    const editAddressModal = document.getElementById('editAddressModal');
    const shippingApiBase = <?php echo json_encode(url('/api/shipping'), 15, 512) ?>;

    function formatMobileDigitsOnly(raw) {
        let digits = String(raw ?? '').replace(/\D/g, '');
        digits = digits.replace(/^(?:91|0)?/, '');
        return digits.slice(-10);
    }

    function formatMobileForStorage(raw) {
        const digits = formatMobileDigitsOnly(raw);
        return /^[6-9]\d{9}$/.test(digits) ? '+91' + digits : '';
    }

    function formatMobileForDisplay(stored) {
        const digits = formatMobileDigitsOnly(stored);
        return digits.length === 10 ? '+91 ' + digits : (stored || 'N/A');
    }

    const editMobileInput = document.getElementById('edit_mobile');
    if (editMobileInput) {
        editMobileInput.addEventListener('input', function () {
            this.value = this.value.replace(/\D/g, '').slice(0, 10);
        });
    }

    async function fetchShippingJson(url) {
        const response = await fetch(url, { headers: { Accept: 'application/json' } });
        if (!response.ok) {
            throw new Error('Failed to load location data');
        }
        return response.json();
    }

    async function initEditOrderAddressDropdowns() {
        if (!editAddressForm) {
            return;
        }

        const countrySelect = editAddressForm.querySelector('[data-country-select]');
        const stateSelect = editAddressForm.querySelector('[data-state-select]');
        const citySelect = editAddressForm.querySelector('[data-city-select]');
        if (!countrySelect) {
            return;
        }

        const initialCountryId = editAddressForm.dataset.initialCountryId || '';
        const initialStateId = editAddressForm.dataset.initialStateId || '';
        const initialCityId = editAddressForm.dataset.initialCityId || '';
        const initialCityName = editAddressForm.dataset.initialCityName || '';

        const countriesData = await fetchShippingJson(`${shippingApiBase}/countries`);
        const countries = countriesData.data || [];
        let selectedCountry = initialCountryId;
        if (!selectedCountry) {
            const india = countries.find((c) => c.code === 'IN');
            selectedCountry = india ? String(india.id) : '';
        }
        AddressLocation.populateSelect(countrySelect, countries, 'Select country', selectedCountry);

        if (selectedCountry) {
            const statesData = await fetchShippingJson(`${shippingApiBase}/states?country_id=${encodeURIComponent(selectedCountry)}`);
            const states = statesData.data || [];
            AddressLocation.populateSelect(stateSelect, states, 'Select state', initialStateId);
            stateSelect.disabled = states.length === 0;

            if (initialStateId) {
                const citiesData = await fetchShippingJson(`${shippingApiBase}/cities?state_id=${encodeURIComponent(initialStateId)}`);
                const cities = citiesData.data || [];
                AddressLocation.populateSelect(citySelect, cities, 'Select city', initialCityId);
                citySelect.disabled = cities.length === 0;
                await AddressLocation.selectCityAfterLoad(citySelect, cities, initialCityId, initialCityName);
            }
        }

        countrySelect.onchange = async () => {
            const countryId = countrySelect.value;
            AddressLocation.resetSelect(stateSelect, 'Loading states...');
            AddressLocation.resetSelect(citySelect, 'Select city');
            if (!countryId) {
                return;
            }
            const statesData = await fetchShippingJson(`${shippingApiBase}/states?country_id=${encodeURIComponent(countryId)}`);
            const states = statesData.data || [];
            AddressLocation.populateSelect(stateSelect, states, 'Select state');
            stateSelect.disabled = states.length === 0;
        };

        stateSelect.onchange = async () => {
            const stateId = stateSelect.value;
            AddressLocation.resetSelect(citySelect, 'Loading cities...');
            if (!stateId) {
                return;
            }
            const citiesData = await fetchShippingJson(`${shippingApiBase}/cities?state_id=${encodeURIComponent(stateId)}`);
            const cities = citiesData.data || [];
            AddressLocation.populateSelect(citySelect, cities, 'Select city');
            citySelect.disabled = cities.length === 0;
        };

        citySelect.onchange = () => AddressLocation.handleCityChange(editAddressForm);

        const cityCustom = editAddressForm.querySelector('[data-city-custom]');
        if (cityCustom) {
            cityCustom.addEventListener('input', () => AddressLocation.syncHiddenLocationNames(editAddressForm));
        }
    }

    if (editAddressModal) {
        editAddressModal.addEventListener('shown.bs.modal', () => {
            initEditOrderAddressDropdowns().catch((error) => {
                console.error('Failed to load order address dropdowns', error);
            });
        });
    }
    
    if (editAddressForm && editAddressModal) {
        editAddressForm.addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const submitBtn = document.getElementById('saveAddressBtn');
            const spinner = submitBtn.querySelector('.spinner-border');
            const btnText = submitBtn.querySelector('.btn-text');
            const errorDiv = document.getElementById('addressEditError');
            
            // Show loading state
            submitBtn.disabled = true;
            spinner.classList.remove('d-none');
            btnText.textContent = 'Updating...';
            errorDiv.style.display = 'none';

            const mobileDigits = formatMobileDigitsOnly(editMobileInput?.value || '');
            if (!/^[6-9]\d{9}$/.test(mobileDigits)) {
                errorDiv.textContent = 'Please enter a valid 10-digit Indian mobile number.';
                errorDiv.style.display = 'block';
                submitBtn.disabled = false;
                spinner.classList.add('d-none');
                btnText.textContent = 'Update Address';
                return;
            }

            if (!AddressLocation.validateCityField(editAddressForm)) {
                submitBtn.disabled = false;
                spinner.classList.add('d-none');
                btnText.textContent = 'Update Address';
                return;
            }
            
            try {
                AddressLocation.prepareCityForSubmit(editAddressForm);
                const formData = new FormData(editAddressForm);
                const orderId = "<?php echo e($order->id); ?>";
                
                const response = await fetch(`/admin/orders/${orderId}/address`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                        'Accept': 'application/json',
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    body: JSON.stringify({
                        name: formData.get('name'),
                        mobile: formatMobileForStorage(formData.get('mobile')),
                        line1: formData.get('line1'),
                        line2: formData.get('line2'),
                        country_id: formData.get('country_id'),
                        state_id: formData.get('state_id'),
                        city_id: formData.get('city_id'),
                        city_custom: formData.get('city_custom'),
                        pin: formData.get('pin'),
                    })
                });
                
                const data = await response.json();
                
                if (response.ok && data.success) {
                    // Update the displayed address
                    const addr = data.address;
                    document.getElementById('addr-name').textContent = addr.name || 'N/A';
                    document.getElementById('addr-mobile').textContent = formatMobileForDisplay(addr.mobile);
                    
                    // Update full address
                    let fullAddr = addr.line1 || '';
                    if (addr.line2) {
                        fullAddr += '<br>' + addr.line2;
                    }
                    fullAddr += '<br>' + [addr.city, addr.state, addr.pin].filter(Boolean).join(', ');
                    document.getElementById('addr-full').innerHTML = fullAddr;
                    
                    // Close modal
                    const modal = bootstrap.Modal.getInstance(editAddressModal);
                    if (modal) {
                        modal.hide();
                    }
                    
                    // Show success message
                    alert('Shipping address updated successfully!');
                } else {
                    // Show error
                    errorDiv.textContent = data.message || 'Failed to update address. Please try again.';
                    errorDiv.style.display = 'block';
                }
            } catch (error) {
                console.error('Error updating address:', error);
                errorDiv.textContent = 'An error occurred while updating the address. Please try again.';
                errorDiv.style.display = 'block';
            } finally {
                AddressLocation.restoreCityFieldsAfterSubmit(editAddressForm);
                submitBtn.disabled = false;
                spinner.classList.add('d-none');
                btnText.textContent = 'Update Address';
            }
        });
        
        editAddressModal.addEventListener('hidden.bs.modal', function() {
            const errorDiv = document.getElementById('addressEditError');
            if (errorDiv) {
                errorDiv.style.display = 'none';
            }
        });
    }
});
</script>
<?php $__env->stopPush(); ?>

<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.admin', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /var/www/html/sudheerkt_uat/resources/views/admin/orders/show.blade.php ENDPATH**/ ?>