@extends('layouts.admin-simple')

@section('title', 'Edit Direct Delivery')

@section('styles')
<style>
.section-header {
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border-left: 4px solid #007bff;
    padding: 1rem;
    margin-bottom: 1.5rem;
    border-radius: 0.5rem;
}

.form-section {
    background: #fff;
    border: 1px solid #dee2e6;
    border-radius: 0.5rem;
    margin-bottom: 2rem;
    overflow: hidden;
}

.form-section-header {
    background: #f8f9fa;
    padding: 1rem 1.25rem;
    border-bottom: 1px solid #dee2e6;
    font-weight: 600;
    color: #495057;
}

.form-section-body {
    padding: 1.5rem;
}

.quality-status {
    display: inline-block;
    padding: 0.25rem 0.5rem;
    border-radius: 0.375rem;
    font-size: 0.875rem;
    font-weight: 500;
}

.quality-pending { background-color: #fef3cd; color: #664d03; }
.quality-passed { background-color: #d1ecf1; color: #055160; }
.quality-failed { background-color: #f8d7da; color: #721c24; }
.quality-conditional { background-color: #fff3cd; color: #856404; }

/* Improved table styling with larger fonts */
#delivery_items_table .form-control-sm {
    font-size: 0.85rem;
    padding: 0.375rem 0.75rem;
}

/* Protected fields styling for business logic */
.protected-field {
    background-color: #f8f9fa !important;
    color: #6c757d !important;
    border: 2px solid #e9ecef;
}

.protected-field:hover {
    border-color: #ffc107;
    box-shadow: 0 0 0 0.2rem rgba(255, 193, 7, 0.25);
}

#delivery_items_table .item-select {
    font-size: 0.8rem !important;
}

#delivery_items_table th {
    font-size: 0.9rem;
    font-weight: 600;
    padding: 0.75rem 0.5rem;
}

#delivery_items_table td {
    padding: 0.75rem 0.5rem;
    vertical-align: middle;
}

#delivery_items_table .btn-sm {
    font-size: 0.8rem;
    padding: 0.375rem 0.75rem;
}
</style>
@endsection

@section('content')
<div class="container-fluid px-4">
    <!-- Header -->
    <div class="section-header">
        <div class="d-flex justify-content-between align-items-center">
            <div>
                <h1 class="h3 mb-2 text-gray-800">
                    <i class="material-icons align-middle mr-2">local_shipping</i>
                    Edit Direct Delivery
                </h1>
                <p class="text-muted mb-0">Update direct delivery details and manage delivery items</p>
                <small class="text-info">Delivery Number: {{ $directDelivery->delivery_number }}</small>
            </div>
            <div>
                <a href="{{ route('warehouse.direct-deliveries.index') }}" class="btn btn-secondary">
                    <i class="material-icons mr-1">arrow_back</i>
                    Back to List
                </a>
            </div>
        </div>
    </div>

    <form action="{{ route('warehouse.direct-deliveries.update', $directDelivery->id) }}" method="POST" id="supplierDeliveryForm">
        @csrf
        @method('PUT')

        <!-- Basic Information -->
        <div class="form-section">
            <div class="form-section-header" style="display: none;">
                <i class="material-icons align-middle mr-2">info</i>
                Basic Delivery Information
            </div>
            <div class="form-section-body">
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label for="delivery_date" class="form-label">Delivery Date <span class="text-danger">*</span></label>
                        <input type="date"
                               class="form-control @error('delivery_date') is-invalid @enderror"
                               id="delivery_date"
                               name="delivery_date"
                               value="{{ old('delivery_date', $directDelivery->delivery_date?->format('Y-m-d')) }}"
                               required>
                        @error('delivery_date')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>

                    <div class="col-md-6 mb-3">
                        @if($directDelivery->supplier_id)
                        <!-- Supplier is already selected, make it read-only -->
                        <label for="supplier_display" class="form-label">Supplier <span class="text-danger">*</span></label>
                        <input type="text"
                               class="form-control protected-field"
                               id="supplier_display"
                               value="{{ $directDelivery->supplier->name ?? 'Selected Supplier' }}"
                               readonly
                               title="Supplier cannot be changed after selection">
                        <!-- Hidden input to preserve supplier_id value -->
                        <input type="hidden" name="supplier_id" value="{{ $directDelivery->supplier_id }}">
                        <small class="text-muted">Supplier cannot be changed after selection</small>
                        @else
                        <!-- Supplier not selected yet, allow selection -->
                        <x-warehouse.select2-dropdown
                            name="supplier_id"
                            id="supplier_id"
                            label="Supplier *"
                            placeholder="Select Supplier"
                            :options="$suppliers->map(function($supplier) {
                                return ['value' => $supplier->id, 'text' => $supplier->name];
                            })"
                            :selected="old('supplier_id', $directDelivery->supplier_id)"
                            :required="true"
                        />
                        @endif
                        @error('supplier_id')
                            <div class="text-danger mt-1">{{ $message }}</div>
                        @enderror
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label for="project_id" class="form-label">Project <span class="text-danger">*</span></label>
                        <select class="form-control @error('project_id') is-invalid @enderror"
                                id="project_id"
                                disabled>
                            @foreach($projects as $project)
                                <option value="{{ $project->id }}" {{ old('project_id', $directDelivery->project_id) == $project->id ? 'selected' : '' }}>
                                    {{ $project->project_number }} - {{ $project->project_name }}
                                </option>
                            @endforeach
                        </select>
                        <!-- Hidden input to preserve project_id value since disabled fields are not submitted -->
                        <input type="hidden" name="project_id" value="{{ old('project_id', $directDelivery->project_id) }}">
                        @error('project_id')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                        <small class="text-muted">Project cannot be changed after creation</small>
                    </div>

                    <div class="col-md-6 mb-3">
                        <label for="lpo_number" class="form-label">LPO Number</label>
                        <input type="text"
                               class="form-control {{ $directDelivery->lpo_number ? 'protected-field' : '' }} @error('lpo_number') is-invalid @enderror"
                               id="lpo_number"
                               name="lpo_number"
                               value="{{ old('lpo_number', $directDelivery->lpo_number) }}"
                               @if($directDelivery->lpo_number)
                               readonly
                               title="LPO Number cannot be changed after entry"
                               @else
                               placeholder="Enter LPO Number"
                               @endif>
                        @if($directDelivery->lpo_number)
                        <small class="text-muted">LPO Number cannot be changed after entry</small>
                        @endif
                        @error('lpo_number')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
            </div>
        </div>


        <!-- Delivery Items -->
        <div class="card shadow">
            <div class="card-header">
                <h6 class="m-0 font-weight-bold text-primary">
                    <i class="material-icons align-middle mr-1">inventory_2</i>
                    Delivery Items
                </h6>
            </div>
            <div class="card-body">
                <!-- Flash Messages -->
                @if(session('success'))
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <i class="material-icons mr-2">check_circle</i>
                    {{ session('success') }}
                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                @endif

                @if(session('error'))
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="material-icons mr-2">error</i>
                    {{ session('error') }}
                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                @endif

                @if($errors->any())
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="material-icons mr-2">error</i>
                    <strong>Please fix the following errors:</strong>
                    <ul class="mb-0 mt-2">
                        @foreach($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                @endif

                <div class="table-responsive">
                    <table class="table table-hover" id="delivery_items_table">
                        <thead class="thead-light">
                            <tr>
                                <th style="width: 250px;">Item</th>
                                <th style="width: 80px;">Unit</th>
                                <th style="width: 100px;">Ordered</th>
                                <th style="width: 100px;">Deliverable</th>
                                <th style="width: 120px;">Unit Price (AED)</th>
                                <th style="width: 120px;">Total (AED)</th>
                                <th style="width: 80px;">Action</th>
                            </tr>
                        </thead>
                        <tbody id="itemsContainer">
                            @if($directDelivery->items && $directDelivery->items->count() > 0)
                                @foreach($directDelivery->items as $index => $item)
                                    <tr class="item-row">
                                        <td>
                                            <select class="form-control form-control-sm item-select" name="items[{{ $index }}][item_id]" onchange="updateItemUnit(this, {{ $index }})" required>
                                                <option value="">Select Item</option>
                                                @foreach($items as $itemOption)
                                                    <option value="{{ $itemOption->id }}"
                                                            data-unit="{{ $itemOption->unit_of_measure }}"
                                                            {{ $item->item_id == $itemOption->id ? 'selected' : '' }}>
                                                        {{ $itemOption->item_description }}
                                                    </option>
                                                @endforeach
                                            </select>
                                        </td>
                                        <td class="text-center">
                                            <input type="text" class="form-control form-control-sm text-center" name="items[{{ $index }}][unit]" id="unit_{{ $index }}" value="{{ $item->item->unit_of_measure ?? '' }}" readonly>
                                        </td>
                                        <td>
                                            <input type="number" class="form-control form-control-sm protected-field" name="items[{{ $index }}][ordered_quantity]" value="{{ $item->ordered_quantity }}" step="0.01" min="0" readonly required title="Ordered quantity cannot be modified">
                                        </td>
                                        <td>
                                            <input type="number" class="form-control form-control-sm calculation-input"
                                                   name="items[{{ $index }}][delivered_quantity]"
                                                   value="{{ $item->delivered_quantity }}"
                                                   step="0.01"
                                                   min="{{ $item->delivered_quantity > 0 ? $item->delivered_quantity : 0 }}"
                                                   max="{{ $item->ordered_quantity }}"
                                                   oninput="calculateItemTotal(this)"
                                                   onchange="calculateItemTotal(this)"
                                                   required
                                                   @if($item->delivered_quantity > 0)
                                                   title="Cannot decrease below already delivered quantity: {{ number_format($item->delivered_quantity, 2) }}"
                                                   @else
                                                   title="Enter quantity delivered (max: {{ number_format($item->ordered_quantity, 2) }})"
                                                   @endif>
                                        </td>
                                        <td>
                                            <input type="number"
                                                   class="form-control form-control-sm calculation-input {{ $item->delivered_quantity > 0 ? 'protected-field' : '' }}"
                                                   name="items[{{ $index }}][unit_price]"
                                                   value="{{ $item->unit_price }}"
                                                   step="0.01"
                                                   min="0"
                                                   oninput="calculateItemTotal(this)"
                                                   onchange="calculateItemTotal(this)"
                                                   required
                                                   @if($item->delivered_quantity > 0)
                                                   readonly
                                                   title="Unit price cannot be changed for partially delivered items"
                                                   @else
                                                   title="Enter unit price"
                                                   @endif>
                                        </td>
                                        <td>
                                            <input type="number" class="form-control form-control-sm" name="items[{{ $index }}][total_price]" id="total_{{ $index }}" value="{{ ($item->delivered_quantity ?? 0) * ($item->unit_price ?? 0) }}" step="0.01" readonly>
                                        </td>
                                        <td class="text-center">
                                            <button type="button" class="btn btn-sm btn-danger remove-item" title="Remove Item">
                                                <i class="material-icons">delete</i>
                                            </button>
                                        </td>
                                    </tr>
                                @endforeach
                            @endif
                        </tbody>
                    </table>
                </div>
                <div class="card-footer">
                    <div class="row">
                        <div class="col-md-6"></div>
                        <div class="col-md-6">
                            <div class="table-responsive">
                                <table class="table table-sm">
                                    <tr>
                                        <td class="text-right font-weight-bold">Sub Total:</td>
                                        <td class="text-right font-weight-bold text-primary" id="subtotal_display">AED 0.00</td>
                                    </tr>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Submit Buttons -->
        <div class="row">
            <div class="col-12">
                <div class="d-flex justify-content-between">
                    <a href="{{ route('warehouse.direct-deliveries.index') }}" class="btn btn-secondary">
                        <i class="material-icons mr-1">arrow_back</i>
                        Cancel
                    </a>
                    <div class="d-flex align-items-center">
                        <button type="button" id="forceCloseBtn" class="btn btn-warning mr-2" title="Set all ordered quantities equal to delivered quantities and mark as delivered">
                            <i class="material-icons mr-1">done_all</i>
                            Force Close
                        </button>
                        <button type="submit" name="action" value="save_draft" class="btn btn-info mr-2">
                            <i class="material-icons mr-1">save</i>
                            Save as Draft
                        </button>
                        <button type="submit" name="action" value="submit" class="btn btn-success mr-2">
                            <i class="material-icons mr-1">check</i>
                            Submit for Processing
                        </button>
                        <div id="forceCloseInfo" class="small text-muted ml-2" style="display: none;">
                            <i class="material-icons" style="font-size: 12px;">info</i>
                            <span id="forceCloseCount">0</span> items pending
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>
@endsection

@push('scripts')
<script>
console.log('🚀 Direct delivery edit script is loading...');

// Global calculation function - must be outside document.ready
function calculateItemTotal(input) {
    console.log('🎯 Direct calculation triggered');

    if (typeof $ === 'undefined') {
        console.error('jQuery not loaded');
        return;
    }

    const row = $(input).closest('tr');
    const deliveredInput = row.find('input[name*="delivered_quantity"]');
    const priceInput = row.find('input[name*="unit_price"]');
    const totalInput = row.find('input[name*="total_price"]');

    const delivered = parseFloat(deliveredInput.val()) || 0;
    const price = parseFloat(priceInput.val()) || 0;
    const total = delivered * price;

    console.log('💰 Calculation:', delivered, 'x', price, '=', total);
    totalInput.val(total.toFixed(2));

    // Call updateSubtotal if it exists
    if (typeof updateSubtotal === 'function') {
        updateSubtotal();
    } else {
        console.warn('updateSubtotal function not found');
    }
}

// Calculate and update subtotal - global function
function updateSubtotal() {
    let subtotal = 0;
    const totalInputs = document.querySelectorAll('input[name*="[total_price]"]');
    console.log('🧮 Found total inputs:', totalInputs.length);

    totalInputs.forEach((input, index) => {
        const value = parseFloat(input.value) || 0;
        console.log(`📋 Item ${index + 1}: ${value}`);
        subtotal += value;
    });

    console.log('💯 Subtotal calculated:', subtotal);
    const subtotalDisplay = document.getElementById('subtotal_display');
    if (subtotalDisplay) {
        subtotalDisplay.textContent = 'AED ' + subtotal.toFixed(2);
    }
}

// Also make it available on window object
window.calculateItemTotal = calculateItemTotal;
window.updateSubtotal = updateSubtotal;

console.log('✅ Functions defined:', {
    calculateItemTotal: typeof calculateItemTotal,
    updateSubtotal: typeof updateSubtotal,
    windowCalculateItemTotal: typeof window.calculateItemTotal,
    windowUpdateSubtotal: typeof window.updateSubtotal
});

$(document).ready(function() {
    let itemIndex = {{ $directDelivery->items ? $directDelivery->items->count() : 0 }};

    // Debug form existence
    console.log('🔍 Form exists:', $('#supplierDeliveryForm').length > 0);
    console.log('🔍 Form action:', $('#supplierDeliveryForm').attr('action'));
    console.log('🔍 Submit buttons:', $('button[type="submit"]').length);

    // Calculate initial subtotal and force close count
    setTimeout(function() {
        console.log('🔄 Recalculating initial totals...');
        // Recalculate each item total first
        $('#delivery_items_table input[name*="total_price"]').each(function() {
            const row = $(this).closest('tr');
            calculateItemTotal(row.find('input[name*="delivered_quantity"]')[0]);
        });
        updateSubtotal();
        updateForceCloseCount();
    }, 1000); // Increased delay to ensure DOM is ready

    // Add direct event listeners to existing inputs
    $('#delivery_items_table input[name*="delivered_quantity"], #delivery_items_table input[name*="unit_price"]').each(function() {
        $(this).on('input change blur keyup', function() {
            console.log('📊 Event triggered on:', $(this).attr('name'));
            calculateItemTotal(this);
        });
    });

    // Add Item
    $('#addItemBtn').click(function() {
        const itemRow = `
            <tr class="item-row">
                <td>
                    <select class="form-control form-control-sm item-select" name="items[${itemIndex}][item_id]" onchange="updateItemUnit(this, ${itemIndex})" required>
                        <option value="">Select Item</option>
                        @foreach($items as $item)
                            <option value="{{ $item->id }}" data-unit="{{ $item->unit_of_measure }}">{{ $item->item_description }}</option>
                        @endforeach
                    </select>
                </td>
                <td class="text-center">
                    <input type="text" class="form-control form-control-sm text-center" name="items[${itemIndex}][unit]" id="unit_${itemIndex}" readonly>
                </td>
                <td>
                    <input type="number" class="form-control form-control-sm" name="items[${itemIndex}][ordered_quantity]" step="0.01" min="0" required>
                </td>
                <td>
                    <input type="number" class="form-control form-control-sm calculation-input" name="items[${itemIndex}][delivered_quantity]" step="0.01" min="0" oninput="calculateItemTotal(this)" onchange="calculateItemTotal(this)" required>
                </td>
                <td>
                    <input type="number" class="form-control form-control-sm calculation-input" name="items[${itemIndex}][unit_price]" step="0.01" min="0" oninput="calculateItemTotal(this)" onchange="calculateItemTotal(this)" required>
                </td>
                <td>
                    <input type="number" class="form-control form-control-sm" name="items[${itemIndex}][total_price]" id="total_${itemIndex}" step="0.01" readonly>
                </td>
                <td class="text-center">
                    <button type="button" class="btn btn-sm btn-danger remove-item" title="Remove Item">
                        <i class="material-icons">delete</i>
                    </button>
                </td>
            </tr>
        `;
        $('#itemsContainer').append(itemRow);

        // Add event listeners to new inputs
        $('#itemsContainer tr:last-child .calculation-input').on('input change blur keyup', function() {
            console.log('📊 New input event triggered');
            calculateItemTotal(this);
        });

        itemIndex++;
    });

    // Remove Item
    $(document).on('click', '.remove-item', function() {
        $(this).closest('tr.item-row').remove();
        updateSubtotal();
    });

    // Fallback event delegation for dynamically added inputs
    $(document).on('input change blur keyup', '.calculation-input', function() {
        console.log('📊 Delegated event triggered');
        calculateItemTotal(this);
    });

    // Direct button click handlers for debugging
    $('button[name="action"]').click(function(e) {
        e.preventDefault(); // Prevent default to debug first

        const action = $(this).val();
        console.log('🔍 Button clicked - Action:', action);
        console.log('🔍 Button text:', $(this).text().trim());
        console.log('🔍 Form element:', $(this).closest('form')[0]);

        const form = $(this).closest('form');

        // Add the action as a hidden input to ensure it's submitted
        form.find('input[name="action"]').remove(); // Remove any existing action input
        form.append(`<input type="hidden" name="action" value="${action}">`);

        console.log('🔥 Added hidden action input and triggering form submission...');

        // Store for debugging
        form.data('clicked-action', action);

        // Manually trigger form submission
        form.trigger('submit');
    });

    // Form validation
    $('#supplierDeliveryForm').submit(function(e) {
        const itemRows = $('#itemsContainer .item-row').length;
        const clickedAction = $(this).data('clicked-action');
        console.log('🔍 Form submission check - Items found:', itemRows);
        console.log('🔍 Submit event triggered by:', e.originalEvent?.submitter);
        console.log('🔍 Clicked action stored:', clickedAction);
        console.log('🔍 Form action:', $(this).attr('action'));
        console.log('🔍 Form method:', $(this).attr('method'));

        // Debug form data
        const formData = new FormData(this);
        console.log('📤 Form data being sent:');
        for (let [key, value] of formData.entries()) {
            console.log(`  ${key}: ${value}`);
        }

        if (itemRows === 0) {
            e.preventDefault();
            alert('Please add at least one item to the delivery.');
            return false;
        }

        console.log('✅ Form validation passed, submitting to server...');
        // Let the form submit naturally - don't prevent it
    });

    // Force Close functionality
    $('#forceCloseBtn').click(function() {
        // Show confirmation dialog
        const confirmMessage = 'This will set all ordered quantities equal to delivered quantities and mark the delivery as fully completed.\n\nThis action cannot be undone. Do you want to continue?';

        if (confirm(confirmMessage)) {
            let itemsUpdated = 0;

            // Update all ordered quantities to match delivered quantities
            $('#itemsContainer .item-row').each(function() {
                const $row = $(this);
                const $orderedInput = $row.find('input[name*="[ordered_quantity]"]');
                const $deliveredInput = $row.find('input[name*="[delivered_quantity]"]');

                if ($orderedInput.length && $deliveredInput.length) {
                    const orderedQty = parseFloat($orderedInput.val()) || 0;
                    const currentDelivered = parseFloat($deliveredInput.val()) || 0;

                    if (orderedQty > currentDelivered) {
                        $orderedInput.val(currentDelivered);
                        calculateItemTotal($deliveredInput[0]);
                        itemsUpdated++;
                    }
                }
            });

            // Update subtotal and force close count
            updateSubtotal();
            updateForceCloseCount();

            // Show feedback
            if (itemsUpdated > 0) {
                // Change button appearance to show action completed
                $('#forceCloseBtn').removeClass('btn-warning').addClass('btn-success')
                                  .html('<i class="material-icons mr-1">check_circle</i>Force Closed')
                                  .prop('disabled', true);

                // Auto-save after force close to update status to delivered
                console.log('🔥 Force close completed, auto-submitting form...');
                const form = $('#supplierDeliveryForm');

                // Add force close action
                form.find('input[name="action"]').remove();
                form.append('<input type="hidden" name="action" value="submit">');

                // Submit the form automatically
                form.submit();
            } else {
                alert('No items need to be force closed. All items are already fully delivered.');
            }
        }
    });
});

// Update item unit when item is selected
function updateItemUnit(selectElement, itemIndex) {
    const selectedOption = selectElement.options[selectElement.selectedIndex];
    const unit = selectedOption.getAttribute('data-unit') || '';
    const unitInput = document.getElementById(`unit_${itemIndex}`);

    if (unitInput) {
        unitInput.value = unit;
    }
}

// Calculate total price for an item
function calculateTotal(itemIndex) {
    const deliveredQtyInput = document.querySelector(`input[name="items[${itemIndex}][delivered_quantity]"]`);
    const unitPriceInput = document.querySelector(`input[name="items[${itemIndex}][unit_price]"]`);
    const totalPriceInput = document.getElementById(`total_${itemIndex}`);

    if (deliveredQtyInput && unitPriceInput && totalPriceInput) {
        const deliveredQty = parseFloat(deliveredQtyInput.value) || 0;
        const unitPrice = parseFloat(unitPriceInput.value) || 0;
        const total = deliveredQty * unitPrice;

        totalPriceInput.value = total.toFixed(2);

        // Update subtotal and force close count
        updateSubtotal();
        updateForceCloseCount();
    }
}

// Update Force Close count
function updateForceCloseCount() {
    let count = 0;

    $('#itemsContainer .item-row').each(function() {
        const $row = $(this);
        const $orderedInput = $row.find('input[name*="[ordered_quantity]"]');
        const $deliveredInput = $row.find('input[name*="[delivered_quantity]"]');

        if ($orderedInput.length && $deliveredInput.length) {
            const orderedQty = parseFloat($orderedInput.val()) || 0;
            const deliveredQty = parseFloat($deliveredInput.val()) || 0;

            if (orderedQty > deliveredQty) {
                count++;
            }
        }
    });

    $('#forceCloseCount').text(count);

    if (count > 0) {
        $('#forceCloseInfo').show();
        $('#forceCloseBtn').prop('disabled', false);
    } else {
        $('#forceCloseInfo').hide();
        if ($('#forceCloseBtn').text().trim().includes('Force Closed')) {
            // Already force closed, keep disabled
        } else {
            $('#forceCloseBtn').prop('disabled', true);
        }
    }
}

</script>
@endpush