<script>
    window.rmReasons = [];
    <?php
    $rmReasons = [];
    if($careMonth->rm_reasons) {
        $rmReasons = json_decode($careMonth->rm_reasons);
    }
    ?>
    @if(count($rmReasons))
        @foreach($rmReasons as $reason)
        window.rmReasons.push({
            icd: '{{$reason->icd}}',
            description: '{{$reason->description}}'
        });
        @endforeach
    @endif
</script>
<div moe wide class="" id="careMonth_rmReasonsComponent">
    <a class="" href="" show start><i class="fa fa-edit"></i></a>
    <form url="/api/careMonth/updateRmReasons">
        <input type="hidden" name="uid" value="{{$careMonth->uid}}">
        <table class="table table-sm table-condensed table-borderless my-0" id="rm-reasons-table">
            <thead>
                <tr>
                    <th class="pl-0">Code</th>
                    <th>Description</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                @if(count($rmReasons))
                    @foreach($rmReasons as $reason)
                    <tr class="data-row">
                        <td class="pl-0"><input type="text" class="form-control rm-reason-icd" data-index="{{$loop->index}}" id="rm_icd_{{$loop->index}}" value="{{$reason->icd}}"></td>
                        <td class=""><input type="text" class="form-control rm-reason-description" data-index="{{$loop->index}}" id="rm_description_{{$loop->index}}" value="{{$reason->description}}"></td>
                        <td class="pr-0 align-middle"><a href="#" class="btn-remove-row text-danger"><i class="fa fa-trash-alt"></i></a></td>
                    </tr>
                    @endforeach
                @else
                <tr class="data-row">
                    <td class="pl-0"><input type="text" class="form-control rm-reason-icd"  data-index="0" id="rm_icd_0" name="rmReasonDTOs[0].code"></td>
                    <td class=""><input type="text" class="form-control rm-reason-description" data-index="0" id="rm_description_0" name="rmReasonDTOs[0].description"></td>
                    <td class="pr-0 align-middle"><a href="#" class="btn-remove-row text-danger"><i class="fa fa-trash-alt"></i></a></td>
                </tr>
                <tr class="data-row">
                    <td class="pl-0"><input type="text" class="form-control rm-reason-icd" data-index="1" id="rm_icd_1" name="rmReasonDTOs[1].code"></td>
                    <td class=""><input type="text" class="form-control rm-reason-description" data-index="1" id="rm_description_1" name="rmReasonDTOs[1].description"></td>
                    <td class="pr-0 align-middle"><a href="#" class="btn-remove-row text-danger"><i class="fa fa-trash-alt"></i></a></td>
                </tr>
                <tr class="data-row">
                    <td class="pl-0"><input type="text" class="form-control rm-reason-icd" data-index="2" id="rm_icd_2" name="rmReasonDTOs[2].code"></td>
                    <td class=""><input type="text" class="form-control rm-reason-description" data-index="2" id="rm_description_2" name="rmReasonDTOs[2].description"></td>
                    <td class="pr-0 align-middle"><a href="#" class="btn-remove-row text-danger"><i class="fa fa-trash-alt"></i></a></td>
                </tr>
                @endif
            </tbody>
        </table>
        <div class="form-group my-2">
            <button class="btn btn-outline-primary btn-sm btn-add-row">Add row</button>
        </div>
        <div class="form-group mb-0">
            <button class="btn btn-primary btn-sm" id="btnUpdateRmReasons" type="button">Submit</button>
            <button class="btn btn-default border btn-sm" cancel>Cancel</button>
        </div>
    </form>
</div>
<script>
    (function() {

        function init() {
            $("#careMonth_rmReasonsComponent .btn-add-row").click(function() {
                var rowCount = $('#rm-reasons-table').find('tr').length;
                var nextIndex = rowCount -1;
                var clone = $('#rm-reasons-table tr.data-row:first').clone();
                clone.find('input').attr('data-index', nextIndex);
                clone.find('input.rm-reason-icd').attr('name','rmReasonDTOs['+nextIndex+'].code').val('');
                clone.find('input.rm-reason-icd').attr('id','rm_icd_'+nextIndex);
                clone.find('input.rm-reason-description').attr('name','rmReasonDTOs['+nextIndex+'].description').val('');
                clone.find('input.rm-reason-description').attr('id','rm_description_'+nextIndex);
                $('#rm-reasons-table').append(clone);
                attachAutocompleterToField(nextIndex);
                return false;
            });

            $('#rm-reasons-table').on('click', '.btn-remove-row', function() {
                $(this).closest('tr').remove();
                return false;
            });

            $('#rm-reasons-table .rm-reason-icd').each(function(i,e) {
                var fieldIndex = $(e).attr('data-index');
                attachAutocompleterToField(fieldIndex);
            });

            $("#careMonth_rmReasonsComponent #btnUpdateRmReasons").click(function() {
                let rmReasons = [];
                $('tr.data-row').each(function() {
                    let icd = $.trim($(this).find('input.rm-reason-icd').val());
                    if(icd) {
                        rmReasons.push({
                            icd: icd,
                            description: $.trim($(this).find('input.rm-reason-description').val())
                        });
                    }
                });
                if(!rmReasons.length) return false;
                showMask();
                rmReasons = JSON.stringify(rmReasons);
                $.post('/api/careMonth/updateRmReasons', {
                    uid: '{{$careMonth->uid}}',
                    rmReasons: rmReasons
                }, (_data) => {
                    hideMask();
                    if(_data && _data.success) {
                        fastReload();
                    }
                    else {
                        toastr.error(_data.message ? _data.message : 'Unable to update RM reasons!');
                    }
                }, 'json');
                return false;
            });

            function attachAutocompleterToField(fieldIndex){
                var e = $('#rm_icd_'+fieldIndex)[0];
                new Def.Autocompleter.Search('rm_icd_'+fieldIndex, 'https://clinicaltables.nlm.nih.gov/api/icd10cm/v3/search?sf=code,name', {
                    tableFormat: true,
                    valueCols: [1],
                    colHeaders: ['Code', 'Name']
                });
                Def.Autocompleter.Event.observeListSelections('rm_icd_'+fieldIndex, function(data) {
                    console.log("Setting value of e to : ", data.item_code);
                    $('#rm_icd_'+fieldIndex).val(data.item_code);
                    $('#rm_description_'+fieldIndex).val(data.final_val);
                    $('#rm_icd_'+fieldIndex).focus();
                    return false;
                });
            }
        }

        addMCInitializer('careMonth_rmReasonsComponent', init, '#careMonth_rmReasonsComponent');

    })();
</script>
