@extends('layouts.admin-simple')

@section('title', 'New Asset Allocation')

@section('breadcrumb')
    <li class="breadcrumb-item">Warehouse</li>
    <li class="breadcrumb-item">Fixed Assets</li>
    <li class="breadcrumb-item"><a href="{{ route('warehouse.fixed-assets.allocations.index') }}">Allocations</a></li>
    <li class="breadcrumb-item active">New Allocation</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">New Asset Allocation</h3>
            <p class="text-muted mb-0" style="font-size: 13px;">Create an asset allocation to be allocated later</p>
        </div>
        <div class="page-actions-right">
            <a href="{{ route('warehouse.fixed-assets.allocations.index') }}" class="btn btn-sm btn-outline-secondary"><i class="material-icons mr-1" style="font-size: 16px;">arrow_back</i> Back</a>
        </div>
    </div>
@endsection

@section('content')
    <form method="POST" action="{{ route('warehouse.fixed-assets.allocations.store') }}">
        @csrf
        <div class="card mb-3">
            <div class="card-header"><h6 class="mb-0"><i class="material-icons mr-2 align-middle">assignment</i>Allocation Details</h6></div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-4">
                        <div class="form-group">
                            <label>Destination <span class="text-danger">*</span></label>
                            <select name="destination_type" id="destination_type" class="form-control" required>
                                <option value="project" {{ old('destination_type', 'project') == 'project' ? 'selected' : '' }}>Project</option>
                                <option value="repair_shop" {{ old('destination_type') == 'repair_shop' ? 'selected' : '' }}>Repair Shop</option>
                                <option value="warehouse" {{ old('destination_type') == 'warehouse' ? 'selected' : '' }}>Back to Warehouse</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-4" id="project-field">
                        <div class="form-group">
                            <label>Project <span class="text-danger">*</span></label>
                            <select name="project_id" id="project_id" class="form-control select2-dropdown">
                                <option value="">Select Project</option>
                                @foreach($projects as $p)
                                    <option value="{{ $p->id }}" {{ old('project_id') == $p->id ? 'selected' : '' }}>{{ $p->project_number }} - {{ $p->project_name }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                    <div class="col-md-4" id="destination-hint" style="display:none; padding-top: 28px;">
                        <div id="hint-repair" class="alert alert-warning py-2 mb-0" style="display:none; font-size: 13px;">
                            <i class="material-icons align-middle mr-1" style="font-size: 16px;">build</i>
                            Asset will be set to <strong>Under Maintenance</strong>
                        </div>
                        <div id="hint-warehouse" class="alert alert-info py-2 mb-0" style="display:none; font-size: 13px;">
                            <i class="material-icons align-middle mr-1" style="font-size: 16px;">store</i>
                            Asset will be returned to <strong>Warehouse stock</strong>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label>Purpose</label>
                            <input type="text" name="purpose" class="form-control" value="{{ old('purpose') }}" placeholder="Purpose of allocation">
                        </div>
                    </div>
                </div>
                <div class="form-group mb-0">
                    <label>Notes</label>
                    <textarea name="notes" rows="2" class="form-control">{{ old('notes') }}</textarea>
                </div>
            </div>
        </div>

        <div class="card mb-3">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h6 class="mb-0"><i class="material-icons mr-2 align-middle">devices</i>Select Assets</h6>
                <button type="button" onclick="addAssetRow()" class="btn btn-sm btn-success"><i class="material-icons mr-1" style="font-size: 16px;">add</i> Add Asset</button>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table mb-0" id="assets-table">
                        <thead class="thead-light">
                            <tr>
                                <th style="min-width: 300px;">Asset *</th>
                                <th style="min-width: 220px;">Current Location</th>
                                <th>Condition</th>
                                <th style="width: 60px;"></th>
                            </tr>
                        </thead>
                        <tbody id="assets-body"></tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="card">
            <div class="card-body text-center py-3">
                <button type="submit" class="btn btn-success mr-3"><i class="material-icons mr-1" style="font-size: 16px;">save</i> Save Allocation</button>
                <a href="{{ route('warehouse.fixed-assets.allocations.index') }}" class="btn btn-outline-secondary">Cancel</a>
            </div>
        </div>
    </form>
@endsection

@push('styles')
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css">
    <style>
        .select2-container { width: 100% !important; }
        .select2-container--default .select2-selection--single { height: 38px; border: 1px solid #ced4da; }
        .select2-container--default .select2-selection--single .select2-selection__rendered { line-height: 36px; }
        .select2-container--default .select2-selection--single .select2-selection__arrow { height: 36px; }
        .asset-location-text { font-size: 12px; line-height: 1.35; }
    </style>
@endpush

@push('scripts')
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script>
        let assetIndex = 0;
        const availableAssets = @json($availableAssets);
        const assetsById = {};

        availableAssets.forEach(asset => {
            assetsById[asset.id] = asset;
        });

        function applyDestinationType(val) {
            if (val === 'project') {
                $('#project-field').show();
                $('#project_id').prop('required', true);
                $('#destination-hint').hide();
                $('#hint-repair, #hint-warehouse').hide();
            } else {
                $('#project-field').hide();
                $('#project_id').prop('required', false).val(null).trigger('change');
                $('#destination-hint').show();
                if (val === 'repair_shop') {
                    $('#hint-repair').show();
                    $('#hint-warehouse').hide();
                } else {
                    $('#hint-warehouse').show();
                    $('#hint-repair').hide();
                }
            }
        }

        $(document).ready(function() {
            $('.select2-dropdown').select2({ allowClear: true });
            $('#project_id').on('change', refreshAllAssetRows);
            $('#destination_type').on('change', function() {
                applyDestinationType($(this).val());
            });
            applyDestinationType($('#destination_type').val());
            addAssetRow();
        });

        function addAssetRow() {
            const rowIndex = assetIndex;
            let opts = '<option value="">Select Asset</option>';
            availableAssets.forEach(a => {
                opts += `<option value="${a.id}">${a.asset_name} (${a.asset_code}) - ${a.category ? a.category.category_name : 'N/A'}</option>`;
            });

            let row = `<tr id="asset-row-${rowIndex}">
                <td><select name="items[${rowIndex}][fixed_asset_id]" class="form-control form-control-sm asset-select" required>${opts}</select></td>
                <td><div class="asset-location-text text-muted" id="asset-location-${rowIndex}">Select asset</div></td>
                <td><select name="items[${rowIndex}][condition_at_allocation]" class="form-control form-control-sm">
                    <option value="good">Good</option><option value="new">New</option><option value="fair">Fair</option><option value="poor">Poor</option>
                </select></td>
                <td><button type="button" onclick="removeAssetRow(${rowIndex})" class="btn btn-sm btn-outline-danger"><i class="material-icons" style="font-size: 16px;">close</i></button></td>
            </tr>`;
            $('#assets-body').append(row);
            $(`#asset-row-${rowIndex} .asset-select`)
                .select2({ placeholder: 'Select Asset', allowClear: true })
                .on('change', function() {
                    refreshAssetRow(rowIndex);
                });
            assetIndex++;
        }

        function removeAssetRow(idx) {
            if ($('#assets-body tr').length > 1) $(`#asset-row-${idx}`).remove();
        }

        function refreshAllAssetRows() {
            $('#assets-body tr').each(function() {
                const idx = this.id.replace('asset-row-', '');
                refreshAssetRow(idx);
            });
        }

        function refreshAssetRow(idx) {
            const assetId = $(`#asset-row-${idx} .asset-select`).val();
            const asset = assetsById[assetId];

            if (!asset) {
                $(`#asset-location-${idx}`).text('Select asset').addClass('text-muted');
                return;
            }

            $(`#asset-location-${idx}`).text(locationLabel(asset)).removeClass('text-muted');
        }

        function locationLabel(asset) {
            if (asset.location_label) {
                return asset.location_label;
            }

            if (asset.current_project) {
                let label = asset.current_project.project_name;
                if (asset.current_division) {
                    label += ' / ' + (asset.current_division.name || asset.current_division.division_name || 'Division');
                }
                return label;
            }

            return asset.current_location || 'Warehouse';
        }
    </script>
@endpush
