@extends('layouts.admin-simple')

@section('title', 'New Easy Out Dispatch')

@section('breadcrumb')
    <li class="breadcrumb-item">Warehouse</li>
    <li class="breadcrumb-item">Outgoing</li>
    <li class="breadcrumb-item"><a href="{{ route('warehouse.easy-out.index') }}">Easy Out</a></li>
    <li class="breadcrumb-item active">New Dispatch</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 Easy Out Dispatch</h3>
            <p class="text-muted mb-0" style="font-size: 13px;">Issue available Easy In stock by bill number</p>
        </div>
        <div class="page-actions-right">
            <a href="{{ route('warehouse.easy-out.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')
    @if($errors->any())
        <div class="alert alert-danger">
            <strong>Please correct the dispatch details.</strong>
            @error('items') <div>{{ $message }}</div> @enderror
        </div>
    @endif

    <form method="POST" action="{{ route('warehouse.easy-out.store') }}" id="easyOutForm">
        @csrf

        <div class="card mb-3">
            <div class="card-header">
                <h6 class="mb-0"><i class="material-icons mr-2 align-middle">receipt_long</i>Dispatch Header</h6>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-4">
                        <div class="form-group">
                            <label class="font-weight-bold">Project/Site <span class="text-danger">*</span></label>
                            <select name="project_id" id="project_id" class="form-control warehouse-select2 @error('project_id') is-invalid @enderror"
                                    data-placeholder="Select Project" required>
                                <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>
                            @error('project_id') <div class="invalid-feedback">{{ $message }}</div> @enderror
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label class="font-weight-bold">Bill Number <span class="text-danger">*</span></label>
                            <select name="bill_number" id="billNumber" class="form-control warehouse-select2 @error('bill_number') is-invalid @enderror" required>
                                <option value="">Select Bill Number</option>
                                @foreach($billNumbers as $billNumber)
                                    <option value="{{ $billNumber }}" {{ old('bill_number') == $billNumber ? 'selected' : '' }}>{{ $billNumber }}</option>
                                @endforeach
                            </select>
                            @error('bill_number') <div class="invalid-feedback">{{ $message }}</div> @enderror
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="form-group">
                            <label class="font-weight-bold">Dispatch Date <span class="text-danger">*</span></label>
                            <input type="date" name="dispatch_date" class="form-control @error('dispatch_date') is-invalid @enderror"
                                   value="{{ old('dispatch_date', date('Y-m-d')) }}" required>
                            @error('dispatch_date') <div class="invalid-feedback">{{ $message }}</div> @enderror
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label class="font-weight-bold">Received By</label>
                            <input type="text" name="received_by" class="form-control @error('received_by') is-invalid @enderror"
                                   value="{{ old('received_by') }}" placeholder="Name of person receiving">
                            @error('received_by') <div class="invalid-feedback">{{ $message }}</div> @enderror
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-12">
                        <div class="form-group mb-0">
                            <label class="font-weight-bold">Purpose</label>
                            <input type="text" name="purpose" class="form-control @error('purpose') is-invalid @enderror"
                                   value="{{ old('purpose') }}" placeholder="Purpose of dispatch">
                            @error('purpose') <div class="invalid-feedback">{{ $message }}</div> @enderror
                        </div>
                    </div>
                </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">table_chart</i>Dispatch Items</h6>
                <small class="text-muted" id="billHint">Please select a Bill Number first.</small>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-sm mb-0 easy-lines-table">
                        <thead class="thead-light">
                            <tr>
                                <th style="min-width: 130px;">MR No.</th>
                                <th style="min-width: 260px;">Item Description <span class="text-danger">*</span></th>
                                <th style="min-width: 110px;">Unit</th>
                                <th style="min-width: 150px;">Available Balance</th>
                                <th style="min-width: 150px;">Quantity to Issue <span class="text-danger">*</span></th>
                                <th style="min-width: 180px;">Division</th>
                                <th style="width: 64px;"></th>
                            </tr>
                        </thead>
                        <tbody id="dispatchRows"></tbody>
                    </table>
                </div>
            </div>
            <div class="card-footer d-flex justify-content-between align-items-center">
                <button type="button" class="btn btn-outline-primary" id="addRowBtn">
                    <i class="material-icons mr-1" style="font-size: 16px;">add</i> Add Row
                </button>
                <small class="text-muted">Items with zero balance are hidden automatically.</small>
            </div>
        </div>

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

    <template id="dispatchRowTemplate">
        <tr>
            <td>
                <input type="text" class="form-control form-control-sm" data-name="mr_no" placeholder="MR / LPO">
            </td>
            <td>
                <select class="form-control form-control-sm item-selector" data-name="item_description" required disabled>
                    <option value="">Please select a Bill Number first</option>
                </select>
            </td>
            <td>
                <input type="text" class="form-control form-control-sm bg-light unit-field" data-name="unit" readonly required>
            </td>
            <td>
                <input type="text" class="form-control form-control-sm bg-light balance-field" readonly>
            </td>
            <td>
                <input type="number" class="form-control form-control-sm quantity-field" data-name="quantity" step="0.01" min="0.01" required>
                <div class="invalid-feedback quantity-warning">Insufficient balance.</div>
            </td>
            <td>
                <select class="form-control form-control-sm" data-name="division_id">
                    <option value="">Select Division</option>
                    @foreach($divisions as $division)
                        <option value="{{ $division->id }}">{{ $division->division_name }}</option>
                    @endforeach
                </select>
            </td>
            <td class="text-center">
                <button type="button" class="btn btn-sm btn-outline-danger delete-row" title="Delete Row">
                    <i class="material-icons" style="font-size: 16px;">delete</i>
                </button>
            </td>
        </tr>
    </template>
@endsection

@push('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--default .select2-selection--single { height: 34px; border: 1px solid #ced4da; }
        .select2-container--default .select2-selection--single .select2-selection__rendered { line-height: 32px; }
        .select2-container--default .select2-selection--single .select2-selection__arrow { height: 32px; }
        .easy-lines-table th,
        .easy-lines-table td { vertical-align: middle; }
        .easy-lines-table .form-control-sm { min-height: 34px; }
    </style>
@endpush

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
$(function () {
    var rowIndex = 0;
    var stockByBill = @json($easyInItems);

    $('.warehouse-select2').select2({ allowClear: true });

    function currentBill() {
        return $('#billNumber').val();
    }

    function refreshNames(row) {
        row.find('[data-name]').each(function () {
            $(this).attr('name', 'items[' + rowIndex + '][' + $(this).data('name') + ']');
        });
        rowIndex++;
    }

    function itemKey(item) {
        return item.item_description + '|' + item.unit;
    }

    function billItems() {
        return stockByBill[currentBill()] || [];
    }

    function populateItemSelect(row) {
        var select = row.find('.item-selector');
        var bill = currentBill();
        select.empty();
        row.find('.unit-field, .balance-field').val('');
        row.find('.quantity-field').removeAttr('max').val('').removeClass('is-invalid');
        row.find('.quantity-warning').text('Insufficient balance.').hide();

        if (!bill) {
            select.append(new Option('Please select a Bill Number first', ''));
            select.prop('disabled', true);
            return;
        }

        var items = billItems();
        select.append(new Option('Select Item', ''));

        items.forEach(function (item) {
            var option = new Option(item.item_description + ' - ' + item.unit + ' | Available: ' + parseFloat(item.balance).toFixed(2), item.item_description);
            $(option)
                .attr('data-unit', item.unit)
                .attr('data-balance', item.balance)
                .attr('data-key', itemKey(item));
            select.append(option);
        });

        select.prop('disabled', items.length === 0);
    }

    function addRow() {
        var row = $($('#dispatchRowTemplate').html());
        refreshNames(row);
        $('#dispatchRows').append(row);
        populateItemSelect(row);
    }

    function updateSelectedItem(row) {
        var selected = row.find('.item-selector option:selected');
        var unit = selected.data('unit') || '';
        var balance = parseFloat(selected.data('balance')) || 0;

        row.find('.unit-field').val(unit);
        row.find('.balance-field').val(unit ? balance.toFixed(2) : '');
        row.find('.quantity-field').attr('max', balance);
        validateQuantities();
    }

    function validateQuantities() {
        var bill = currentBill();
        var valid = !!bill;
        var totals = {};

        $('#dispatchRows tr').each(function () {
            var row = $(this);
            var selected = row.find('.item-selector option:selected');
            var key = selected.data('key');
            var balance = parseFloat(selected.data('balance')) || 0;
            var qty = parseFloat(row.find('.quantity-field').val()) || 0;

            row.find('.quantity-field').removeClass('is-invalid');
            row.find('.quantity-warning').hide();

            if (!key) {
                valid = false;
                return;
            }

            totals[key] = (totals[key] || 0) + qty;
            if (qty <= 0 || totals[key] > balance) {
                valid = false;
                row.find('.quantity-field').addClass('is-invalid');
                row.find('.quantity-warning').text('Insufficient balance. Max allowed: ' + balance.toFixed(2) + '.').show();
            }
        });

        $('#saveDispatchBtn').prop('disabled', !valid);
        $('#billHint').text(bill ? 'Showing available items for Bill Number ' + bill + '.' : 'Please select a Bill Number first.');
        return valid;
    }

    $('#billNumber').on('change', function () {
        $('#dispatchRows tr').each(function () {
            populateItemSelect($(this));
        });
        validateQuantities();
    });

    $('#addRowBtn').on('click', addRow);

    $('#dispatchRows').on('change', '.item-selector', function () {
        updateSelectedItem($(this).closest('tr'));
    });

    $('#dispatchRows').on('input', '.quantity-field', validateQuantities);

    $('#dispatchRows').on('click', '.delete-row', function () {
        if ($('#dispatchRows tr').length > 1) {
            $(this).closest('tr').remove();
            validateQuantities();
        }
    });

    $('#easyOutForm').on('submit', function (e) {
        if (!validateQuantities()) {
            e.preventDefault();
        }
    });

    addRow();
    validateQuantities();
});
</script>
@endpush
