<?php

use App\Models\Point;
use App\Models\Client;
use App\Models\Note;
use App\Models\Segment;

/** @var Client $patient */
/** @var Note $note */

$formID = rand(100000, 999999);

?>

<div class="mt-3 p-3 border-top" id="problems-quick-add-{{$formID}}">
    <div class="d-flex align-items-center">
        <form action="/api/visitPoint/addTopLevel" class="mcp-theme-1 w-100" id="frm-add-problem">
            <input type="hidden" name="noteUid" value="<?= $note->uid ?>">
            <input type="hidden" name="category" value="PROBLEM">
            <input type="hidden" name="data">

            <input type="hidden" data-name="dxid">
            <input type="hidden" data-name="icd-type">

            <input type="hidden" name="additionReasonCategory">
            <input type="hidden" name="isRemoved">
            <input type="hidden" name="removalReasonCategory">
            <input type="hidden" name="isRemovedDueToEntryError">

            <div class="row mb-2">
                <div class="col-8 pr-0">
                    <label class="text-sm text-secondary mb-0">Name</label>
                    <input type="text"
                           data-name="name"
                           class="form-control form-control-sm"
                           stag-suggest
                           stag-suggest-ep="/fdb-dx-suggest/json"
                           required>
                </div>
                <div class="col-4">
                    <label class="text-sm text-secondary mb-0">ICD</label>
                    <select data-name="icd"
                            class="form-control form-control-sm min-width-unset"
                            disabled>
                    </select>
                </div>
            </div>
            <div class="row mb-2">
                <div class="col-12">
                    <label class="text-sm text-secondary mb-0">Historic / Preexisting / New</label>
                    <select class="form-control form-control-sm additionReasonCategory_ui"
                            name="additionReasonCategory_ui" required>
                        <option value="">-- select --</option>
                        <option value="HISTORIC">Historic</option>
                        <option value="PRE_EXISTING" selected>Preexisting</option>
                        <option value="NEW">New (Found during this visit)</option>
                    </select>
                </div>
            </div>
            <div class="row mb-2">
                <div class="col-4 pr-0">
                    <div class="start_date_ui" style="display: none">
                        <label class="text-sm text-secondary mb-0">Start Date</label>
                        <input type="date"
                               data-name="start_date"
                               class="form-control form-control-sm min-width-unset">
                    </div>
                </div>
                <div class="col-4 pr-0">
                    <div class="removalEffectiveDate_ui" style="display: none">
                        <label class="text-sm text-secondary mb-0">End Date</label>
                        <input type="date"
                               name="removalEffectiveDate"
                               class="form-control form-control-sm min-width-unset">
                    </div>
                </div>
                <div class="col-4">
                    <div class="removalReasonMemo_ui" style="display: none">
                        <label class="text-sm text-secondary mb-0">Removal By/Memo</label>
                        <input type="text"
                               name="removalReasonMemo"
                               class="form-control form-control-sm min-width-unset">
                    </div>
                </div>
            </div>

            <div class="d-flex align-items-center">
                <button type="submit" class="btn btn-sm btn-primary mr-2 my-1">Save Problem</button>
            </div>
        </form>
    </div>
</div>

<script>
    (function () {
        function init() {
            let parentSegment = $('#problems-quick-add-{{$formID}}');
            parentSegment.find('input[stag-suggest][data-name="name"]')
                .off('stag-suggest-selected')
                .on('stag-suggest-selected', (_e, _input, _data) => {
                    $(_input).closest('form').find('input[data-name="dxid"]').val(_data.dxid);
                    let icdSelect = $(_input).closest('form').find('[data-name="icd"]').empty().prop('disabled', true);
                    $.get('/fdb-dx-icds-for-dxid?dxid=' + _data.dxid, _data => {
                        icdSelect.empty().append('<option value="">-- select --</option>');
                        for (let i = 0; i < _data.length; i++) {
                            icdSelect.append('<option value="' + _data[i].search_icd_cd + '" data-icd-type="' + _data[i].icd_cd_type + '">' + _data[i].search_icd_cd + ' (' + (_data[i].icd_cd_type === '01' ? 'ICD-9' : 'ICD-10') + ') - ' + _data[i].icd_desc + '</option>')
                        }
                        icdSelect.prop('disabled', false);
                        if (_data.length === 1) {
                            icdSelect.val(_data[0].search_icd_cd).trigger('change');
                        }
                    }, 'json');
                });

            // on route selection
            parentSegment.find('input[data-name="icd"]')
                .off('change')
                .on('change', function () {
                    $(this).closest('form').find('input[data-name="icd-type"]').val($(this).find('option:selected').attr('data-icd-type'));
                });

            parentSegment.find('.additionReasonCategory_ui')
                .off('change')
                .on('change', function () {

                    let form = $(this).closest('form');

                    // additionReasonCategory
                    // isRemoved
                    // removalReasonCategory
                    form.find('[name="isRemovedDueToEntryError"]').val('0');

                    form.find('.start_date_ui').hide();
                    form.find('.removalEffectiveDate_ui').hide();
                    form.find('.removalReasonMemo_ui').hide();

                    if (this.value === 'HISTORIC') {
                        form.find('[name="additionReasonCategory"]').val('ON_INTAKE');
                        form.find('[name="isRemoved"]').val('1');
                        form.find('.start_date_ui').show();
                        form.find('.removalEffectiveDate_ui').show();
                        form.find('.removalReasonMemo_ui').show();
                    } else if (this.value === 'PRE_EXISTING') {
                        form.find('[name="additionReasonCategory"]').val('ON_INTAKE');
                        form.find('[name="isRemoved"]').val('0');
                        form.find('.start_date_ui').show();
                    } else if (this.value === 'NEW') {
                        form.find('[name="additionReasonCategory"]').val('DURING_VISIT');
                        form.find('[name="isRemoved"]').val('0');
                        form.find('.start_date_ui').show().find('input').val('{{date('Y-m-d')}}');
                    }

                });

            parentSegment.find('#frm-add-problem')
                .off('submit')
                .on('submit', function () {

                    let form = $(this);

                    if (!form[0].checkValidity()) {
                        form[0].reportValidity();
                        return false;
                    }

                    // add [data-name] values to payload
                    let dataField = form.find('[name="data"]').first();
                    let parsed = null;
                    if (dataField.val()) {
                        parsed = JSON.parse(dataField.val());
                    }
                    form.find('[data-name]').each(function () {
                        if (!parsed) parsed = {};

                        let keys = $(this).attr('data-name').split('->');
                        let currentNode = parsed;
                        for (let i = 0; i < keys.length; i++) {
                            if (i !== keys.length - 1) {
                                if (typeof currentNode[keys[i]] === 'undefined') {
                                    currentNode[keys[i]] = {};
                                }
                                currentNode = currentNode[keys[i]];
                            } else {
                                if ($(this).is(':checkbox')) {
                                    currentNode[keys[i]] = $(this).prop('checked');
                                } else {
                                    currentNode[keys[i]] = $(this).val();
                                }
                            }
                        }

                    });
                    if (parsed) {
                        dataField.val(JSON.stringify(parsed));
                    }

                    $.post(form.attr('action'), form.serialize(), _data => {
                        if (!hasResponseError(_data)) {
                            hideMask();
                            refreshAffectedSegmentsByType('problem');
                            closeStagPopup();
                        }
                    }, 'json');
                    return false;
                });

            initStagSuggest();

            $('.additionReasonCategory_ui').trigger('change');

            @if(request()->input('dx'))
            parentSegment.find('input[stag-suggest][data-name="name"]')
                .val('{{request()->input('dx')}}')
                .trigger('keypress');
            @endif

        }

        addMCInitializer('problems-quick-add-{{$note->id}}', init)
    }).call(window);
</script>