@extends('layouts.admin-simple')

@section('title', 'Material Issue Decision - Multi-Source')

@push('styles')
<style>
    /* Floating Tracker Styles */
    #floating-tracker {
        width: 350px;
        animation: slideIn 0.3s ease-out;
    }

    #floating-tracker .card {
        margin: 0;
    }

    #floating-tracker .table {
        font-size: 11px;
    }

    #floating-tracker .table th {
        padding: 4px 6px;
        font-weight: 600;
    }

    #floating-tracker .table td {
        padding: 3px 6px;
    }

    @keyframes slideIn {
        from {
            transform: translateX(350px);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }

    .allocation-warning {
        margin: 0.5rem 0;
        animation: warningPulse 2s ease-in-out;
    }

    @keyframes warningPulse {
        0% { background-color: #f8d7da; }
        50% { background-color: #f5c6cb; }
        100% { background-color: #f8d7da; }
    }

    .quantity-input-wrapper {
        position: relative;
    }

    .quantity-input-warning {
        border: 2px solid #dc3545 !important;
        background-color: #f8d7da !important;
    }

    .allocation-summary {
        background: linear-gradient(135deg, #e3f2fd 0%, #f8f9fa 100%);
        border-left: 4px solid #2196f3;
    }

    /* Fix file input width and add visibility */
    .form-control-file {
        width: auto;
        max-width: 100%;
        display: inline-block;
        padding: 8px 12px;
        border: 1px dashed #ced4da;
        border-radius: 4px;
        background-color: #f8f9fa;
        cursor: pointer;
    }

    .form-control-file:hover {
        border-color: #80bdff;
        background-color: #e9ecef;
    }
</style>
@endpush

@section('breadcrumb')
    <li class="breadcrumb-item">Warehouse</li>
    <li class="breadcrumb-item"><a href="{{ route('warehouse.material-issue.index') }}">Material Issue</a></li>
    <li class="breadcrumb-item active">Material Issue</li>
@endsection

@section('page-title')
    <div class="d-flex justify-content-between align-items-center w-100">
        <div class="page-title-left">
            <h3 class="mb-1">Material Issue</h3>
            <p class="text-muted mb-0" style="font-size: 13px;">Issue material request from multiple sources</p>
        </div>
        <div class="page-actions-right">
            <a href="{{ route('warehouse.material-issue.index') }}" class="btn btn-outline-secondary">
                <i class="material-icons mr-1" style="font-size: 16px;">arrow_back</i>
                Back to List
            </a>
        </div>
    </div>
@endsection

@section('content')
<div class="container-fluid">
    @php
        $indirectRequest = $indirectRequest ?? null;
    @endphp

    <!-- Request Information -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h6 class="card-title mb-0">
                        <i class="material-icons mr-2">assignment</i>
                        Material Request Information
                    </h6>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-3">
                            <div class="info-item">
                                <label>Request Number</label>
                                <div class="text-primary font-weight-bold">
                                    {{ $transaction->material_request_number ?: 'MR-' . str_pad($transaction->id, 6, '0', STR_PAD_LEFT) }}
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="info-item">
                                <label>Request Date</label>
                                <div>{{ $transaction->transaction_date->format('d-M-Y') }}</div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="info-item">
                                <label>Project</label>
                                <div>{{ $transaction->project->project_name ?? 'N/A' }}</div>
                                @if($transaction->division)
                                    <small class="text-muted">{{ $transaction->division->division_name }}</small>
                                @endif
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="info-item">
                                <label>Requested By</label>
                                <div>{{ $transaction->requester->name ?? 'N/A' }}</div>
                            </div>
                        </div>
                    </div>

                    <div class="mt-4">
                        <div class="d-flex justify-content-end align-items-center mb-3">
                            <div>
                                <button type="button" class="btn btn-sm btn-outline-secondary mr-2" onclick="enableAllSources()">
                                    <i class="material-icons mr-1" style="font-size: 14px;">check_box</i>
                                    Enable All
                                </button>
                                <button type="button" class="btn btn-sm btn-outline-primary" onclick="autoAllocate()">
                                    <i class="material-icons mr-1" style="font-size: 14px;">auto_fix_high</i>
                                    Auto-Allocate
                                </button>
                            </div>
                        </div>

                        <!-- Allocation Summary Table -->
                        <div class="card mb-3">
                            <div class="card-header">
                                <h6 class="card-title mb-0">
                                    <i class="material-icons mr-2">assignment_turned_in</i>
                                    Direct Goods Allocation Summary
                                </h6>
                            </div>
                            <div class="card-body py-2">
                                <div class="table-responsive">
                                    <table class="table table-sm mb-0">
                                        <thead class="bg-light">
                                            <tr>
                                                <th>Item</th>
                                                <th width="80">Requested</th>
                                                <th width="80">Already Issued</th>
                                                <th width="80">Inventory</th>
                                                <th width="80">Delivery</th>
                                                <th width="80">Transfer</th>
                                                <th width="80">Total</th>
                                                <th width="80">Remaining</th>
                                                <th width="100">Status</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            @foreach($transaction->items as $item)
                                                @php
                                                    // Get fulfillment breakdown by type for this item (fixed to include all fulfillment types)
                                                    $fulfillments = \App\Models\Warehouse\OutgoingFulfillment::where('outgoing_transaction_id', $transaction->id)
                                                        ->where('item_id', $item->item_id)
                                                        ->get()
                                                        ->groupBy('fulfillment_type');

                                                    // Get fulfillment data directly to avoid groupBy issues
                                                    $allFulfillmentData = \App\Models\Warehouse\OutgoingFulfillment::where('outgoing_transaction_id', $transaction->id)
                                                        ->where('item_id', $item->item_id)
                                                        ->get();

                                                    // Calculate quantities directly from raw data
                                                    $inventoryQty = $allFulfillmentData->whereIn('fulfillment_type', ['inventory', 'inventory_dispatch'])->sum('quantity_fulfilled');
                                                    $deliveryQty = $allFulfillmentData->where('fulfillment_type', 'direct_delivery')->sum('quantity_fulfilled');
                                                    $transferQty = $allFulfillmentData->where('fulfillment_type', 'project_transfer')->sum('quantity_fulfilled');
                                                    $focQty = $allFulfillmentData->where('fulfillment_type', 'foc_transfer')->sum('quantity_fulfilled');
                                                    $totalIssued = $inventoryQty + $deliveryQty + $transferQty + $focQty;
                                                @endphp
                                                <tr id="summary_row_{{ $item->item_id }}">
                                                    <td>
                                                        <strong class="text-primary">{{ $item->item->item_code ?? 'N/A' }}</strong>
                                                        <br><small class="text-muted">{{ Str::limit($item->item->item_description ?? '', 40) }}</small>
                                                    </td>
                                                    <td class="text-center">
                                                        <strong>{{ number_format($item->quantity_requested, 0) }}</strong>
                                                    </td>
                                                    <td class="text-center">
                                                        @if($totalIssued > 0)
                                                            <span class="badge badge-success">{{ number_format($totalIssued, 0) }}</span>
                                                        @else
                                                            <span class="badge badge-light">0</span>
                                                        @endif
                                                    </td>
                                                    <td class="text-center">
                                                        @if($inventoryQty > 0)
                                                            <span id="summary_inv_{{ $item->item_id }}" class="badge badge-success">{{ number_format($inventoryQty, 0) }}</span>
                                                        @else
                                                            <span id="summary_inv_{{ $item->item_id }}" class="badge badge-light">0</span>
                                                        @endif
                                                    </td>
                                                    <td class="text-center">
                                                        @if($deliveryQty > 0)
                                                            <span id="summary_del_{{ $item->item_id }}" class="badge badge-info">{{ number_format($deliveryQty, 0) }}</span>
                                                        @else
                                                            <span id="summary_del_{{ $item->item_id }}" class="badge badge-light">0</span>
                                                        @endif
                                                    </td>
                                                    <td class="text-center">
                                                        @if($transferQty > 0)
                                                            <span id="summary_tra_{{ $item->item_id }}" class="badge badge-primary">{{ number_format($transferQty, 0) }}</span>
                                                        @else
                                                            <span id="summary_tra_{{ $item->item_id }}" class="badge badge-light">0</span>
                                                        @endif
                                                    </td>
                                                    <td class="text-center">
                                                        <strong id="summary_total_{{ $item->item_id }}">{{ number_format($totalIssued, 0) }}</strong>
                                                    </td>
                                                    <td class="text-center">
                                                        <span id="summary_remaining_{{ $item->item_id }}" class="text-danger">{{ number_format($item->quantity_remaining ?? $item->quantity_requested, 0) }}</span>
                                                    </td>
                                                    <td class="text-center">
                                                        @if(isset($item->quantity_remaining) && $item->quantity_remaining <= 0)
                                                            <span id="summary_status_{{ $item->item_id }}" class="badge badge-success">Fully Issued</span>
                                                        @elseif(isset($item->quantity_fulfilled) && $item->quantity_fulfilled > 0)
                                                            <span id="summary_status_{{ $item->item_id }}" class="badge badge-warning">Partially Issued</span>
                                                        @else
                                                            <span id="summary_status_{{ $item->item_id }}" class="badge badge-secondary">Pending</span>
                                                        @endif
                                                    </td>
                                                </tr>
                                            @endforeach
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>

                        @if($indirectRequest)
                            <div class="card mb-3">
                                <div class="card-header">
                                    <h6 class="card-title mb-0">
                                        <i class="material-icons mr-2">assignment_turned_in</i>
                                        Indirect Goods Allocation Summary
                                    </h6>
                                </div>
                                <div class="card-body py-2">
                                    <div class="table-responsive">
                                        <table class="table table-sm mb-0">
                                            <thead class="bg-light">
                                                <tr>
                                                    <th>Item</th>
                                                    <th width="90">Requested</th>
                                                    <th width="90">Already Issued</th>
                                                    <th width="90">To Issue</th>
                                                    <th width="90">Total</th>
                                                    <th width="90">Remaining</th>
                                                    <th width="110">Status</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                @foreach($indirectRequest->items as $item)
                                                    @php
                                                        $alreadyIssued = (float) $item->quantity_released;
                                                        $toIssue = max(0, (float) $item->quantity_balance);
                                                        $totalAfterIssue = $alreadyIssued + $toIssue;
                                                        $remainingAfterIssue = max(0, (float) $item->quantity_requested - $totalAfterIssue);
                                                    @endphp
                                                    <tr>
                                                        <td>
                                                            <strong class="text-warning">{{ $item->indirectGood->ig_code ?? 'N/A' }}</strong>
                                                            <br><small class="text-muted">{{ Str::limit($item->indirectGood->ig_description ?? '', 40) }}</small>
                                                        </td>
                                                        <td class="text-center">
                                                            <strong>{{ number_format($item->quantity_requested, 0) }}</strong>
                                                        </td>
                                                        <td class="text-center">
                                                            <span class="badge {{ $alreadyIssued > 0 ? 'badge-success' : 'badge-light' }}">
                                                                {{ number_format($alreadyIssued, 0) }}
                                                            </span>
                                                        </td>
                                                        <td class="text-center">
                                                            <span id="summary_indirect_to_issue_{{ $item->id }}" class="badge {{ $toIssue > 0 ? 'badge-warning' : 'badge-light' }}">
                                                                0
                                                            </span>
                                                        </td>
                                                        <td class="text-center">
                                                            <strong id="summary_indirect_total_{{ $item->id }}">{{ number_format($alreadyIssued, 0) }}</strong>
                                                        </td>
                                                        <td class="text-center">
                                                            <span id="summary_indirect_remaining_{{ $item->id }}" class="{{ $item->quantity_balance > 0 ? 'text-danger' : 'text-success' }}">
                                                                {{ number_format($item->quantity_balance, 0) }}
                                                            </span>
                                                        </td>
                                                        <td class="text-center">
                                                            @if($item->quantity_balance <= 0)
                                                                <span class="badge badge-success">Fully Issued</span>
                                                            @elseif($alreadyIssued > 0)
                                                                <span id="summary_indirect_status_{{ $item->id }}" class="badge badge-warning">Partially Issued</span>
                                                            @else
                                                                <span id="summary_indirect_status_{{ $item->id }}" class="badge badge-secondary">Pending</span>
                                                            @endif
                                                        </td>
                                                    </tr>
                                                @endforeach
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        @endif

                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Display Validation Errors -->
    @if ($errors->any())
        <div class="alert alert-danger">
            <ul class="mb-0">
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    <!-- Display Session Messages -->
    @if(session('error'))
        <div class="alert alert-danger">
            {{ session('error') }}
        </div>
    @endif

    @if(session('success'))
        <div class="alert alert-success">
            {{ session('success') }}
        </div>
    @endif

    @php
        // Calculate if all items are fully issued
        $allFullyIssued = $transaction->items->every(function($item) {
            return isset($item->quantity_remaining) && $item->quantity_remaining <= 0;
        });
        $indirectRequest = $indirectRequest ?? null;
        $indirectFullyIssued = !$indirectRequest || $indirectRequest->items->sum('quantity_balance') <= 0;
        $allFullyIssued = $allFullyIssued && $indirectFullyIssued;
    @endphp

    @if($allFullyIssued)
        <!-- Fully Issued Notice -->
        <div class="alert alert-success">
            <i class="material-icons align-middle mr-2">check_circle</i>
            <strong>Material Request Fully Issued:</strong> All requested items have been completely issued to the project. No further action required.
        </div>
    @else
        <!-- Multi-Source Material Issue Forms -->
        <form action="{{ route('warehouse.material-issue.process-multi', $transaction->id) }}" method="POST" id="multiSourceForm" enctype="multipart/form-data">
            @csrf
            <input type="hidden" name="multi_source" value="true">

        <!-- Hidden inputs for boolean fields -->
        <input type="hidden" name="enable_inventory" value="0" id="hidden_enable_inventory">
        <input type="hidden" name="enable_delivery" value="0" id="hidden_enable_delivery">
        <input type="hidden" name="enable_foc" value="0" id="hidden_enable_foc">

        <!-- Inventory Dispatch Section -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-header bg-light">
                        <h6 class="card-title mb-0">
                            <i class="material-icons mr-2">inventory</i>
                            Inventory Dispatch
                        </h6>
                    </div>
                    <div class="card-body">
                        <div class="form-check mb-3">
                            <input type="checkbox" class="form-check-input" id="enable_inventory" onchange="toggleSection('inventory')">
                            <label class="form-check-label" for="enable_inventory">
                                Enable Inventory Dispatch
                            </label>
                        </div>

                        <div id="inventory_section" style="display: none;">
                            <div class="form-group">
                                <label>Dispatch Date <span class="text-danger">*</span></label>
                                <input type="date" name="inventory_dispatch_date" class="form-control form-control-sm"
                                       value="{{ date('Y-m-d') }}" min="{{ date('Y-m-d') }}">
                            </div>

                            <div class="form-group">
                                <label>Receiver Name <span class="text-danger">*</span></label>
                                <input type="text" name="inventory_receiver_name" class="form-control form-control-sm">
                            </div>

                            <!-- Inventory Items List -->
                            <div class="form-group">
                                <label>Items for Inventory Dispatch</label>
                                <div class="table-responsive">
                                    <table class="table table-sm">
                                        <thead class="thead-light">
                                            <tr>
                                                <th>Item Code</th>
                                                <th width="90">Type</th>
                                                <th>Description</th>
                                                <th width="100">Requested</th>
                                                <th width="100">Available</th>
                                                <th width="150">Division</th>
                                                <th width="120">Dispatch Qty</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            @foreach($transaction->items as $item)
                                                @php
                                                    $availableStock = \App\Models\Warehouse\Inventory::where('item_id', $item->item_id)
                                                        ->where('quantity_available', '>', 0)
                                                        ->sum('quantity_available') ?: 0;
                                                @endphp
                                                <tr data-item-id="{{ $item->item_id }}">
                                                    <td>
                                                        <strong class="text-primary">{{ $item->item->item_code ?? 'N/A' }}</strong>
                                                    </td>
                                                    <td><span class="badge badge-primary">Direct</span></td>
                                                    <td>
                                                        <small>{{ $item->item->item_description ?? 'N/A' }}</small>
                                                    </td>
                                                    <td class="text-center">
                                                        <strong>{{ number_format($item->quantity_remaining ?? $item->quantity_requested, 0) }}</strong>
                                                        @if(isset($item->quantity_fulfilled) && $item->quantity_fulfilled > 0)
                                                            <br><small class="text-success">({{ number_format($item->quantity_fulfilled, 0) }} issued)</small>
                                                        @endif
                                                    </td>
                                                    <td class="text-center">
                                                        <span id="inventory_available_{{ $item->item_id }}" class="badge {{ $availableStock > 0 ? 'badge-success' : 'badge-danger' }}">
                                                            {{ number_format($availableStock, 0) }}
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <select name="inventory_division[{{ $item->item_id }}]"
                                                                class="form-control form-control-sm division-select inventory-division-select"
                                                                data-item-id="{{ $item->item_id }}"
                                                                onchange="updateDivisionStock({{ $item->item_id }})"
                                                                >
                                                            <option value="">Select Division</option>
                                                            @foreach($divisions ?? [] as $division)
                                                                <option value="{{ $division->id }}" data-division-name="{{ $division->division_name }}">
                                                                    {{ $division->division_name }} ({{ $division->division_code }})
                                                                </option>
                                                            @endforeach
                                                        </select>
                                                    </td>
                                                    <td>
                                                        <input type="number"
                                                               class="form-control form-control-sm inventory-qty"
                                                               name="inventory[{{ $item->item_id }}]"
                                                               data-item-id="{{ $item->item_id }}"
                                                               step="0.01" min="0"
                                                               max="{{ min($availableStock, $item->quantity_remaining ?? $item->quantity_requested) }}"
                                                               value="0"
                                                               onchange="updateAllocations({{ $item->item_id }})">
                                                    </td>
                                                </tr>
                                            @endforeach
                                            @if($indirectRequest && !$indirectFullyIssued)
                                                @foreach($indirectRequest->items as $indirectItem)
                                                    @php
                                                        $availableStock = \App\Models\Warehouse\IndirectGoods\IndirectGoodsInventory::where('indirect_good_id', $indirectItem->indirect_good_id)
                                                            ->where('quantity_available', '>', 0)
                                                            ->sum('quantity_available') ?: 0;
                                                    @endphp
                                                    <tr data-indirect-id="{{ $indirectItem->id }}">
                                                        <td><strong class="text-warning">{{ $indirectItem->indirectGood->ig_code ?? 'N/A' }}</strong></td>
                                                        <td><span class="badge badge-warning">Indirect</span></td>
                                                        <td><small>{{ $indirectItem->indirectGood->ig_description ?? 'N/A' }}</small></td>
                                                        <td class="text-center">
                                                            <strong>{{ number_format($indirectItem->quantity_balance, 0) }}</strong>
                                                            @if($indirectItem->quantity_released > 0)
                                                                <br><small class="text-success">({{ number_format($indirectItem->quantity_released, 0) }} issued)</small>
                                                            @endif
                                                        </td>
                                                        <td class="text-center">
                                                            <span id="indirect_available_inventory_{{ $indirectItem->id }}" class="badge {{ $availableStock > 0 ? 'badge-success' : 'badge-danger' }}">
                                                                {{ number_format($availableStock, 0) }}
                                                            </span>
                                                        </td>
                                                        <td>
                                                            <select name="inventory_indirect_division[{{ $indirectItem->id }}]"
                                                                    class="form-control form-control-sm division-select indirect-division-select inventory-indirect-division-select"
                                                                    data-indirect-id="{{ $indirectItem->id }}"
                                                                    data-indirect-good-id="{{ $indirectItem->indirect_good_id }}"
                                                                    onchange="updateIndirectDivisionStock({{ $indirectItem->id }}, 'inventory')">
                                                                <option value="">Select Division</option>
                                                                @foreach($divisions ?? [] as $division)
                                                                    <option value="{{ $division->id }}" data-division-name="{{ $division->division_name }}">
                                                                        {{ $division->division_name }} ({{ $division->division_code }})
                                                                    </option>
                                                                @endforeach
                                                            </select>
                                                        </td>
                                                        <td>
                                                            <input type="number"
                                                                   class="form-control form-control-sm inventory-qty indirect-qty inventory-indirect-qty"
                                                                   name="inventory_indirect[{{ $indirectItem->id }}]"
                                                                   data-indirect-id="{{ $indirectItem->id }}"
                                                                   data-indirect-good-id="{{ $indirectItem->indirect_good_id }}"
                                                                   data-already-issued="{{ $indirectItem->quantity_released }}"
                                                                   data-balance="{{ $indirectItem->quantity_balance }}"
                                                                   step="0.01" min="0"
                                                                   max="{{ min($availableStock, $indirectItem->quantity_balance) }}"
                                                                   value="0"
                                                                   onchange="updateIndirectAllocation({{ $indirectItem->id }})"
                                                                   oninput="updateIndirectAllocation({{ $indirectItem->id }})">
                                                        </td>
                                                    </tr>
                                                @endforeach
                                            @endif
                                        </tbody>
                                    </table>
                                </div>
                            </div>


                            <div class="form-group">
                                <label>Supporting Document</label>
                                <input type="file"
                                       name="inventory_file"
                                       class="form-control-file @error('inventory_file') is-invalid @enderror"
                                       accept=".pdf,.doc,.docx,.jpg,.jpeg,.png">
                                <small class="form-text text-muted">Upload supporting document (PDF, DOC, DOCX, JPG, PNG - Max: 10MB)</small>
                                @error('inventory_file')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>

                            <div class="form-group">
                                <label>Notes</label>
                                <textarea name="inventory_notes" class="form-control form-control-sm" rows="2"></textarea>
                            </div>

                            <div class="alert alert-success alert-sm">
                                <small>
                                    <i class="material-icons" style="font-size: 14px;">info</i>
                                    Items will be immediately deducted from warehouse stock
                                </small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Direct Delivery Section -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-header bg-light">
                        <h6 class="card-title mb-0">
                            <i class="material-icons mr-2">local_shipping</i>
                            Direct Delivery
                        </h6>
                    </div>
                    <div class="card-body">
                        <div class="form-check mb-3">
                            <input type="checkbox" class="form-check-input" id="enable_delivery" onchange="toggleSection('delivery')">
                            <label class="form-check-label" for="enable_delivery">
                                Enable Direct Delivery
                            </label>
                        </div>

                        <div id="delivery_section" style="display: none;">
                            <div class="form-group">
                                <label>Supplier <span class="text-danger">*</span></label>
                                <x-warehouse.select2-dropdown
                                    name="delivery_supplier_id"
                                    id="delivery_supplier_select"
                                    placeholder="Select Supplier"
                                    :options="collect([['value' => '', 'text' => 'Select Supplier']])->merge($suppliers->map(function($supplier) {
                                        return ['value' => $supplier->id, 'text' => $supplier->name];
                                    }))"
                                    allowClear="true"
                                    class="form-control-sm"
                                />
                            </div>


                            <div class="form-group">
                                <label>LPO Number</label>
                                <input type="text" name="delivery_lpo_number" class="form-control form-control-sm"
                                       placeholder="LPO-XXXXX">
                            </div>

                            <div class="form-group">
                                <label>Delivery Note Number <span class="text-danger">*</span></label>
                                <input type="text" name="delivery_note_number" class="form-control form-control-sm"
                                       placeholder="DN-XXXXX">
                            </div>

                            <!-- Direct Delivery Items List -->
                            <div class="form-group">
                                <label>Items for Direct Delivery</label>
                                <div class="table-responsive">
                                    <table class="table table-sm">
                                        <thead class="thead-light">
                                            <tr>
                                                <th>Item Code</th>
                                                <th width="90">Type</th>
                                                <th>Description</th>
                                                <th width="80">Requested</th>
                                                <th width="100">Order Qty</th>
                                                <th width="100">Unit Price</th>
                                                <th width="150">Division</th>
                                                <th width="120">Batch Number</th>
                                                <th width="120">Production Date</th>
                                                <th width="120">Expiry Date</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            @foreach($transaction->items as $item)
                                                <tr data-item-id="{{ $item->item_id }}">
                                                    <td>
                                                        <strong class="text-info">{{ $item->item->item_code ?? 'N/A' }}</strong>
                                                    </td>
                                                    <td><span class="badge badge-primary">Direct</span></td>
                                                    <td>
                                                        <small>{{ $item->item->item_description ?? 'N/A' }}</small>
                                                    </td>
                                                    <td class="text-center">
                                                        <strong>{{ number_format($item->quantity_remaining ?? $item->quantity_requested, 0) }}</strong>
                                                        @if(isset($item->quantity_fulfilled) && $item->quantity_fulfilled > 0)
                                                            <br><small class="text-success">({{ number_format($item->quantity_fulfilled, 0) }} issued)</small>
                                                        @endif
                                                    </td>
                                                    <td>
                                                        <input type="number"
                                                               class="form-control form-control-sm delivery-qty"
                                                               name="delivery[{{ $item->item_id }}]"
                                                               data-item-id="{{ $item->item_id }}"
                                                               step="0.01" min="0"
                                                               max="{{ $item->quantity_requested }}"
                                                               value="0"
                                                               onchange="updateAllocations({{ $item->item_id }})">
                                                    </td>
                                                    <td>
                                                        <input type="number"
                                                               class="form-control form-control-sm"
                                                               name="delivery_unit_price[{{ $item->item_id }}]"
                                                               step="0.01" min="0"
                                                               placeholder="0.00">
                                                    </td>
                                                    <td>
                                                        <select name="delivery_division[{{ $item->item_id }}]"
                                                                class="form-control form-control-sm division-select delivery-division-select"
                                                                data-item-id="{{ $item->item_id }}"
                                                                >
                                                            <option value="">Select Division</option>
                                                            @foreach($divisions ?? [] as $division)
                                                                <option value="{{ $division->id }}" data-division-name="{{ $division->division_name }}">
                                                                    {{ $division->division_name }} ({{ $division->division_code }})
                                                                </option>
                                                            @endforeach
                                                        </select>
                                                    </td>
                                                    <td>
                                                        <input type="text"
                                                               class="form-control form-control-sm"
                                                               name="delivery_batch[{{ $item->item_id }}]"
                                                               placeholder="BATCH-XXXX">
                                                    </td>
                                                    <td>
                                                        <input type="date"
                                                               class="form-control form-control-sm"
                                                               name="delivery_production_date[{{ $item->item_id }}]">
                                                    </td>
                                                    <td>
                                                        <input type="date"
                                                               class="form-control form-control-sm"
                                                               name="delivery_expiry_date[{{ $item->item_id }}]">
                                                    </td>
                                                </tr>
                                            @endforeach
                                            @if($indirectRequest && !$indirectFullyIssued)
                                                @foreach($indirectRequest->items as $indirectItem)
                                                    <tr data-indirect-id="{{ $indirectItem->id }}">
                                                        <td><strong class="text-warning">{{ $indirectItem->indirectGood->ig_code ?? 'N/A' }}</strong></td>
                                                        <td><span class="badge badge-warning">Indirect</span></td>
                                                        <td><small>{{ $indirectItem->indirectGood->ig_description ?? 'N/A' }}</small></td>
                                                        <td class="text-center">
                                                            <strong>{{ number_format($indirectItem->quantity_balance, 0) }}</strong>
                                                            @if($indirectItem->quantity_released > 0)
                                                                <br><small class="text-success">({{ number_format($indirectItem->quantity_released, 0) }} issued)</small>
                                                            @endif
                                                        </td>
                                                        <td>
                                                            <input type="number"
                                                                   class="form-control form-control-sm delivery-qty indirect-qty delivery-indirect-qty"
                                                                   name="delivery_indirect[{{ $indirectItem->id }}]"
                                                                   data-indirect-id="{{ $indirectItem->id }}"
                                                                   data-indirect-good-id="{{ $indirectItem->indirect_good_id }}"
                                                                   data-already-issued="{{ $indirectItem->quantity_released }}"
                                                                   data-balance="{{ $indirectItem->quantity_balance }}"
                                                                   step="0.01" min="0"
                                                                   max="{{ $indirectItem->quantity_balance }}"
                                                                   value="0"
                                                                   onchange="updateIndirectAllocation({{ $indirectItem->id }})"
                                                                   oninput="updateIndirectAllocation({{ $indirectItem->id }})">
                                                        </td>
                                                        <td><span class="text-muted small">N/A</span></td>
                                                        <td>
                                                            <select name="delivery_indirect_division[{{ $indirectItem->id }}]"
                                                                    class="form-control form-control-sm division-select indirect-division-select delivery-indirect-division-select"
                                                                    data-indirect-id="{{ $indirectItem->id }}"
                                                                    data-indirect-good-id="{{ $indirectItem->indirect_good_id }}">
                                                                <option value="">Select Division</option>
                                                                @foreach($divisions ?? [] as $division)
                                                                    <option value="{{ $division->id }}" data-division-name="{{ $division->division_name }}">
                                                                        {{ $division->division_name }} ({{ $division->division_code }})
                                                                    </option>
                                                                @endforeach
                                                            </select>
                                                        </td>
                                                        <td><span class="text-muted small">N/A</span></td>
                                                        <td><span class="text-muted small">N/A</span></td>
                                                        <td><span class="text-muted small">N/A</span></td>
                                                    </tr>
                                                @endforeach
                                            @endif
                                        </tbody>
                                    </table>
                                </div>
                            </div>

                            <div class="form-group">
                                <label>Delivery Site</label>
                                <input type="text" name="delivery_site_location" class="form-control form-control-sm"
                                       value="{{ $transaction->project->project_name ?? '' }}">
                            </div>

                            <div class="form-group">
                                <label>Supporting Document</label>
                                <input type="file"
                                       name="delivery_file"
                                       class="form-control-file @error('delivery_file') is-invalid @enderror"
                                       accept=".pdf,.doc,.docx,.jpg,.jpeg,.png">
                                <small class="form-text text-muted">Upload supporting document (PDF, DOC, DOCX, JPG, PNG - Max: 10MB)</small>
                                @error('delivery_file')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>

                            <div class="form-group">
                                <label>Notes</label>
                                <textarea name="delivery_notes" class="form-control form-control-sm" rows="2"></textarea>
                            </div>

                            <div class="alert alert-info alert-sm">
                                <small>
                                    <i class="material-icons" style="font-size: 14px;">info</i>
                                    Creates a direct delivery order for supplier
                                </small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>


        <!-- FOC Transfer Section -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-header bg-light d-flex justify-content-between align-items-center">
                        <h6 class="card-title mb-0">
                            <i class="material-icons mr-2">recycling</i>
                            FOC Transfer
                        </h6>
                        <button type="button" class="btn btn-sm btn-outline-secondary" onclick="loadFocQuantities()" title="Refresh FOC Quantities">
                            <i class="material-icons" style="font-size: 16px;">refresh</i>
                            <small>Refresh</small>
                        </button>
                    </div>
                    <div class="card-body">
                        <div class="form-check mb-3">
                            <input type="checkbox" class="form-check-input" id="enable_foc" onchange="toggleSection('foc')">
                            <label class="form-check-label" for="enable_foc">
                                Enable FOC Transfer
                            </label>
                            <small class="form-text text-muted">Transfer FOC (Free of Charge) items directly from FOC inventory</small>
                        </div>

                        <div id="foc_section" style="display: none;">
                            <div class="alert alert-info alert-sm mb-3">
                                <small>
                                    <i class="material-icons" style="font-size: 14px;">info</i>
                                    FOC items are dispatched directly from FOC inventory - no reference selection required
                                </small>
                            </div>

                            <!-- FOC Transfer Items List -->
                            <div class="form-group">
                                <label>Items for FOC Transfer</label>
                                <div class="table-responsive">
                                    <table class="table table-sm">
                                        <thead class="thead-light">
                                            <tr>
                                                <th>Item Code</th>
                                                <th width="90">Type</th>
                                                <th>Description</th>
                                                <th width="100">Requested</th>
                                                <th width="160">Division</th>
                                                <th width="100">Available</th>
                                                <th width="120">Transfer Qty</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            @foreach($transaction->items as $item)
                                                <tr data-item-id="{{ $item->item_id }}">
                                                    <td>
                                                        <strong class="text-primary">{{ $item->item->item_code ?? 'N/A' }}</strong>
                                                    </td>
                                                    <td><span class="badge badge-primary">Direct</span></td>
                                                    <td>
                                                        <small>{{ $item->item->item_description ?? 'N/A' }}</small>
                                                    </td>
                                                    <td class="text-center">
                                                        <strong>{{ number_format($item->quantity_remaining ?? $item->quantity_requested, 0) }}</strong>
                                                        @if(isset($item->quantity_fulfilled) && $item->quantity_fulfilled > 0)
                                                            <br><small class="text-success">({{ number_format($item->quantity_fulfilled, 0) }} issued)</small>
                                                        @endif
                                                    </td>
                                                    <td>
                                                        <select name="foc_division[{{ $item->item_id }}]"
                                                                class="form-control form-control-sm division-select foc-division-select"
                                                                data-item-id="{{ $item->item_id }}"
                                                                onchange="updateFocDivisionStock({{ $item->item_id }})">
                                                            <option value="">Select Division</option>
                                                            @foreach($focDivisions ?? [] as $division)
                                                                <option value="{{ $division->id }}" data-division-name="{{ $division->division_name }}">
                                                                    {{ $division->division_name }} ({{ $division->division_code }})
                                                                </option>
                                                            @endforeach
                                                        </select>
                                                    </td>
                                                    <td class="text-center">
                                                        @php
                                                            $focQty = $item->foc_available ?? 0;
                                                        @endphp
                                                        <span class="badge {{ $focQty > 0 ? 'badge-warning' : 'badge-danger' }}" id="foc_available_{{ $item->item_id }}" title="{{ $focQty > 0 ? 'FOC Inventory - Total Available: ' . $focQty . ' units (select division to filter)' : 'No FOC stock available' }}">{{ number_format($focQty, 0) }}</span>
                                                    </td>
                                                    <td>
                                                        <input type="number"
                                                               class="form-control form-control-sm foc-qty"
                                                               name="foc[{{ $item->item_id }}]"
                                                               data-item-id="{{ $item->item_id }}"
                                                               step="0.01" min="0"
                                                               max="{{ min($focQty, $item->quantity_remaining ?? $item->quantity_requested) }}"
                                                               value="0"
                                                               onchange="updateAllocations({{ $item->item_id }})">
                                                    </td>
                                                </tr>
                                            @endforeach
                                            @if($indirectRequest && !$indirectFullyIssued)
                                                @foreach($indirectRequest->items as $indirectItem)
                                                    @php
                                                        $availableStock = \App\Models\Warehouse\IndirectGoods\IndirectGoodsInventory::where('indirect_good_id', $indirectItem->indirect_good_id)
                                                            ->where('quantity_available', '>', 0)
                                                            ->sum('quantity_available') ?: 0;
                                                    @endphp
                                                    <tr data-indirect-id="{{ $indirectItem->id }}">
                                                        <td><strong class="text-warning">{{ $indirectItem->indirectGood->ig_code ?? 'N/A' }}</strong></td>
                                                        <td><span class="badge badge-warning">Indirect</span></td>
                                                        <td><small>{{ $indirectItem->indirectGood->ig_description ?? 'N/A' }}</small></td>
                                                        <td class="text-center">
                                                            <strong>{{ number_format($indirectItem->quantity_balance, 0) }}</strong>
                                                            @if($indirectItem->quantity_released > 0)
                                                                <br><small class="text-success">({{ number_format($indirectItem->quantity_released, 0) }} issued)</small>
                                                            @endif
                                                        </td>
                                                        <td>
                                                            <select name="foc_indirect_division[{{ $indirectItem->id }}]"
                                                                    class="form-control form-control-sm division-select indirect-division-select foc-indirect-division-select"
                                                                    data-indirect-id="{{ $indirectItem->id }}"
                                                                    data-indirect-good-id="{{ $indirectItem->indirect_good_id }}"
                                                                    onchange="updateIndirectDivisionStock({{ $indirectItem->id }}, 'foc')">
                                                                <option value="">Select Division</option>
                                                                @foreach($divisions ?? [] as $division)
                                                                    <option value="{{ $division->id }}" data-division-name="{{ $division->division_name }}">
                                                                        {{ $division->division_name }} ({{ $division->division_code }})
                                                                    </option>
                                                                @endforeach
                                                            </select>
                                                        </td>
                                                        <td class="text-center">
                                                            <span id="indirect_available_foc_{{ $indirectItem->id }}" class="badge {{ $availableStock > 0 ? 'badge-warning' : 'badge-danger' }}">
                                                                {{ number_format($availableStock, 0) }}
                                                            </span>
                                                        </td>
                                                        <td>
                                                            <input type="number"
                                                                   class="form-control form-control-sm foc-qty indirect-qty foc-indirect-qty"
                                                                   name="foc_indirect[{{ $indirectItem->id }}]"
                                                                   data-indirect-id="{{ $indirectItem->id }}"
                                                                   data-indirect-good-id="{{ $indirectItem->indirect_good_id }}"
                                                                   data-already-issued="{{ $indirectItem->quantity_released }}"
                                                                   data-balance="{{ $indirectItem->quantity_balance }}"
                                                                   step="0.01" min="0"
                                                                   max="{{ min($availableStock, $indirectItem->quantity_balance) }}"
                                                                   value="0"
                                                                   onchange="updateIndirectAllocation({{ $indirectItem->id }})"
                                                                   oninput="updateIndirectAllocation({{ $indirectItem->id }})">
                                                        </td>
                                                    </tr>
                                                @endforeach
                                            @endif
                                        </tbody>
                                    </table>
                                </div>
                            </div>

                            <div class="form-group">
                                <label>Transfer Date <span class="text-danger">*</span></label>
                                <input type="date" name="foc_transfer_date" class="form-control form-control-sm"
                                       value="{{ date('Y-m-d') }}">
                            </div>

                            <div class="form-group">
                                <label>Transfer Reason</label>
                                <input type="text" name="foc_transfer_reason" class="form-control form-control-sm"
                                       value="FOC material transfer for project requirement">
                            </div>

                            <div class="form-group">
                                <label>Notes</label>
                                <textarea name="foc_notes" class="form-control form-control-sm" rows="2" placeholder="Additional notes about FOC transfer..."></textarea>
                            </div>

                            <div class="alert alert-warning alert-sm">
                                <small>
                                    <i class="material-icons" style="font-size: 14px;">info</i>
                                    Transfers FOC (Free of Charge) damaged items for project use
                                </small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Summary and Actions -->
        <div class="card">
            <div class="card-header">
                <h6 class="card-title mb-0">
                    <i class="material-icons mr-2">summarize</i>
                    Issue Summary
                </h6>
            </div>
            <div class="card-body">
                @php
                    $totalRequested = 0;
                    $totalFulfilled = 0;
                    $totalRemaining = 0;
                    $totalInventory = 0;
                    $totalDelivery = 0;
                    $totalFoc = 0;

                    foreach($transaction->items as $item) {
                        $totalRequested += $item->quantity_requested;
                        $totalFulfilled += $item->quantity_fulfilled ?? 0;
                        $totalRemaining += $item->quantity_remaining ?? $item->quantity_requested;

                        // Get fulfillment data directly to avoid groupBy issues (same approach as above)
                        $itemFulfillments = \App\Models\Warehouse\OutgoingFulfillment::where('outgoing_transaction_id', $transaction->id)
                            ->where('item_id', $item->item_id)
                            ->get();

                        // Calculate totals using direct filtering
                        $totalInventory += $itemFulfillments->whereIn('fulfillment_type', ['inventory', 'inventory_dispatch'])->sum('quantity_fulfilled');
                        $totalDelivery += $itemFulfillments->where('fulfillment_type', 'direct_delivery')->sum('quantity_fulfilled');
                        $totalFoc += $itemFulfillments->where('fulfillment_type', 'foc_transfer')->sum('quantity_fulfilled');
                    }
                @endphp

                <div class="row mb-3">
                    <div class="col-md-3">
                        <div class="summary-item">
                            <label class="text-muted">Original Requested</label>
                            <h5 id="summary_original">{{ number_format($totalRequested, 2) }}</h5>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="summary-item">
                            <label class="text-warning">Already Issued</label>
                            <h5 id="summary_already_issued" class="text-warning">{{ number_format($totalFulfilled, 2) }}</h5>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="summary-item">
                            <label class="text-danger">Remaining to Issue</label>
                            <h5 id="summary_remaining_total" class="text-danger">{{ number_format($totalRemaining, 2) }}</h5>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="summary-item">
                            <label class="text-muted">Current Session</label>
                            <h5 id="summary_current_session" class="text-muted">0.00</h5>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-3">
                        <div class="summary-item">
                            <label class="text-success">Inventory</label>
                            <h5 id="summary_inventory" class="text-success">{{ number_format($totalInventory, 2) }}</h5>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="summary-item">
                            <label class="text-info">Delivery</label>
                            <h5 id="summary_delivery" class="text-info">{{ number_format($totalDelivery, 2) }}</h5>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="summary-item">
                            <label class="text-warning">FOC</label>
                            <h5 id="summary_foc" class="text-warning">{{ number_format($totalFoc, 2) }}</h5>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="summary-item">
                            <label class="text-dark">Total</label>
                            <h5 id="summary_total_allocated" class="text-dark">{{ number_format($totalFulfilled, 2) }}</h5>
                        </div>
                    </div>
                </div>

                <div class="alert alert-warning mt-3" id="warning_message" style="display: none;">
                    <i class="material-icons align-middle mr-1">warning</i>
                    <span id="warning_text"></span>
                </div>

                <div class="alert alert-success mt-3" id="success_message" style="display: none;">
                    <i class="material-icons align-middle mr-1">check_circle</i>
                    <span id="success_text">All items fully allocated!</span>
                </div>

                <hr>

                <div class="text-right">
                    <a href="{{ route('warehouse.material-issue.index') }}" class="btn btn-secondary mr-2">
                        <i class="material-icons mr-1" style="font-size: 16px;">cancel</i>
                        Cancel
                    </a>
                    <button type="submit" class="btn btn-success" id="submitBtn" disabled>
                        <i class="material-icons mr-1" style="font-size: 16px;">send</i>
                        Process Material Issue
                    </button>
                </div>
            </div>
        </div>
    </form>
    @endif

    <!-- Floating Tracker -->
    <div id="floating-tracker" style="position: fixed !important; top: 80px !important; right: 20px !important; z-index: 99999 !important; display: none; width: 350px !important;">
        <div class="card border-primary shadow">
            <div class="card-header bg-primary text-white py-2">
                <div class="d-flex justify-content-between align-items-center">
                    <h6 class="mb-0" style="font-size: 14px;">
                        <i class="material-icons mr-1" style="font-size: 16px; vertical-align: middle;">track_changes</i>
                        Quick Tracker
                    </h6>
                    <button type="button" class="btn btn-sm btn-outline-light" onclick="toggleFloatingTracker()" style="padding: 2px 6px;">
                        <i class="material-icons" style="font-size: 14px;">close</i>
                    </button>
                </div>
            </div>
            <div class="card-body py-2">
                <div id="floating-tracker-content">
                    <!-- Dynamic content will be added here -->
                </div>
            </div>
        </div>
    </div>
</div>
@endsection


@push('styles')
<style>
.info-item label {
    font-size: 12px;
    color: #6c757d;
    text-transform: uppercase;
    font-weight: 600;
    margin-bottom: 2px;
}

.summary-item label {
    font-size: 12px;
    text-transform: uppercase;
    font-weight: 600;
    margin-bottom: 2px;
}

.summary-item h5 {
    margin: 0;
    font-weight: bold;
}

.alert-sm {
    padding: 0.5rem 0.75rem;
    font-size: 0.875rem;
}

/* Subtle table styling */
.table th {
    border-top: none;
    font-weight: 600;
    color: #495057;
}

.form-control-sm {
    font-size: 0.875rem;
}

.reference-item {
    transition: border-color 0.3s ease;
}

.reference-item:hover {
    border-color: #007bff !important;
}

.inventory-items-list .item-row,
.delivery-items-list .item-row,
.transfer-items-list .item-row {
    background-color: #f8f9fa;
    transition: background-color 0.3s ease;
}

.inventory-items-list .item-row:hover {
    background-color: #e3f2e3;
}

.delivery-items-list .item-row:hover {
    background-color: #e3f2fd;
}

.transfer-items-list .item-row:hover {
    background-color: #e8f0fe;
}

#reference-panel {
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.progress {
    background-color: #e9ecef;
}

.progress-bar {
    transition: width 0.3s ease;
}

.allocation-status {
    font-size: 11px;
    font-weight: 600;
}


/* Summary row highlighting */
.summary-row-updated {
    background-color: #fff3cd !important;
    animation: fadeHighlight 1s ease-out;
}

@keyframes fadeHighlight {
    0% { background-color: #d4edda; }
    100% { background-color: #fff3cd; }
}

/* Custom Select2 styling for decision page */
.select2-container {
    width: 100% !important;
}

.select2-container .select2-selection--single {
    height: 31px !important; /* Match form-control-sm height */
    border: 1px solid #ced4da;
    border-radius: 0.25rem;
    font-size: 0.875rem;
}

.select2-container--default .select2-selection--single .select2-selection__rendered {
    line-height: 29px;
    padding-left: 8px;
    font-size: 0.875rem;
}

.select2-container--default .select2-selection--single .select2-selection__arrow {
    height: 29px;
    right: 8px;
}

.select2-dropdown {
    border-radius: 0.25rem;
    border: 1px solid #ced4da;
    font-size: 0.875rem;
    width: 100% !important; /* Fixed width instead of auto */
    min-width: 200px !important;
    max-width: 300px !important; /* Limit maximum width */
}

.select2-container--open .select2-dropdown--below {
    width: 100% !important;
    min-width: 200px !important;
    max-width: 300px !important;
}

.select2-search__field {
    border: 1px solid #ced4da !important;
    border-radius: 0.25rem;
    font-size: 0.875rem !important;
    padding: 4px 8px !important;
}

.select2-container--default .select2-results__option {
    padding: 6px 12px;
    font-size: 0.875rem;
}

.select2-container--default .select2-results__option--highlighted[aria-selected] {
    background-color: #007bff;
}

.select2-container--default .select2-results__option[aria-selected=true] {
    background-color: #e7f3ff;
    color: #495057;
}
</style>
@endpush

@push('scripts')
<script>
let itemData = {};
let projectInventoryData = {}; // Store project inventory data globally

// Initialize item data
@foreach($transaction->items as $item)
    itemData[{{ $item->item_id }}] = {
        requested: {{ $item->quantity_remaining ?? $item->quantity_requested }},
        inventory: 0,
        delivery: 0,
        transfer: 0
    };
@endforeach

function toggleSection(type) {
    const checkbox = document.getElementById('enable_' + type);
    const section = document.getElementById(type + '_section');
    const hiddenInput = document.getElementById('hidden_enable_' + type);

    if (checkbox.checked) {
        section.style.display = 'block';
        hiddenInput.value = '1';

        // Show floating tracker
        updateFloatingTracker();

        // Add required attribute to relevant fields when section is enabled
        if (type === 'inventory') {
            const receiverName = document.querySelector('input[name="inventory_receiver_name"]');
            const dispatchDate = document.querySelector('input[name="inventory_dispatch_date"]');
            if (receiverName) receiverName.setAttribute('required', 'required');
            if (dispatchDate) dispatchDate.setAttribute('required', 'required');

            // Make division fields required for inventory items with quantity
            const inventoryDivisionFields = document.querySelectorAll('.inventory-division-select');
            inventoryDivisionFields.forEach(field => {
                const itemId = field.getAttribute('data-item-id');
                const qtyInput = document.querySelector(`input[name="inventory[${itemId}]"]`);
                if (qtyInput && parseFloat(qtyInput.value) > 0) {
                    field.setAttribute('required', 'required');
                }
            });

            document.querySelectorAll('.inventory-indirect-division-select').forEach(field => {
                const itemId = field.getAttribute('data-indirect-id');
                const qtyInput = document.querySelector(`input[name="inventory_indirect[${itemId}]"]`);
                if (qtyInput && parseFloat(qtyInput.value) > 0) {
                    field.setAttribute('required', 'required');
                }
            });
        } else if (type === 'delivery') {
            const deliveryNote = document.querySelector('input[name="delivery_note_number"]');
            if (deliveryNote) deliveryNote.setAttribute('required', 'required');

            // Make division fields required for delivery items with quantity
            const deliveryDivisionFields = document.querySelectorAll('.delivery-division-select');
            deliveryDivisionFields.forEach(field => {
                const itemId = field.getAttribute('data-item-id');
                const qtyInput = document.querySelector(`input[name="delivery[${itemId}]"]`);
                if (qtyInput && parseFloat(qtyInput.value) > 0) {
                    field.setAttribute('required', 'required');
                }
            });

            document.querySelectorAll('.delivery-indirect-division-select').forEach(field => {
                const itemId = field.getAttribute('data-indirect-id');
                const qtyInput = document.querySelector(`input[name="delivery_indirect[${itemId}]"]`);
                if (qtyInput && parseFloat(qtyInput.value) > 0) {
                    field.setAttribute('required', 'required');
                }
            });

            // Make unit price fields required when direct delivery is enabled
            const unitPriceFields = document.querySelectorAll('input[name^="delivery_unit_price"]');
            unitPriceFields.forEach(field => {
                field.setAttribute('required', 'required');
                // Add visual indicator
                const label = field.closest('td')?.previousElementSibling?.previousElementSibling?.previousElementSibling?.previousElementSibling?.previousElementSibling;
                if (label && label.tagName === 'TH' && !label.innerHTML.includes('<span class="text-danger">')) {
                    // Find the Unit Price header and add required indicator
                    const header = document.querySelector('th:nth-child(5)'); // Unit Price column
                    if (header && !header.innerHTML.includes('*')) {
                        header.innerHTML = 'Unit Price <span class="text-danger">*</span>';
                    }
                }
            });
        } else if (type === 'foc') {
            const focDate = document.querySelector('input[name="foc_transfer_date"]');
            if (focDate) focDate.setAttribute('required', 'required');

            // Make division fields required for FOC items with quantity
            const focDivisionFields = document.querySelectorAll('.foc-division-select');
            focDivisionFields.forEach(field => {
                const itemId = field.getAttribute('data-item-id');
                const qtyInput = document.querySelector(`input[name="foc[${itemId}]"]`);
                if (qtyInput && parseFloat(qtyInput.value) > 0) {
                    field.setAttribute('required', 'required');
                }
            });

            document.querySelectorAll('.foc-indirect-division-select').forEach(field => {
                const itemId = field.getAttribute('data-indirect-id');
                const qtyInput = document.querySelector(`input[name="foc_indirect[${itemId}]"]`);
                if (qtyInput && parseFloat(qtyInput.value) > 0) {
                    field.setAttribute('required', 'required');
                }
            });

            // Load FOC quantities when enabling
            loadFocQuantities();
        }
    } else {
        section.style.display = 'none';
        hiddenInput.value = '0';

        // Update floating tracker
        updateFloatingTracker();

        // Remove required attribute when section is disabled
        if (type === 'inventory') {
            const receiverName = document.querySelector('input[name="inventory_receiver_name"]');
            const dispatchDate = document.querySelector('input[name="inventory_dispatch_date"]');
            if (receiverName) receiverName.removeAttribute('required');
            if (dispatchDate) dispatchDate.removeAttribute('required');

            // Remove required from all inventory division fields
            const inventoryDivisionFields = document.querySelectorAll('.inventory-division-select');
            inventoryDivisionFields.forEach(field => {
                field.removeAttribute('required');
            });
            document.querySelectorAll('.inventory-indirect-division-select').forEach(field => {
                field.removeAttribute('required');
            });
        } else if (type === 'delivery') {
            const deliveryNote = document.querySelector('input[name="delivery_note_number"]');
            if (deliveryNote) deliveryNote.removeAttribute('required');

            // Remove required from all delivery division fields
            const deliveryDivisionFields = document.querySelectorAll('.delivery-division-select');
            deliveryDivisionFields.forEach(field => {
                field.removeAttribute('required');
            });
            document.querySelectorAll('.delivery-indirect-division-select').forEach(field => {
                field.removeAttribute('required');
            });

            // Remove required attribute from unit price fields when direct delivery is disabled
            const unitPriceFields = document.querySelectorAll('input[name^="delivery_unit_price"]');
            unitPriceFields.forEach(field => {
                field.removeAttribute('required');
            });

            // Remove required indicator from header
            const header = document.querySelector('th:nth-child(5)'); // Unit Price column
            if (header && header.innerHTML.includes('*')) {
                header.innerHTML = 'Unit Price';
            }
        } else if (type === 'foc') {
            const focDate = document.querySelector('input[name="foc_transfer_date"]');
            if (focDate) focDate.removeAttribute('required');

            // Remove required from all FOC division fields
            const focDivisionFields = document.querySelectorAll('.foc-division-select');
            focDivisionFields.forEach(field => {
                field.removeAttribute('required');
            });
            document.querySelectorAll('.foc-indirect-division-select').forEach(field => {
                field.removeAttribute('required');
            });
        }

        // Reset quantities for this type
        document.querySelectorAll('.' + type + '-qty').forEach(input => {
            input.value = 0;
            if (input.dataset.itemId) {
                updateAllocations(input.dataset.itemId);
            } else if (input.dataset.indirectId) {
                updateIndirectAllocation(input.dataset.indirectId);
            }
        });
    }

    validateForm();
}

function updateAllocations(itemId) {
    console.log('🔄 updateAllocations called for item:', itemId);
    console.log('📞 Call stack:', new Error().stack);

    const inventoryInput = document.querySelector(`input[name="inventory[${itemId}]"]`);
    const deliveryInput = document.querySelector(`input[name="delivery[${itemId}]"]`);
    const focInput = document.querySelector(`input[name="foc[${itemId}]"]`);

    // Log input element existence and values
    console.log('🎯 Input elements:', {
        inventoryInput: !!inventoryInput,
        inventoryValue: inventoryInput ? inventoryInput.value : 'N/A',
        inventoryDisabled: inventoryInput ? inventoryInput.disabled : 'N/A',
        deliveryInput: !!deliveryInput,
        deliveryValue: deliveryInput ? deliveryInput.value : 'N/A',
        deliveryDisabled: deliveryInput ? deliveryInput.disabled : 'N/A',
        focInput: !!focInput,
        focValue: focInput ? focInput.value : 'N/A',
        focDisabled: focInput ? focInput.disabled : 'N/A'
    });

    const inventoryQty = inventoryInput ? parseFloat(inventoryInput.value) || 0 : 0;
    const deliveryQty = deliveryInput ? parseFloat(deliveryInput.value) || 0 : 0;
    const focQty = focInput ? parseFloat(focInput.value) || 0 : 0;

    // Get the remaining quantity for this item
    const remainingQty = itemData[itemId] ? itemData[itemId].requested : 0;
    const totalAllocated = inventoryQty + deliveryQty + focQty;

    console.log('Quantities for item', itemId, ':', {
        inventory: inventoryQty,
        delivery: deliveryQty,
        foc: focQty,
        total: totalAllocated,
        remaining: remainingQty,
        overAllocated: totalAllocated > remainingQty,
        exactDifference: (totalAllocated - remainingQty),
        withinTolerance: (totalAllocated <= remainingQty + 0.01)
    });

    // Validate allocation - show warning if over-allocated (with small tolerance for decimal precision)
    if (totalAllocated > remainingQty + 0.01) {
        const overAllocation = totalAllocated - remainingQty;
        showAllocationWarning(itemId, overAllocation, remainingQty);
    } else {
        clearAllocationWarning(itemId);
    }

    if (itemData[itemId]) {
        const requested = itemData[itemId].requested;
        const total = inventoryQty + deliveryQty + focQty;

        // Update item data
        itemData[itemId] = {
            requested: requested,
            inventory: inventoryQty,
            delivery: deliveryQty,
            foc: focQty
        };

        console.log('Updated itemData for', itemId, ':', itemData[itemId]);

        // Update reference panel for this item
        updateReferencePanel(itemId, inventoryQty, deliveryQty, focQty, requested);

        // Update summary
        updateSummary();
        validateForm();

        // Update floating tracker
        updateFloatingTracker();
    } else {
        console.error('itemData not found for itemId:', itemId);
    }

    // Update division required state based on quantity
    const inventoryEnabled = document.getElementById('enable_inventory')?.checked;
    const deliveryEnabled = document.getElementById('enable_delivery')?.checked;

    if (inventoryEnabled && inventoryInput) {
        const divisionField = document.querySelector(`.inventory-division-select[data-item-id="${itemId}"]`);
        if (divisionField) {
            if (parseFloat(inventoryInput.value) > 0) {
                divisionField.setAttribute('required', 'required');
            } else {
                divisionField.removeAttribute('required');
            }
        }
    }

    if (deliveryEnabled && deliveryInput) {
        const divisionField = document.querySelector(`.delivery-division-select[data-item-id="${itemId}"]`);
        if (divisionField) {
            if (parseFloat(deliveryInput.value) > 0) {
                divisionField.setAttribute('required', 'required');
            } else {
                divisionField.removeAttribute('required');
            }
        }
    }

    const focEnabled = document.getElementById('enable_foc')?.checked;
    if (focEnabled && focInput) {
        const divisionField = document.querySelector(`.foc-division-select[data-item-id="${itemId}"]`);
        if (divisionField) {
            if (parseFloat(focInput.value) > 0) {
                divisionField.setAttribute('required', 'required');
            } else {
                divisionField.removeAttribute('required');
            }
        }
    }
}

function updateReferencePanel(itemId, inventoryQty, deliveryQty, focQty, requested) {
    const total = inventoryQty + deliveryQty + focQty;
    const remaining = Math.max(0, requested - total);

    // Update summary table
    updateSummaryRow(itemId, inventoryQty, deliveryQty, focQty, total, remaining, requested);

}

function updateSummaryRow(itemId, inventoryQty, deliveryQty, focQty, total, remaining, requested) {
    console.log(`🔄 Updating summary for item ${itemId}:`, {
        inventoryQty, deliveryQty, focQty, total, remaining, requested,
        difference: Math.abs(total - requested),
        isComplete: Math.abs(total - requested) < 0.01
    });

    // Update allocation badges
    const invBadge = document.getElementById(`summary_inv_${itemId}`);
    const delBadge = document.getElementById(`summary_del_${itemId}`);
    const traBadge = document.getElementById(`summary_tra_${itemId}`);

    if (invBadge) {
        invBadge.textContent = inventoryQty > 0 ? Math.round(inventoryQty) : '0';
        invBadge.className = inventoryQty > 0 ? 'badge badge-success' : 'badge badge-light';
    }

    if (delBadge) {
        delBadge.textContent = deliveryQty > 0 ? Math.round(deliveryQty) : '0';
        delBadge.className = deliveryQty > 0 ? 'badge badge-info' : 'badge badge-light';
    }

    if (traBadge) {
        traBadge.textContent = focQty > 0 ? Math.round(focQty) : '0';
        traBadge.className = focQty > 0 ? 'badge badge-primary' : 'badge badge-light';
    }

    // Update total
    const totalElement = document.getElementById(`summary_total_${itemId}`);
    if (totalElement) {
        totalElement.textContent = Math.round(total);
        totalElement.className = total > 0 ? 'text-success font-weight-bold' : 'text-muted';
    }

    // Update remaining
    const remainingElement = document.getElementById(`summary_remaining_${itemId}`);
    if (remainingElement) {
        if (remaining > 0) {
            remainingElement.textContent = Math.round(remaining);
            remainingElement.className = 'text-danger font-weight-bold';
        } else if (total > requested) {
            remainingElement.textContent = '+' + Math.round(total - requested);
            remainingElement.className = 'text-warning font-weight-bold';
        } else {
            remainingElement.textContent = '0';
            remainingElement.className = 'text-success font-weight-bold';
        }
    }

    // Update status
    const statusElement = document.getElementById(`summary_status_${itemId}`);
    if (statusElement) {
        if (total === 0) {
            statusElement.textContent = 'Pending';
            statusElement.className = 'badge badge-secondary';
        } else if (Math.abs(total - requested) < 0.01) {
            statusElement.textContent = 'Complete';
            statusElement.className = 'badge badge-success';
        } else if (total < requested) {
            statusElement.textContent = 'Partial';
            statusElement.className = 'badge badge-warning';
        } else {
            statusElement.textContent = 'Excess';
            statusElement.className = 'badge badge-danger';
        }
    }

    // Highlight updated row
    const row = document.getElementById(`summary_row_${itemId}`);
    if (row) {
        row.classList.add('summary-row-updated');
        setTimeout(() => row.classList.remove('summary-row-updated'), 1000);
    }
}

function updateSummary() {
    let totalInventory = 0;
    let totalDelivery = 0;
    let totalFoc = 0;
    let totalRemainingToIssue = 0;

    for (let itemId in itemData) {
        totalInventory += itemData[itemId].inventory;
        totalDelivery += itemData[itemId].delivery;
        totalFoc += itemData[itemId].foc || 0;
        totalRemainingToIssue += itemData[itemId].requested; // This is the remaining quantity for each item
    }

    document.getElementById('summary_inventory').textContent = totalInventory.toFixed(2);
    document.getElementById('summary_delivery').textContent = totalDelivery.toFixed(2);
    document.getElementById('summary_foc').textContent = totalFoc.toFixed(2);

    const totalAllocated = totalInventory + totalDelivery + totalFoc;
    document.getElementById('summary_current_session').textContent = totalAllocated.toFixed(2);
    document.getElementById('summary_total_allocated').textContent = totalAllocated.toFixed(2);

    // Update the remaining total with the correct calculated value
    document.getElementById('summary_remaining_total').textContent = totalRemainingToIssue.toFixed(2);

    const stillRemaining = totalRemainingToIssue - totalAllocated;

    const warningEl = document.getElementById('warning_message');
    const successEl = document.getElementById('success_message');

    if (stillRemaining > 0.01) {
        warningEl.style.display = 'block';
        successEl.style.display = 'none';
        document.getElementById('warning_text').textContent = `${stillRemaining.toFixed(2)} units still need to be allocated`;
    } else if (totalAllocated > totalRemainingToIssue + 0.01) {
        warningEl.style.display = 'block';
        successEl.style.display = 'none';
        document.getElementById('warning_text').textContent = `Over-allocated by ${(totalAllocated - totalRemainingToIssue).toFixed(2)} units`;
    } else if (Math.abs(stillRemaining) < 0.01) {
        warningEl.style.display = 'none';
        successEl.style.display = 'block';
    } else {
        warningEl.style.display = 'none';
        successEl.style.display = 'none';
    }
}

function hasIndirectAllocations() {
    return Array.from(document.querySelectorAll('.indirect-qty')).some(input => (parseFloat(input.value) || 0) > 0);
}

function updateIndirectAllocation(itemId) {
    const inputs = Array.from(document.querySelectorAll(`.indirect-qty[data-indirect-id="${itemId}"]`));
    if (!inputs.length) return;

    const balance = parseFloat(inputs[0].dataset.balance) || 0;
    const alreadyIssued = parseFloat(inputs[0].dataset.alreadyIssued) || 0;
    let runningTotal = 0;

    inputs.forEach(input => {
        let quantity = parseFloat(input.value) || 0;
        const remainingForInput = Math.max(0, balance - runningTotal);
        const inputMax = parseFloat(input.getAttribute('max'));
        const maxForInput = Number.isFinite(inputMax) ? Math.min(remainingForInput, inputMax) : remainingForInput;

        if (quantity > maxForInput) {
            quantity = maxForInput;
            input.value = maxForInput;
        }

        runningTotal += quantity;

        const divisionField = document.querySelector(`.${input.classList.contains('inventory-indirect-qty') ? 'inventory' : (input.classList.contains('delivery-indirect-qty') ? 'delivery' : 'foc')}-indirect-division-select[data-indirect-id="${itemId}"]`);
        if (divisionField) {
            if (quantity > 0) {
                divisionField.setAttribute('required', 'required');
            } else {
                divisionField.removeAttribute('required');
            }
        }
    });

    const total = alreadyIssued + runningTotal;
    const remaining = Math.max(0, balance - runningTotal);

    const toIssueBadge = document.getElementById(`summary_indirect_to_issue_${itemId}`);
    if (toIssueBadge) {
        toIssueBadge.textContent = Math.round(runningTotal);
        toIssueBadge.className = runningTotal > 0 ? 'badge badge-warning' : 'badge badge-light';
    }

    const totalEl = document.getElementById(`summary_indirect_total_${itemId}`);
    if (totalEl) {
        totalEl.textContent = Math.round(total);
    }

    const remainingEl = document.getElementById(`summary_indirect_remaining_${itemId}`);
    if (remainingEl) {
        remainingEl.textContent = Math.round(remaining);
        remainingEl.className = remaining > 0 ? 'text-danger' : 'text-success';
    }

    const statusEl = document.getElementById(`summary_indirect_status_${itemId}`);
    if (statusEl) {
        if (remaining <= 0 && runningTotal > 0) {
            statusEl.textContent = 'Ready to Issue';
            statusEl.className = 'badge badge-info';
        } else if (runningTotal > 0) {
            statusEl.textContent = 'Partial';
            statusEl.className = 'badge badge-warning';
        } else {
            statusEl.textContent = alreadyIssued > 0 ? 'Partially Issued' : 'Pending';
            statusEl.className = alreadyIssued > 0 ? 'badge badge-warning' : 'badge badge-secondary';
        }
    }

    validateForm();
}

function validateForm() {
    const inventoryEnabled = document.getElementById('enable_inventory') ? document.getElementById('enable_inventory').checked : false;
    const deliveryEnabled = document.getElementById('enable_delivery') ? document.getElementById('enable_delivery').checked : false;
    const focEnabled = document.getElementById('enable_foc') ? document.getElementById('enable_foc').checked : false;

    // Check if sections are actually visible
    const inventorySection = document.getElementById('inventory_section');
    const deliverySection = document.getElementById('delivery_section');
    const focSection = document.getElementById('foc_section');

    console.log('🔍 Section visibility:', {
        inventoryEnabled: inventoryEnabled,
        inventoryVisible: inventorySection ? inventorySection.style.display !== 'none' : false,
        deliveryEnabled: deliveryEnabled,
        deliveryVisible: deliverySection ? deliverySection.style.display !== 'none' : false,
        focEnabled: focEnabled,
        focVisible: focSection ? focSection.style.display !== 'none' : false
    });

    // Check if at least one source is enabled
    const hasSource = inventoryEnabled || deliveryEnabled || focEnabled;

    // Check if there are any allocations
    let hasAllocations = hasIndirectAllocations();

    for (let itemId in itemData) {
        const total = itemData[itemId].inventory + itemData[itemId].delivery + (itemData[itemId].foc || 0);
        if (total > 0) {
            hasAllocations = true;
            break; // Found at least one allocation, no need to continue
        }
    }

    // Check required fields for enabled sections
    let requiredFieldsValid = true;
    let missingFields = [];

    if (inventoryEnabled) {
        const receiverName = document.querySelector('input[name="inventory_receiver_name"]');
        const dispatchDate = document.querySelector('input[name="inventory_dispatch_date"]');

        if (!receiverName || !receiverName.value.trim()) {
            requiredFieldsValid = false;
            missingFields.push('Inventory Receiver Name');
        }
        if (!dispatchDate || !dispatchDate.value.trim()) {
            requiredFieldsValid = false;
            missingFields.push('Inventory Dispatch Date');
        }
    }

    if (deliveryEnabled) {
        const deliveryNoteNumber = document.querySelector('input[name="delivery_note_number"]');
        const supplierSelect = document.querySelector('select[name="delivery_supplier_id"]');

        if (!supplierSelect || !supplierSelect.value.trim()) {
            requiredFieldsValid = false;
            missingFields.push('Delivery Supplier');
        }
        if (!deliveryNoteNumber || !deliveryNoteNumber.value.trim()) {
            requiredFieldsValid = false;
            missingFields.push('Delivery Note Number');
        }
    }

    if (focEnabled) {
        const focDate = document.querySelector('input[name="foc_transfer_date"]');

        if (!focDate || !focDate.value.trim()) {
            requiredFieldsValid = false;
            missingFields.push('FOC Transfer Date');
        }
    }

    const submitBtn = document.getElementById('submitBtn');
    if (submitBtn) {
        submitBtn.disabled = !hasSource || !hasAllocations || !requiredFieldsValid;

        // Enhanced debug logging
        console.log('🔍 Form validation debug:', {
            hasSource: hasSource,
            hasAllocations: hasAllocations,
            requiredFieldsValid: requiredFieldsValid,
            missingFields: missingFields,
            inventoryEnabled: inventoryEnabled,
            deliveryEnabled: deliveryEnabled,
            focEnabled: focEnabled,
            buttonDisabled: submitBtn.disabled,
            itemDataCount: Object.keys(itemData).length,
            submitButtonExists: !!submitBtn
        });

        // Log each item's allocation details with more info
        for (let itemId in itemData) {
            const data = itemData[itemId];
            const total = data.inventory + data.delivery + data.transfer + (data.foc || 0);
            const hasAnyAllocation = total > 0;

            // Get actual input values for verification
            const inventoryInput = document.querySelector(`input[name="inventory[${itemId}]"]`);
            const deliveryInput = document.querySelector(`input[name="delivery[${itemId}]"]`);
            const transferInput = document.querySelector(`input[name="transfer[${itemId}]"]`);
            const focInput = document.querySelector(`input[name="foc[${itemId}]"]`);

            const actualInventory = inventoryInput ? parseFloat(inventoryInput.value) || 0 : 0;
            const actualDelivery = deliveryInput ? parseFloat(deliveryInput.value) || 0 : 0;
            const actualTransfer = transferInput ? parseFloat(transferInput.value) || 0 : 0;
            const actualFoc = focInput ? parseFloat(focInput.value) || 0 : 0;

            console.log(`📊 Item ${itemId}:`, {
                requested: data.requested,
                storedData: { inventory: data.inventory, delivery: data.delivery, transfer: data.transfer, foc: data.foc || 0 },
                actualInputs: { inventory: actualInventory, delivery: actualDelivery, transfer: actualTransfer, foc: actualFoc },
                total: total,
                hasAllocation: hasAnyAllocation,
                inputsMatch: data.inventory === actualInventory && data.delivery === actualDelivery && data.transfer === actualTransfer && (data.foc || 0) === actualFoc
            });
        }

        // Check if button should be enabled
        const shouldBeEnabled = hasSource && hasAllocations;
        console.log(`🎯 Button state: Should be ${shouldBeEnabled ? 'ENABLED' : 'DISABLED'} - Currently ${submitBtn.disabled ? 'DISABLED' : 'ENABLED'}`);

        if (shouldBeEnabled && submitBtn.disabled) {
            console.log('⚠️  Button should be enabled but is disabled!');
        } else if (!shouldBeEnabled && !submitBtn.disabled) {
            console.log('⚠️  Button should be disabled but is enabled!');
        }
    }
}

function enableAllSources() {
    ['inventory', 'delivery', 'foc'].forEach(type => {
        const checkbox = document.getElementById('enable_' + type);
        if (checkbox && !checkbox.checked) {
            checkbox.checked = true;
            toggleSection(type);
        }
    });
}

// Auto-allocate function
function autoAllocate() {
    @foreach($transaction->items as $item)
        @php
            $availableStock = \App\Models\Warehouse\Inventory::where('item_id', $item->item_id)
                ->where('quantity_available', '>', 0)
                ->sum('quantity_available') ?: 0;
        @endphp

        const itemId{{ $item->item_id }} = {{ $item->item_id }};
        const requested{{ $item->item_id }} = {{ $item->quantity_requested }};
        const available{{ $item->item_id }} = {{ $availableStock }};

        // First, allocate from inventory if available
        const inventoryAlloc{{ $item->item_id }} = Math.min(requested{{ $item->item_id }}, available{{ $item->item_id }});
        if (inventoryAlloc{{ $item->item_id }} > 0 && document.getElementById('enable_inventory').checked) {
            document.querySelector(`input[name="inventory[${itemId{{ $item->item_id }}}]"]`).value = inventoryAlloc{{ $item->item_id }};
        }

        // Remaining goes to direct delivery or FOC
        const remaining{{ $item->item_id }} = requested{{ $item->item_id }} - inventoryAlloc{{ $item->item_id }};
        if (remaining{{ $item->item_id }} > 0) {
            if (document.getElementById('enable_delivery') && document.getElementById('enable_delivery').checked) {
                const deliveryInput = document.querySelector(`input[name="delivery[${itemId{{ $item->item_id }}}]"]`);
                if (deliveryInput) deliveryInput.value = remaining{{ $item->item_id }};
            } else if (document.getElementById('enable_foc') && document.getElementById('enable_foc').checked) {
                const focInput = document.querySelector(`input[name="foc[${itemId{{ $item->item_id }}}]"]`);
                if (focInput) focInput.value = remaining{{ $item->item_id }};
            }
        }

        updateAllocations(itemId{{ $item->item_id }});
    @endforeach
}

// Function to update item availability based on selected reference
function updateReferenceItemAvailability() {
    const referenceSelect = $('#transfer_reference_select');
    const selectedReference = referenceSelect.val();
    const projectId = $('#transfer_source_project_select').val();

    console.log('Selected reference:', selectedReference);

    if (!selectedReference || !projectId) {
        // Reset availability if no reference selected
        @foreach($transaction->items as $item)
            const resetElement{{ $item->item_id }} = document.getElementById('project_available_{{ $item->item_id }}');
            if (resetElement{{ $item->item_id }}) {
                resetElement{{ $item->item_id }}.textContent = 'Select reference first';
                resetElement{{ $item->item_id }}.className = 'badge badge-light';
            }
        @endforeach
        return;
    }

    // Parse reference type and ID
    const [refType, refId] = selectedReference.split('_');
    console.log('Reference type:', refType, 'ID:', refId);

    // Based on reference type, fetch specific item availability
    let fetchUrl = '';

    // First, show the stored project inventory while we fetch reference-specific data
    @foreach($transaction->items as $item)
        const tempElement{{ $item->item_id }} = document.getElementById('project_available_{{ $item->item_id }}');
        if (tempElement{{ $item->item_id }}) {
            const tempQty = projectInventoryData[{{ $item->item_id }}] || 0;
            tempElement{{ $item->item_id }}.textContent = `Loading...`;
            tempElement{{ $item->item_id }}.className = 'badge badge-secondary';
        }
    @endforeach

    switch(refType) {
        case 'MR':
            // Material Request - get remaining items from this request
            fetchUrl = `{{ url('/warehouse/transfer-requests/material-request') }}/${refId}/items`;
            break;
        case 'DD':
            // Direct Delivery - get items from this delivery
            fetchUrl = `{{ url('/warehouse/transfer-requests/direct-delivery') }}/${refId}/items`;
            break;
        case 'MT':
            // Material Transfer - get approved transfer items
            fetchUrl = `{{ url('/warehouse/transfer-requests/material-transfer') }}/${refId}`;
            break;
        default:
            console.error('Unknown reference type:', refType);
            // Fall back to project inventory
            @foreach($transaction->items as $item)
                const fallbackElement{{ $item->item_id }} = document.getElementById('project_available_{{ $item->item_id }}');
                if (fallbackElement{{ $item->item_id }}) {
                    const fallbackQty = projectInventoryData[{{ $item->item_id }}] || 0;
                    fallbackElement{{ $item->item_id }}.textContent = `Available: ${fallbackQty}`;
                    fallbackElement{{ $item->item_id }}.className = fallbackQty > 0 ? 'badge badge-success' : 'badge badge-danger';
                }
            @endforeach
            return;
    }

    // Fetch reference-specific items
    console.log('Fetching reference items from:', fetchUrl);
    fetch(fetchUrl)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            console.log('Reference items data:', data);

            // Handle different response structures for different reference types
            const items = data.items || (data.data && data.data.items) || [];
            if (data.success && items.length > 0) {
                // Update availability based on reference items
                @foreach($transaction->items as $item)
                    const refElement{{ $item->item_id }} = document.getElementById('project_available_{{ $item->item_id }}');
                    if (refElement{{ $item->item_id }}) {
                        const refItem = items.find(i => i.item_id == {{ $item->item_id }});
                        let availableQty = 0;

                        if (refItem) {
                            // Determine available quantity based on reference type
                            if (refType === 'MR') {
                                // For Material Request: use remaining quantity
                                availableQty = refItem.quantity_remaining || refItem.quantity_balance || 0;
                            } else if (refType === 'DD') {
                                // For Direct Delivery: use net available quantity (already calculated server-side)
                                availableQty = refItem.net_available_quantity || 0;
                            } else if (refType === 'MT') {
                                // For Material Transfer: use remaining transferable quantity
                                availableQty = refItem.remaining_transferable || 0;
                            }
                        }

                        refElement{{ $item->item_id }}.textContent = `Available: ${availableQty}`;

                        // Update badge color
                        if (availableQty >= {{ $item->quantity_remaining ?? $item->quantity_requested }}) {
                            refElement{{ $item->item_id }}.className = 'badge badge-success';
                        } else if (availableQty > 0) {
                            refElement{{ $item->item_id }}.className = 'badge badge-warning';
                        } else {
                            refElement{{ $item->item_id }}.className = 'badge badge-danger';
                        }

                        // Update max value for transfer quantity input
                        const transferInput = document.querySelector(`input[name="transfer[{{ $item->item_id }}]"]`);
                        if (transferInput) {
                            const remainingQty = {{ $item->quantity_remaining ?? $item->quantity_requested }};
                            transferInput.max = Math.min(availableQty, remainingQty);
                        }
                    }
                @endforeach
            } else {
                // Fall back to project inventory if no reference items
                console.log('No reference items found, using project inventory');
                @foreach($transaction->items as $item)
                    const noRefElement{{ $item->item_id }} = document.getElementById('project_available_{{ $item->item_id }}');
                    if (noRefElement{{ $item->item_id }}) {
                        const projQty = projectInventoryData[{{ $item->item_id }}] || 0;
                        noRefElement{{ $item->item_id }}.textContent = `Available: ${projQty}`;
                        noRefElement{{ $item->item_id }}.className = projQty > 0 ? 'badge badge-success' : 'badge badge-danger';
                    }
                @endforeach
            }
        })
        .catch(error => {
            console.error('Error fetching reference items:', error);
            // Fall back to project inventory on error
            @foreach($transaction->items as $item)
                const errorElement{{ $item->item_id }} = document.getElementById('project_available_{{ $item->item_id }}');
                if (errorElement{{ $item->item_id }}) {
                    const errorQty = projectInventoryData[{{ $item->item_id }}] || 0;
                    errorElement{{ $item->item_id }}.textContent = `Available: ${errorQty} (Project Stock)`;
                    errorElement{{ $item->item_id }}.className = errorQty > 0 ? 'badge badge-info' : 'badge badge-danger';
                }
            @endforeach
        });
}

// Function to update transfer references based on selected project
function updateTransferReferences() {
    console.log('updateTransferReferences called');
    validateForm(); // Validate form when source project changes
    const sourceProjectSelect = $('#transfer_source_project_select');
    const projectId = sourceProjectSelect.val();
    const referenceSection = document.getElementById('transfer_reference_section');
    const referenceSelect = $('#transfer_reference_select');

    console.log('Selected project ID:', projectId);

    if (!projectId) {
        referenceSection.style.display = 'none';
        // Clear and reset reference dropdown
        referenceSelect.empty().append('<option value="">Select Reference Number</option>');
        // Clear stored inventory data
        projectInventoryData = {};
        // Reset project availability indicators
        @foreach($transaction->items as $item)
            const availableElement{{ $item->item_id }} = document.getElementById('project_available_{{ $item->item_id }}');
            if (availableElement{{ $item->item_id }}) {
                availableElement{{ $item->item_id }}.textContent = 'Available: Select project first';
                availableElement{{ $item->item_id }}.className = 'badge badge-light';
            }
        @endforeach
        return;
    }

    // Show loading state
    referenceSelect.empty().append('<option value="">Loading references...</option>');
    referenceSection.style.display = 'block';

    // Fetch project references
    console.log('Fetching references for project:', projectId);
    fetch(`{{ url('/warehouse/transfer-requests/project') }}/${projectId}/combined-references`)
        .then(response => {
            console.log('Response status:', response.status);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            console.log('Received data:', data);
            // Clear and populate reference dropdown
            referenceSelect.empty();
            referenceSelect.append('<option value="">Select Reference Number</option>');

            if (data.success && data.data && data.data.length > 0) {
                data.data.forEach(ref => {
                    referenceSelect.append(`<option value="${ref.id}">${ref.text}</option>`);
                });
            } else {
                referenceSelect.append('<option value="" disabled>No recent references available</option>');
            }
        })
        .catch(error => {
            console.error('Error fetching project references:', error);
            referenceSelect.empty().append('<option value="" disabled>Error loading references</option>');
        });

    // Fetch project inventory
    fetch(`{{ url('/warehouse/transfer-requests/project') }}/${projectId}/inventory`)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            // Store inventory data globally
            if (data.success && data.data) {
                projectInventoryData = {};
                data.data.forEach(item => {
                    projectInventoryData[item.item_id] = item.quantity_available;
                });
                console.log('Stored project inventory data:', projectInventoryData);
            }

            // Update project inventory availability for each item
            @foreach($transaction->items as $item)
                const availableElement{{ $item->item_id }} = document.getElementById('project_available_{{ $item->item_id }}');
                if (availableElement{{ $item->item_id }}) {
                    const itemInventory = data.success && data.data ? data.data.find(inv => inv.item_id == {{ $item->item_id }}) : null;
                    const availableQty = itemInventory ? itemInventory.quantity_available : 0;

                    availableElement{{ $item->item_id }}.textContent = `Available: ${availableQty}`;
                    availableElement{{ $item->item_id }}.className = availableQty > 0 ? 'badge badge-success' : 'badge badge-danger';

                    // Update max value for transfer quantity input
                    const transferInput = document.querySelector(`input[name="transfer[{{ $item->item_id }}]"]`);
                    if (transferInput) {
                        const remainingQty = {{ $item->quantity_remaining ?? $item->quantity_requested }};
                        transferInput.max = Math.min(availableQty, remainingQty);
                    }
                }
            @endforeach
        })
        .catch(error => {
            console.error('Error fetching project data:', error);
            // Update availability indicators to show error
            @foreach($transaction->items as $item)
                const errorElement{{ $item->item_id }} = document.getElementById('project_available_{{ $item->item_id }}');
                if (errorElement{{ $item->item_id }}) {
                    errorElement{{ $item->item_id }}.textContent = 'Error loading availability';
                    errorElement{{ $item->item_id }}.className = 'badge badge-danger';
                }
            @endforeach
        });
}


// Show allocation warning for over-allocated items
function showAllocationWarning(itemId, overAllocation, remainingQty) {
    // Remove existing warning first
    clearAllocationWarning(itemId);

    // Find the item row in any of the tables
    const itemRow = document.querySelector(`[data-item-id="${itemId}"]`)?.closest('tr');
    if (!itemRow) return;

    // Highlight the input fields with warning styling
    const inputs = document.querySelectorAll(`[data-item-id="${itemId}"]`);
    inputs.forEach(input => {
        if (input.value && parseFloat(input.value) > 0) {
            input.classList.add('quantity-input-warning');
        }
    });

    // Create warning element
    const warningDiv = document.createElement('div');
    warningDiv.className = 'allocation-warning alert alert-danger mt-2 py-2 px-3';
    warningDiv.innerHTML = `
        <div class="d-flex align-items-center">
            <i class="material-icons text-danger mr-2" style="font-size: 18px;">warning</i>
            <div>
                <strong>⚠️ Over-Allocation Warning!</strong><br>
                <small>You've allocated <strong>${overAllocation}</strong> more than the remaining quantity of <strong>${remainingQty}</strong>.<br>
                Please reduce the quantities before submitting.</small>
            </div>
        </div>
    `;

    // Insert warning after the row
    itemRow.parentNode.insertBefore(warningDiv, itemRow.nextSibling);
}

// Clear allocation warning
function clearAllocationWarning(itemId) {
    const warnings = document.querySelectorAll('.allocation-warning');
    warnings.forEach(warning => {
        const row = warning.previousElementSibling;
        if (row && row.querySelector(`[data-item-id="${itemId}"]`)) {
            warning.remove();
        }
    });

    // Remove warning styling from input fields
    const inputs = document.querySelectorAll(`[data-item-id="${itemId}"]`);
    inputs.forEach(input => {
        input.classList.remove('quantity-input-warning');
    });
}

// Enhanced form validation to prevent over-allocation
function validateAllocation() {
    let hasErrors = false;
    const errors = [];

    console.log('=== VALIDATION DEBUG ===');

    for (let itemId in itemData) {
        const data = itemData[itemId];
        const total = data.inventory + data.delivery + data.transfer + (data.foc || 0);
        const remainingQty = data.requested; // This is the remaining quantity to be issued

        console.log(`Item ${itemId}:`, {
            inventory: data.inventory,
            delivery: data.delivery,
            transfer: data.transfer,
            totalAllocating: total,
            remainingToIssue: remainingQty,
            difference: total - remainingQty,
            isOverAllocated: total > remainingQty + 0.01
        });

        // Allow reasonable decimal tolerance (0.1) to account for rounding
        if (total > remainingQty + 0.1) {
            hasErrors = true;
            const overAllocation = (total - remainingQty).toFixed(2);
            errors.push(`Item ${itemId}: Over-allocated by ${overAllocation} units (Allocating: ${total}, Remaining to issue: ${remainingQty})`);
        } else if (total > 0 && total <= remainingQty + 0.1) {
            console.log(`✅ Item ${itemId} allocation is valid`);
        }
    }

    if (hasErrors) {
        alert('❌ Allocation Error!\n\nYou cannot allocate more than the required quantity:\n\n' + errors.join('\n\n') + '\n\nPlease adjust the quantities before submitting.');
        return false;
    }

    return true;
}

// Debug function to check form state
function debugFormState() {
    console.log('=== FORM DEBUG INFO ===');

    const inventoryEnabled = document.getElementById('enable_inventory').checked;
    const deliveryEnabled = document.getElementById('enable_delivery').checked;
    const transferEnabled = document.getElementById('enable_transfer').checked;
    const submitBtn = document.getElementById('submitBtn');

    console.log('Sections enabled:', {
        inventory: inventoryEnabled,
        delivery: deliveryEnabled,
        transfer: transferEnabled
    });

    console.log('Item data:', itemData);

    let hasAllocations = false;
    for (let itemId in itemData) {
        const total = itemData[itemId].inventory + itemData[itemId].delivery + (itemData[itemId].foc || 0);
        console.log(`Item ${itemId}:`, {
            requested: itemData[itemId].requested,
            inventory: itemData[itemId].inventory,
            delivery: itemData[itemId].delivery,
            transfer: itemData[itemId].transfer,
            total: total
        });
        if (total > 0) hasAllocations = true;
    }

    console.log('Has allocations:', hasAllocations);
    console.log('Submit button disabled:', submitBtn.disabled);

    // Check form fields
    if (inventoryEnabled) {
        const receiverName = document.querySelector('input[name="inventory_receiver_name"]');
        const dispatchDate = document.querySelector('input[name="inventory_dispatch_date"]');
        console.log('Inventory required fields:', {
            receiverName: receiverName ? receiverName.value : 'not found',
            dispatchDate: dispatchDate ? dispatchDate.value : 'not found'
        });
    }

    alert('Debug info logged to console. Press F12 to view.');
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    updateSummary();

    // Initialize reference panels for all items
    @foreach($transaction->items as $item)
        @if(isset($item->quantity_remaining) && $item->quantity_remaining <= 0)
            // Skip updating status for fully issued items - keep original HTML status
            console.log('Item {{ $item->item_id }} is fully issued, preserving original status');
        @else
            updateReferencePanel({{ $item->item_id }}, 0, 0, 0, {{ $item->quantity_remaining ?? $item->quantity_requested }});
        @endif
    @endforeach

    // PERMANENT FIX: Always load FOC quantities on page load
    console.log('🚀 Page loaded, fetching FOC quantities...');

    // SERVER-SIDE VALUES SHOULD BE CORRECT - Only load via AJAX if needed
    console.log('🖥️ Server-side FOC values should be displayed correctly');

    // Check if server-side values are already correct
    let serverSideValuesCorrect = true;
    const focBadges = document.querySelectorAll('[id^="foc_available_"]');
    focBadges.forEach(badge => {
        const itemId = badge.id.replace('foc_available_', '');
        const badgeText = badge.textContent.trim();
        console.log(`🔍 Server-side FOC for item ${itemId}: ${badgeText}`);

        // Only trigger AJAX reload if all badges show 0
        if (badgeText === '0' && badge.className.includes('badge-danger')) {
            // This item might need AJAX loading
        }
    });

    // Only use AJAX as backup if server-side values are incorrect
    const shouldLoadViaAjax = false; // Disable by default since server-side should work

    if (shouldLoadViaAjax) {
        console.log('📡 Loading FOC quantities via AJAX...');
        loadFocQuantities();
    }

    // Debug current state after 1 second
    setTimeout(function() {
        console.log('⏰ Checking FOC display state after page load');

        // Log all FOC badges
        const allBadges = document.querySelectorAll('[id^="foc_available_"]');
        allBadges.forEach(badge => {
            const itemId = badge.id.replace('foc_available_', '');
            console.log(`🔍 Final FOC state for item ${itemId}:`, {
                text: badge.textContent,
                className: badge.className,
                title: badge.title
            });
        });

        // Special debug for item 2109 (code 90090)
        const badge2109 = document.getElementById('foc_available_2109');
        if (badge2109) {
            console.log('🔍 DEBUG Item 2109 (90090) FOC Badge:', {
                text: badge2109.textContent,
                className: badge2109.className,
                title: badge2109.title
            });
        }
    }, 1000);

    // Add form submit debug handler
    const form = document.getElementById('multiSourceForm');
    if (form) {
        form.addEventListener('submit', function(e) {
            console.log('🚀 Form submission attempted');

            // First, validate allocation quantities
            const allocationValid = validateAllocation();
            console.log('Allocation validation result:', allocationValid);

            if (!allocationValid) {
                console.log('❌ Form submission blocked - allocation validation failed');
                e.preventDefault();
                return false; // This stops form submission
            }

            console.log('✅ Allocation validation passed, continuing with form submission...');

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

            // Check if any sections are enabled
            const inventoryEnabled = document.getElementById('enable_inventory') ? document.getElementById('enable_inventory').checked : false;
            const deliveryEnabled = document.getElementById('enable_delivery') ? document.getElementById('enable_delivery').checked : false;
            const focEnabled = document.getElementById('enable_foc') ? document.getElementById('enable_foc').checked : false;

            if (!inventoryEnabled && !deliveryEnabled && !focEnabled) {
                e.preventDefault();
                alert('Please enable at least one issue section before submitting.');
                return false;
            }

            // Check allocations
            let hasAllocations = hasIndirectAllocations();
            for (let itemId in itemData) {
                const total = itemData[itemId].inventory + itemData[itemId].delivery + (itemData[itemId].foc || 0);
                if (total > 0) {
                    hasAllocations = true;
                    break;
                }
            }

            if (!hasAllocations) {
                e.preventDefault();
                alert('Please allocate quantities for at least one item before submitting.');
                return false;
            }

            // Check required fields for inventory section
            if (inventoryEnabled) {
                const receiverName = document.querySelector('input[name="inventory_receiver_name"]');
                if (!receiverName || !receiverName.value.trim()) {
                    e.preventDefault();
                    alert('Please enter a receiver name for inventory dispatch.');
                    return false;
                }
            }

            // Show loading indicator
            const submitBtn = document.getElementById('submitBtn');
            if (submitBtn) {
                submitBtn.innerHTML = '<i class="material-icons mr-1" style="font-size: 16px;">hourglass_empty</i> Processing...';
                submitBtn.disabled = true;
            }

            console.log('Form validation passed, submitting...');
            return true;
        });
    }

    // Initialize Select2 event listeners after Select2 is loaded
    setTimeout(function() {
        if (typeof $ !== 'undefined') {
            // Reinitialize Select2 dropdowns with fixed width settings
            $('.select2-dropdown').each(function() {
                const $select = $(this);
                if ($select.data('select2')) {
                    $select.select2('destroy');
                }

                $select.select2({
                    placeholder: $select.attr('placeholder') || 'Please select...',
                    allowClear: true,
                    width: '100%',
                    dropdownAutoWidth: false, // Prevent auto-width
                    theme: 'default'
                });
            });

            // Initialize reference dropdown specifically
            if ($('#transfer_reference_select').length) {
                $('#transfer_reference_select').select2({
                    placeholder: 'Select Reference Number',
                    allowClear: true,
                    width: '100%',
                    dropdownAutoWidth: false,
                    theme: 'default'
                });

                // Add event listener for reference selection
                $('#transfer_reference_select').on('change', function() {
                    updateReferenceItemAvailability();
                    validateForm(); // Also validate form when reference changes
                });

                // Add event listener for supplier selection
                $('#delivery_supplier_select').on('change', function() {
                    validateForm(); // Validate form when supplier changes
                });
            }

            // Event listeners are handled by the Select2 component via onchange attribute
        }
    }, 500); // Wait for Select2 to initialize

    // Add real-time validation to quantity inputs
    document.querySelectorAll('.inventory-qty, .delivery-qty, .transfer-qty, .foc-qty').forEach(input => {
        input.addEventListener('input', function() {
            const itemId = this.dataset.itemId;
            if (itemId) {
                // Small delay to allow updateAllocations to process
                setTimeout(() => updateAllocations(itemId), 100);
            }
        });

        // Also validate on blur (when user leaves the field)
        input.addEventListener('blur', function() {
            const itemId = this.dataset.itemId;
            if (itemId) {
                updateAllocations(itemId);
            }
        });

        // Set max attribute to prevent typing more than remaining quantity
        const itemId = input.dataset.itemId;
        if (itemId && itemData[itemId]) {
            const remainingQty = itemData[itemId].requested;
            input.setAttribute('max', remainingQty);
        }
    });

    // Add real-time validation to required fields
    const requiredFields = [
        'input[name="inventory_receiver_name"]',
        'input[name="inventory_dispatch_date"]',
        'select[name="delivery_supplier_id"]',
        'input[name="delivery_note_number"]',
        'select[name="transfer_source_project_id"]',
        'select[name="transfer_reference_id"]',
        'input[name="transfer_date"]'
    ];

    requiredFields.forEach(selector => {
        const field = document.querySelector(selector);
        if (field) {
            field.addEventListener('input', validateForm);
            field.addEventListener('change', validateForm);
        }
    });

    // Initial validation
    validateForm();
});

/**
 * Load FOC references for dropdown
 */
function loadFocReferences() {
    const focReferenceSelect = document.getElementById('foc_reference_select');

    if (!focReferenceSelect) return;

    // Clear existing options
    $(focReferenceSelect).empty().append(new Option('Loading...', '', false, false));

    $.ajax({
        url: '{{ route("warehouse.material-issue.foc-references") }}',
        method: 'GET',
        success: function(response) {
            $(focReferenceSelect).empty();

            if (response.success && response.references.length > 0) {
                // Add default option
                $(focReferenceSelect).append(new Option('Select FOC Reference', '', false, false));

                // Add FOC references
                response.references.forEach(function(reference) {
                    $(focReferenceSelect).append(new Option(reference.text, reference.id, false, false));
                });

                // Initialize/reinitialize select2
                $(focReferenceSelect).select2({
                    theme: 'bootstrap4',
                    width: '100%',
                    allowClear: true,
                    placeholder: 'Select FOC Reference'
                });

                // Bind change event to load available items
                $(focReferenceSelect).off('change.foc').on('change.foc', function() {
                    const selectedRef = $(this).val();
                    if (selectedRef) {
                        loadFocItemsForReference(selectedRef);
                    } else {
                        clearFocAvailability();
                    }
                });
            } else {
                $(focReferenceSelect).append(new Option('No FOC references available', '', false, false));
                $(focReferenceSelect).prop('disabled', true);
            }
        },
        error: function(xhr, status, error) {
            console.error('Error loading FOC references:', error);
            $(focReferenceSelect).empty().append(new Option('Error loading references', '', false, false));
        }
    });
}

/**
 * Load FOC items for specific reference
 */
function loadFocItemsForReference(referenceId) {
    // Get item IDs from current transaction
    const itemIds = Object.keys(itemData);

    if (itemIds.length === 0) return;

    $.ajax({
        url: '{{ route("warehouse.material-issue.foc-items") }}',
        method: 'GET',
        data: {
            item_ids: itemIds,
            reference_id: referenceId
        },
        success: function(response) {
            if (response.success) {
                updateFocAvailability(response.data);
            } else {
                console.error('Error loading FOC items:', response.message);
                clearFocAvailability();
            }
        },
        error: function(xhr, status, error) {
            console.error('Error loading FOC items:', error);
            clearFocAvailability();
        }
    });
}

/**
 * Update FOC availability displays (not needed - now server-side)
 */
function updateFocAvailability(focData) {
    console.log('📦 FOC availability already loaded server-side');
}

/**
 * Clear FOC availability displays (not needed - now server-side)
 */
function clearFocAvailability() {
    console.log('📦 FOC availability already loaded server-side');
}

// Floating Tracker Functions
function updateFloatingTracker() {
    const inventoryEnabled = document.getElementById('enable_inventory')?.checked || false;
    const deliveryEnabled = document.getElementById('enable_delivery')?.checked || false;
    const focEnabled = document.getElementById('enable_foc')?.checked || false;

    const tracker = document.getElementById('floating-tracker');
    const trackerContent = document.getElementById('floating-tracker-content');

    // Show tracker if any source is enabled
    if (inventoryEnabled || deliveryEnabled || focEnabled) {
        tracker.style.display = 'block';

        // Build table-based tracker content
        let html = '<div class="table-responsive">';
        html += '<table class="table table-sm mb-0">';
        html += '<thead class="bg-light">';
        html += '<tr>';
        html += '<th style="font-size:11px;">Item</th>';
        html += '<th style="font-size:11px;" width="40">Inv</th>';
        html += '<th style="font-size:11px;" width="40">Del</th>';
        html += '<th style="font-size:11px;" width="40">FOC</th>';
        html += '<th style="font-size:11px;" width="40">Rem</th>';
        html += '</tr>';
        html += '</thead>';
        html += '<tbody>';

        // Add rows for each item
        @foreach($transaction->items as $item)
            const itemId{{ $item->item_id }} = {{ $item->item_id }};
            const itemCode{{ $item->item_id }} = '{{ $item->item->item_code ?? 'N/A' }}';
            const data{{ $item->item_id }} = itemData[itemId{{ $item->item_id }}];

            if (data{{ $item->item_id }}) {
                const inv = data{{ $item->item_id }}.inventory || 0;
                const del = data{{ $item->item_id }}.delivery || 0;
                const foc = data{{ $item->item_id }}.foc || 0;
                const total = inv + del + foc;
                const remaining = data{{ $item->item_id }}.requested - total;

                html += '<tr style="font-size: 11px;">';
                html += '<td><small class="text-primary font-weight-bold">' + itemCode{{ $item->item_id }} + '</small></td>';

                // Inventory column
                html += '<td class="text-center">';
                if (inv > 0) {
                    html += '<span class="text-success font-weight-bold">' + Math.round(inv) + '</span>';
                } else {
                    html += '-';
                }
                html += '</td>';

                // Delivery column
                html += '<td class="text-center">';
                if (del > 0) {
                    html += '<span class="text-info font-weight-bold">' + Math.round(del) + '</span>';
                } else {
                    html += '-';
                }
                html += '</td>';

                // FOC column
                html += '<td class="text-center">';
                if (foc > 0) {
                    html += '<span class="text-warning font-weight-bold">' + Math.round(foc) + '</span>';
                } else {
                    html += '-';
                }
                html += '</td>';

                // Remaining column
                html += '<td class="text-center">';
                if (remaining > 0) {
                    html += '<span class="text-danger font-weight-bold">' + Math.round(remaining) + '</span>';
                } else if (remaining < 0) {
                    html += '<span class="text-warning font-weight-bold">+' + Math.abs(Math.round(remaining)) + '</span>';
                } else {
                    html += '<span class="text-success">✓</span>';
                }
                html += '</td>';

                html += '</tr>';
            }
        @endforeach

        html += '</tbody>';
        html += '</table>';
        html += '</div>';

        trackerContent.innerHTML = html;
    } else {
        tracker.style.display = 'none';
    }
}

function toggleFloatingTracker() {
    const tracker = document.getElementById('floating-tracker');
    if (tracker.style.display === 'none') {
        updateFloatingTracker();
    } else {
        tracker.style.display = 'none';
    }
}

function hideFloatingTracker() {
    document.getElementById('floating-tracker').style.display = 'none';
}

/**
 * Load FOC quantities from API and update the display
 * PERMANENT FIX: Robust loading with multiple fallbacks
 */
function loadFocQuantities() {
    console.log('📦 Loading FOC quantities...');

    // Get all item IDs from the current transaction
    const itemIds = Object.keys(itemData);

    // Also check for any FOC badges on the page (backup method)
    const focBadges = document.querySelectorAll('[id^="foc_available_"]');
    const badgeItemIds = Array.from(focBadges).map(badge => {
        return badge.id.replace('foc_available_', '');
    });

    // Merge both sources of item IDs
    const allItemIds = [...new Set([...itemIds, ...badgeItemIds])];

    if (allItemIds.length === 0) {
        console.log('No items found to check FOC quantities');
        return;
    }

    // Use the merged list
    const itemIdsToCheck = allItemIds;

    // Show loading indicators for ALL items
    itemIdsToCheck.forEach(function(itemId) {
        const focBadge = document.getElementById(`foc_available_${itemId}`);
        if (focBadge) {
            focBadge.className = 'badge badge-secondary';
            focBadge.textContent = '...';
            focBadge.title = 'Loading FOC quantities...';
        }
    });

    // Make AJAX call to get FOC quantities
    $.ajax({
        url: '{{ route("warehouse.material-issue.foc-quantities") }}',
        method: 'GET',
        data: {
            item_ids: itemIdsToCheck  // Use the merged list
        },
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
            'X-Requested-With': 'XMLHttpRequest'
        },
        dataType: 'json',
        timeout: 10000, // 10 second timeout
        success: function(response) {
            console.log('✅ FOC quantities loaded:', response);

            if (response.success && response.data && Array.isArray(response.data)) {
                // Update each item's FOC display
                response.data.forEach(function(item) {
                    if (item.item_id && typeof item.total_available !== 'undefined') {
                        updateFocDisplay(item.item_id, item.total_available);
                    }
                });

                // Update any items not in the response to show 0
                itemIdsToCheck.forEach(function(itemId) {
                    const found = response.data.find(item => item.item_id == itemId);
                    if (!found) {
                        updateFocDisplay(itemId, 0);
                    }
                });
            } else {
                console.error('Invalid FOC quantities response:', response);
                // Set all to 0 on invalid response
                itemIdsToCheck.forEach(function(itemId) {
                    updateFocDisplay(itemId, 0);
                });
            }
        },
        error: function(xhr, status, error) {
            console.error('Error loading FOC quantities:', {
                status: status,
                error: error,
                response: xhr.responseText,
                url: '{{ route("warehouse.material-issue.foc-quantities") }}'
            });

            // ENHANCED FALLBACK: Since AJAX failed, let the model accessor handle it
            // The FOC badges will show the correct values from server-side rendering
            console.log('📡 AJAX failed, relying on server-side FOC values and model accessor');

            // Show user-friendly error
            if (xhr.status === 404) {
                console.warn('FOC quantities endpoint not found - FOC values from model accessor should be visible');
            } else if (xhr.status === 500) {
                console.error('Server error loading FOC quantities');
            } else if (status === 'timeout') {
                console.error('Request timeout loading FOC quantities');
            }
        }
    });
}

/**
 * Update FOC display for a specific item
 */
function updateFocDisplay(itemId, availableQuantity) {
    console.log(`📦 Updating FOC display for item ${itemId}: ${availableQuantity} units`);

    // Ensure quantity is a valid number
    const qty = parseFloat(availableQuantity) || 0;

    const focBadge = document.getElementById(`foc_available_${itemId}`);
    const focInput = document.querySelector(`input[name="foc[${itemId}]"]`);

    if (focBadge) {
        if (qty > 0) {
            focBadge.className = 'badge badge-warning';
            focBadge.textContent = qty.toFixed(0);
            focBadge.title = `FOC Inventory - Available: ${qty} units`;

            // Also update any data attributes for debugging
            focBadge.setAttribute('data-foc-quantity', qty);
            focBadge.setAttribute('data-last-updated', new Date().toISOString());
        } else {
            focBadge.className = 'badge badge-danger';
            focBadge.textContent = '0';
            focBadge.title = 'No FOC stock available';

            focBadge.setAttribute('data-foc-quantity', '0');
            focBadge.setAttribute('data-last-updated', new Date().toISOString());
        }
    } else {
        console.warn(`FOC badge not found for item ${itemId}`);
    }

    if (focInput) {
        // Update the max attribute of the input
        const requestedQty = itemData[itemId] ? itemData[itemId].requested : 0;
        const maxAllowed = Math.min(qty, requestedQty);
        focInput.setAttribute('max', maxAllowed);
        focInput.setAttribute('data-foc-available', qty);

        // Reset input value if it exceeds available quantity
        if (parseFloat(focInput.value) > qty) {
            focInput.value = Math.min(parseFloat(focInput.value), qty);
        }
    } else {
        console.log(`FOC input not found for item ${itemId} (may not be in FOC section)`);
    }
}

/**
 * Force refresh all FOC displays from server data
 */
function forceRefreshFocDisplays() {
    console.log('🔄 Force refreshing all FOC displays...');

    // Get all FOC badges on the page
    const focBadges = document.querySelectorAll('[id^="foc_available_"]');

    focBadges.forEach(badge => {
        const itemId = badge.id.replace('foc_available_', '');
        console.log(`Checking FOC for item ${itemId}`);

        // Mark as loading
        badge.className = 'badge badge-secondary';
        badge.textContent = '...';
    });

    // Load fresh data
    loadFocQuantities();
}

/**
 * Update available stock based on selected division for inventory dispatch
 */
function updateDivisionStock(itemId) {
    const divisionSelect = document.querySelector(`select[name="inventory_division[${itemId}]"]`);
    const divisionId = divisionSelect.value;
    const divisionName = divisionSelect.options[divisionSelect.selectedIndex].getAttribute('data-division-name');

    if (!divisionId) {
        // Reset available stock display using specific ID
        const stockBadge = document.getElementById(`inventory_available_${itemId}`);
        if (stockBadge) {
            stockBadge.textContent = '0';
            stockBadge.className = 'badge badge-danger';
            stockBadge.title = 'Select a division to see available stock';
        }

        // Update max quantity for input
        const qtyInput = document.querySelector(`input[name="inventory[${itemId}]"]`);
        if (qtyInput) {
            qtyInput.setAttribute('max', '0');
            qtyInput.value = '0';
        }
        return;
    }

    // Fetch division-specific stock via AJAX
    const url = `{{ url('/warehouse/inventory/division-stock') }}/${itemId}/${divisionId}`;
    console.log(`🔍 Fetching division stock from: ${url}`);

    fetch(url, {
        method: 'GET',
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'application/json'
        }
    })
        .then(response => {
            console.log(`📡 Division stock response status: ${response.status}`);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            console.log(`📊 Division stock data:`, data);
            const availableQty = data.available_quantity || 0;
            const stockBadge = document.getElementById(`inventory_available_${itemId}`);
            const qtyInput = document.querySelector(`input[name="inventory[${itemId}]"]`);

            if (stockBadge) {
                stockBadge.textContent = availableQty.toLocaleString();

                if (availableQty > 0) {
                    // Color coding based on stock type
                    if (data.breakdown && data.breakdown.division_specific > 0) {
                        stockBadge.className = 'badge badge-success'; // Green for division-specific stock
                    } else {
                        stockBadge.className = 'badge badge-info'; // Blue for unassigned stock
                    }

                    // Detailed tooltip with breakdown
                    let tooltipText = `Total available: ${availableQty.toLocaleString()} units`;
                    if (data.breakdown) {
                        tooltipText += `\nDivision-specific: ${data.breakdown.division_specific.toLocaleString()}`;
                        tooltipText += `\nUnassigned: ${data.breakdown.unassigned.toLocaleString()}`;
                    }
                    if (data.note) {
                        tooltipText += `\n${data.note}`;
                    }
                    stockBadge.title = tooltipText;
                } else {
                    stockBadge.className = 'badge badge-danger';
                    stockBadge.title = `No stock available in ${divisionName}`;
                }
            } else {
                console.error(`Stock badge not found for item ${itemId}`);
            }

            if (qtyInput) {
                const requested = itemData[itemId] ? itemData[itemId].requested : 0;
                const maxAllowed = Math.min(availableQty, requested);
                qtyInput.setAttribute('max', maxAllowed);

                // Reset input value if it exceeds available quantity
                if (parseFloat(qtyInput.value) > maxAllowed) {
                    qtyInput.value = maxAllowed;
                    updateAllocations(itemId);
                }
            }
        })
        .catch(error => {
            console.error('Error fetching division stock:', error);

            // Try to get the actual error response
            fetch(url)
                .then(response => response.text())
                .then(text => {
                    console.error('Error response body:', text);
                })
                .catch(e => console.error('Could not get error details:', e));

            const stockBadge = document.getElementById(`inventory_available_${itemId}`);
            if (stockBadge) {
                stockBadge.textContent = 'Error';
                stockBadge.className = 'badge badge-warning';
                stockBadge.title = `Error loading division stock: ${error.message}`;
            }
        });
}

/**
 * Update available FOC stock based on selected division
 */
function updateFocDivisionStock(itemId) {
    const divisionSelect = document.querySelector(`select[name="foc_division[${itemId}]"]`);
    const divisionId = divisionSelect.value;
    const divisionName = divisionSelect.options[divisionSelect.selectedIndex].getAttribute('data-division-name');

    const stockBadge = document.getElementById(`foc_available_${itemId}`);
    const qtyInput = document.querySelector(`input[name="foc[${itemId}]"]`);

    if (!divisionId) {
        // No division selected — reload total FOC quantities
        loadFocQuantities();
        return;
    }

    // Show loading state
    if (stockBadge) {
        stockBadge.className = 'badge badge-secondary';
        stockBadge.textContent = '...';
        stockBadge.title = 'Loading FOC stock...';
    }

    // Fetch division-specific FOC stock via AJAX
    const url = `{{ url('/warehouse/material-issue-api/foc-division-stock') }}/${itemId}/${divisionId}`;

    fetch(url, {
        method: 'GET',
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'application/json'
        }
    })
    .then(response => {
        if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
        return response.json();
    })
    .then(data => {
        const availableQty = data.available_quantity || 0;

        if (stockBadge) {
            stockBadge.textContent = availableQty.toLocaleString();
            if (availableQty > 0) {
                stockBadge.className = 'badge badge-warning';
                stockBadge.title = `FOC available in ${divisionName}: ${availableQty} units`;
            } else {
                stockBadge.className = 'badge badge-danger';
                stockBadge.title = `No FOC stock in ${divisionName}`;
            }
        }

        if (qtyInput) {
            const requested = itemData[itemId] ? itemData[itemId].requested : 0;
            const maxAllowed = Math.min(availableQty, requested);
            qtyInput.setAttribute('max', maxAllowed);

            if (parseFloat(qtyInput.value) > maxAllowed) {
                qtyInput.value = maxAllowed;
                updateAllocations(itemId);
            }
        }
    })
    .catch(error => {
        console.error('Error fetching FOC division stock:', error);
        if (stockBadge) {
            stockBadge.textContent = 'Error';
            stockBadge.className = 'badge badge-warning';
            stockBadge.title = `Error loading FOC stock: ${error.message}`;
        }
    });
}

/**
 * Update available indirect goods stock based on selected division.
 */
function updateIndirectDivisionStock(indirectItemId, context) {
    const divisionSelect = document.querySelector(`.${context}-indirect-division-select[data-indirect-id="${indirectItemId}"]`);
    const stockBadge = document.getElementById(`indirect_available_${context}_${indirectItemId}`);
    const qtyInput = document.querySelector(`.${context}-indirect-qty[data-indirect-id="${indirectItemId}"]`);

    if (!divisionSelect || !qtyInput) {
        return;
    }

    const divisionId = divisionSelect.value;
    const selectedOption = divisionSelect.options[divisionSelect.selectedIndex];
    const divisionName = selectedOption ? selectedOption.getAttribute('data-division-name') : '';
    const indirectGoodId = divisionSelect.getAttribute('data-indirect-good-id') || qtyInput.getAttribute('data-indirect-good-id');

    if (!divisionId || !indirectGoodId) {
        if (stockBadge) {
            stockBadge.textContent = '0';
            stockBadge.className = context === 'foc' ? 'badge badge-danger' : 'badge badge-danger';
            stockBadge.title = 'Select a division to see available stock';
        }

        qtyInput.setAttribute('max', '0');
        qtyInput.value = '0';
        updateIndirectAllocation(indirectItemId);
        return;
    }

    if (stockBadge) {
        stockBadge.textContent = '...';
        stockBadge.className = 'badge badge-secondary';
        stockBadge.title = 'Loading indirect goods stock...';
    }

    const url = `{{ url('/warehouse/material-issue-api/indirect-division-stock') }}/${indirectGoodId}/${divisionId}`;

    fetch(url, {
        method: 'GET',
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'application/json'
        }
    })
    .then(response => {
        if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
        return response.json();
    })
    .then(data => {
        const availableQty = data.available_quantity || 0;
        const balance = parseFloat(qtyInput.dataset.balance) || 0;
        const maxAllowed = Math.min(availableQty, balance);

        if (stockBadge) {
            stockBadge.textContent = availableQty.toLocaleString();
            if (availableQty > 0) {
                stockBadge.className = context === 'foc' ? 'badge badge-warning' : 'badge badge-success';
                stockBadge.title = `Indirect goods available in ${divisionName}: ${availableQty} units`;
            } else {
                stockBadge.className = 'badge badge-danger';
                stockBadge.title = `No indirect goods stock in ${divisionName}`;
            }
        }

        qtyInput.setAttribute('max', maxAllowed);
        if ((parseFloat(qtyInput.value) || 0) > maxAllowed) {
            qtyInput.value = maxAllowed;
            updateIndirectAllocation(indirectItemId);
        }
    })
    .catch(error => {
        console.error('Error fetching indirect division stock:', error);
        if (stockBadge) {
            stockBadge.textContent = 'Error';
            stockBadge.className = 'badge badge-warning';
            stockBadge.title = `Error loading indirect goods stock: ${error.message}`;
        }
    });
}
</script>
@endpush
