@extends('layouts.admin-simple')

@section('title', 'Create Indirect Goods Material Request')

@section('breadcrumb')
    <li class="breadcrumb-item">Warehouse</li>
    <li class="breadcrumb-item">Indirect Goods</li>
    <li class="breadcrumb-item"><a href="{{ route('warehouse.indirect-goods.requests.index') }}">Material Requests</a></li>
    <li class="breadcrumb-item active">Create</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">Create Material Request</h3>
            <p class="text-muted mb-0" style="font-size: 13px;">Request indirect goods materials for a project</p>
        </div>
        <div class="page-actions-right d-flex align-items-center">
            <a href="{{ route('warehouse.indirect-goods.requests.index') }}" class="btn btn-sm btn-secondary">
                <i class="material-icons mr-1" style="font-size: 16px;">arrow_back</i>
                Back to List
            </a>
        </div>
    </div>
@endsection

@section('styles')
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<style>
    .select2-container { width: 100% !important; }
    .select2-container .select2-selection { min-height: 38px; }
    .table-responsive { overflow: visible !important; }
    #items-table { overflow: visible !important; }
    #items-tbody .select2-container { position: relative !important; }
    #items-tbody .select2-dropdown { position: absolute !important; top: 100% !important; z-index: 9999 !important; }
    .select2-dropdown { min-width: 300px !important; }
</style>
@endsection

@section('content')
    <div class="card shadow">
        <div class="card-header">
            <h6 class="m-0 font-weight-bold text-primary">
                <i class="material-icons align-middle mr-1">assignment</i>
                Indirect Goods Material Request Form
            </h6>
        </div>
        <div class="card-body">
            <form action="{{ route('warehouse.indirect-goods.requests.store') }}" method="POST" id="igRequestForm" enctype="multipart/form-data">
                @csrf

                <!-- Request Information -->
                <div class="row mb-4">
                    <div class="col-12">
                        <h6 class="font-weight-bold text-secondary mb-3">
                            <i class="material-icons align-middle mr-1">info</i>
                            Request Information
                        </h6>
                        <div class="row">
                            <!-- Date -->
                            <div class="col-md-3 mb-3">
                                <label for="request_date" class="form-label">Request Date <span class="text-danger">*</span></label>
                                <input type="date"
                                       class="form-control @error('request_date') is-invalid @enderror"
                                       id="request_date"
                                       name="request_date"
                                       value="{{ old('request_date', date('Y-m-d')) }}"
                                       required>
                                @error('request_date')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>

                            <!-- Project -->
                            <div class="col-md-5 mb-3">
                                <label for="project_id" class="form-label">Project <span class="text-danger">*</span></label>
                                <select name="project_id" id="project_id" class="form-control select2-project @error('project_id') is-invalid @enderror" required>
                                    <option value="">Select Project</option>
                                    @foreach($projects as $project)
                                        <option value="{{ $project->id }}"
                                                data-division-id="{{ $project->project_division_id ?? '' }}"
                                                data-division-name="{{ $project->projectDivision->division_name ?? '' }}"
                                                {{ old('project_id') == $project->id ? 'selected' : '' }}>
                                            {{ $project->project_number }} - {{ $project->project_name }}
                                        </option>
                                    @endforeach
                                </select>
                                @error('project_id')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>

                            <!-- Division -->
                            <div class="col-md-4 mb-3">
                                <label for="division_id" class="form-label">Division</label>
                                <select name="division_id" id="division_id" class="form-control select2-division @error('division_id') is-invalid @enderror">
                                    <option value="">Select Division</option>
                                    @foreach($divisions as $division)
                                        <option value="{{ $division->id }}" {{ old('division_id') == $division->id ? 'selected' : '' }}>
                                            {{ $division->division_name }}
                                        </option>
                                    @endforeach
                                </select>
                                @error('division_id')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>

                        <div class="row">
                            <!-- Receiver Name -->
                            <div class="col-md-4 mb-3">
                                <label for="receiver_name" class="form-label">Receiver Name</label>
                                <input type="text"
                                       class="form-control @error('receiver_name') is-invalid @enderror"
                                       id="receiver_name"
                                       name="receiver_name"
                                       value="{{ old('receiver_name') }}"
                                       placeholder="Name of person receiving materials">
                                @error('receiver_name')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>

                            <!-- Request File -->
                            <div class="col-md-4 mb-3">
                                <label for="request_file" class="form-label">Request File</label>
                                <input type="file"
                                       class="form-control @error('request_file') is-invalid @enderror"
                                       id="request_file"
                                       name="request_file"
                                       accept=".pdf,.doc,.docx,.jpg,.jpeg,.png">
                                <small class="form-text text-muted">PDF, DOC, DOCX, JPG, PNG (max 10MB)</small>
                                @error('request_file')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>

                            <!-- Requires Approval -->
                            <div class="col-md-4 mb-3 d-flex align-items-end">
                                <div class="custom-control custom-checkbox">
                                    <input type="checkbox"
                                           class="custom-control-input"
                                           id="requires_approval"
                                           name="requires_approval"
                                           value="1"
                                           {{ old('requires_approval', '1') ? 'checked' : '' }}>
                                    <label class="custom-control-label" for="requires_approval">
                                        <strong>Requires Approval</strong>
                                        <br><small class="text-muted">If unchecked, request will be auto-approved</small>
                                    </label>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <!-- Notes -->
                            <div class="col-md-12 mb-3">
                                <label for="notes" class="form-label">Notes</label>
                                <textarea class="form-control @error('notes') is-invalid @enderror"
                                          id="notes"
                                          name="notes"
                                          rows="2"
                                          placeholder="Additional notes or remarks...">{{ old('notes') }}</textarea>
                                @error('notes')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>
                    </div>
                </div>

                <hr class="my-4">

                <!-- Items Section -->
                <div class="row">
                    <div class="col-12">
                        <h6 class="font-weight-bold text-secondary mb-3">
                            <i class="material-icons align-middle mr-1">shopping_cart</i>
                            Request Items
                        </h6>

                        <div class="table-responsive">
                            <table class="table table-bordered" id="items-table">
                                <thead class="thead-light">
                                    <tr>
                                        <th width="50%">Indirect Good <span class="text-danger">*</span></th>
                                        <th width="20%">Quantity Requested <span class="text-danger">*</span></th>
                                        <th width="25%">Notes</th>
                                        <th width="5%">Action</th>
                                    </tr>
                                </thead>
                                <tbody id="items-tbody">
                                    <tr data-row="0">
                                        <td>
                                            <select name="items[0][indirect_good_id]" id="ig_select_0" class="form-control ig-select" required>
                                                <option value="">Select Indirect Good</option>
                                            </select>
                                        </td>
                                        <td>
                                            <input type="number" name="items[0][quantity_requested]" class="form-control qty-input" step="0.01" min="0.01" placeholder="0.00" required>
                                        </td>
                                        <td>
                                            <input type="text" name="items[0][notes]" class="form-control" placeholder="Item notes...">
                                        </td>
                                        <td class="text-center">
                                            <button type="button" class="btn btn-sm btn-outline-danger remove-row-btn" title="Remove row">
                                                <i class="material-icons" style="font-size: 18px;">delete</i>
                                            </button>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>

                        <div class="mb-3">
                            <button type="button" class="btn btn-outline-primary" id="addRowBtn">
                                <i class="material-icons mr-1" style="font-size: 16px;">add</i>
                                Add Another Item
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Form Actions -->
                <hr class="my-4">
                <div class="row">
                    <div class="col-12">
                        <div class="d-flex justify-content-between align-items-center">
                            <div class="text-muted">
                                <i class="material-icons align-middle mr-1">info</i>
                                <strong>Total Items:</strong> <span id="totalItemsDisplay">1</span>
                            </div>
                            <div>
                                <a href="{{ route('warehouse.indirect-goods.requests.index') }}" class="btn btn-outline-secondary mr-2">
                                    <i class="material-icons mr-1" style="font-size: 16px;">arrow_back</i>
                                    Cancel
                                </a>
                                <button type="submit" class="btn btn-success" id="submitBtn">
                                    <i class="material-icons mr-1" style="font-size: 16px;">send</i>
                                    Submit Request
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
@endsection

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
let rowCounter = 1;

$(document).ready(function() {
    // Initialize Select2 for project
    $('.select2-project').select2({
        placeholder: 'Select Project',
        allowClear: true,
        width: '100%'
    });

    // Initialize Select2 for division
    $('.select2-division').select2({
        placeholder: 'Select Division',
        allowClear: true,
        width: '100%'
    });

    // Project change - auto-select division
    $('#project_id').on('change', function() {
        var selectedOption = $(this).find('option:selected');
        var divisionId = selectedOption.data('division-id');
        var divisionName = selectedOption.data('division-name');

        if (divisionId) {
            $('#division_id').val(divisionId).trigger('change');
        }
    });

    // Initialize Select2 for first item row
    initIGSelect2(0);

    // Add row button
    $('#addRowBtn').on('click', function() {
        addItemRow();
    });

    // Remove row button (event delegation)
    $(document).on('click', '.remove-row-btn', function() {
        var tbody = document.getElementById('items-tbody');
        if (tbody.children.length > 1) {
            var row = $(this).closest('tr');
            var select = row.find('.ig-select');
            if (select.hasClass('select2-hidden-accessible')) {
                select.select2('destroy');
            }
            row.remove();
            updateItemCount();
        } else {
            alert('At least one item row is required.');
        }
    });

    // Form submission validation
    $('#igRequestForm').on('submit', function(e) {
        var isValid = true;
        var errors = [];

        if (!$('#request_date').val()) {
            isValid = false;
            errors.push('Request Date is required');
            $('#request_date').addClass('is-invalid');
        }

        if (!$('#project_id').val()) {
            isValid = false;
            errors.push('Project is required');
        }

        // Validate items
        var selectedGoods = [];
        var hasDuplicates = false;

        $('#items-tbody tr').each(function(index) {
            var goodSelect = $(this).find('.ig-select');
            var qtyInput = $(this).find('.qty-input');
            var goodId = goodSelect.val();

            if (!goodId) {
                isValid = false;
                errors.push('Item selection is required in row ' + (index + 1));
            } else if (selectedGoods.includes(goodId)) {
                isValid = false;
                hasDuplicates = true;
            } else {
                selectedGoods.push(goodId);
            }

            if (!qtyInput.val() || parseFloat(qtyInput.val()) <= 0) {
                isValid = false;
                errors.push('Quantity is required in row ' + (index + 1));
                qtyInput.addClass('is-invalid');
            } else {
                qtyInput.removeClass('is-invalid');
            }
        });

        if (hasDuplicates) {
            errors.push('Duplicate items detected. Please remove duplicates.');
        }

        if (!isValid) {
            e.preventDefault();
            alert('Please fix the following errors:\n\n' + errors.join('\n'));
            return false;
        }
    });

    // Clear validation on input
    $(document).on('input change', '.qty-input', function() {
        if ($(this).val() && parseFloat($(this).val()) > 0) {
            $(this).removeClass('is-invalid');
        }
    });

    $(document).on('change', '#request_date', function() {
        $(this).removeClass('is-invalid');
    });
});

function addItemRow() {
    var tbody = document.getElementById('items-tbody');
    var newRow = document.createElement('tr');
    newRow.setAttribute('data-row', rowCounter);

    newRow.innerHTML = '<td>' +
        '<select name="items[' + rowCounter + '][indirect_good_id]" id="ig_select_' + rowCounter + '" class="form-control ig-select" required>' +
        '<option value="">Select Indirect Good</option>' +
        '</select>' +
        '</td>' +
        '<td>' +
        '<input type="number" name="items[' + rowCounter + '][quantity_requested]" class="form-control qty-input" step="0.01" min="0.01" placeholder="0.00" required>' +
        '</td>' +
        '<td>' +
        '<input type="text" name="items[' + rowCounter + '][notes]" class="form-control" placeholder="Item notes...">' +
        '</td>' +
        '<td class="text-center">' +
        '<button type="button" class="btn btn-sm btn-outline-danger remove-row-btn" title="Remove row">' +
        '<i class="material-icons" style="font-size: 18px;">delete</i>' +
        '</button>' +
        '</td>';

    tbody.appendChild(newRow);
    initIGSelect2(rowCounter);
    rowCounter++;
    updateItemCount();
}

function initIGSelect2(rowIndex) {
    var selectId = '#ig_select_' + rowIndex;

    $(selectId).select2({
        placeholder: 'Search indirect goods...',
        allowClear: true,
        width: '100%',
        minimumInputLength: 1,
        ajax: {
            url: '{{ route("warehouse.indirect-goods.catalog.dropdown") }}',
            dataType: 'json',
            delay: 250,
            data: function(params) {
                return {
                    q: params.term,
                    page: params.page || 1
                };
            },
            processResults: function(data) {
                // Handle both array and object responses
                var items = Array.isArray(data) ? data : (data.data || data.results || []);
                return {
                    results: items.map(function(item) {
                        return {
                            id: item.id || item.value,
                            text: item.text || (item.ig_code + ' - ' + item.ig_description),
                            ig_code: item.ig_code || '',
                            ig_description: item.ig_description || '',
                            unit_of_measure: item.unit_of_measure || ''
                        };
                    })
                };
            },
            cache: true
        },
        language: {
            inputTooShort: function() {
                return 'Type at least 1 character to search';
            },
            searching: function() {
                return 'Searching...';
            },
            noResults: function() {
                return 'No indirect goods found';
            }
        }
    });

    // Prevent duplicate selection
    $(selectId).on('select2:select', function() {
        var selectedId = $(this).val();
        var currentSelect = this;
        var isDuplicate = false;

        $('#items-tbody .ig-select').each(function() {
            if (this !== currentSelect && $(this).val() === selectedId) {
                isDuplicate = true;
            }
        });

        if (isDuplicate) {
            alert('This item has already been added. Please select a different item.');
            $(this).val('').trigger('change');
        }
    });
}

function updateItemCount() {
    var count = $('#items-tbody tr').length;
    $('#totalItemsDisplay').text(count);
}
</script>
@endpush
