<?php
$formID = rand(0, 100000);
?>
<div id="assessmentSection"
      onsubmit="return submitForm_NoteSection_{{ $formID }}(this);">
    <input type="hidden" name="count">
    <?php if($section): ?>
    <input type="hidden" name="section_uid" value="<?= $section->uid?>">
    <?php else: ?>
    <input type="hidden" name="note_uid" value="<?= $note->uid?>">
    <input type="hidden" name="section_template_uid" value="<?= $sectionTemplate->uid ?>">
    <?php endif; ?>

    <?php
    $dxInfoLines = \App\Models\ClientInfoLine::where('client_id', $patient->id)
        ->where('category', 'dx')
        ->where('is_removed', false)
        ->orderBy('content_text', 'asc')
        ->get();
    $dxRows = new \Illuminate\Support\Collection();
    foreach($dxInfoLines as $line) {
         if(@$line->contentDetail()->{"IsCurrent"} && intval($line->contentDetail()->{"IsCurrent"}) === 1) {
            $dxRows->add($line);
         }
    }
    ?>
    <div class="mb-3">
        <table class="bg-white table table-striped table-sm table-bordered mb-0" style="table-layout:fixed">
            <thead>
            <tr class="">
                <th class="px-2 text-secondary width-50px">
                    <label class="d-flex align-items-center c-pointer align-items-end m-0">
                        <input type="checkbox" class="mr-1"
                               v-model="includeAll" v-on:change="includeAllChanged()">
                        <span>All</span>
                    </label>
                </th>
                <th class="px-2 text-secondary w-50px">Title</th>
                <th class="px-2 text-secondary">ICD</th>
                <th class="px-2 text-secondary w-100px">Chr/Act</th>
                <th class="px-2 text-secondary width-200px">Prognosis</th>
                {{--<th class="px-2 text-secondary width-200px">History</th>--}}
                <th class="px-2 text-secondary width-200px">Goal</th>
                <th class="px-2 text-secondary width-200px">Plan</th>
                <th class="px-2 text-secondary delete-column">&nbsp;</th>
            </tr>
            </thead>
            <tbody>
            @foreach($dxRows as $line)
                <?php
                $isCurrent = @$line->contentDetail()->{"IsCurrent"} && intval(@$line->contentDetail()->{"IsCurrent"}) === 1;
                ?>
                <tr>
                    <td class="px-2">
                        <label class="d-block c-pointer m-0">
                            <input type="checkbox" class="mt-1"
                                   v-model="items['{{$line->uid}}'].included"
                                   v-on:change="includeChanged()">
                        </label>
                    </td>
                    <td class="px-2">{{$line->content_text}}</td>
                    <td class="px-2">{{ @$line->contentDetail()->{"ICD"} }}</td>
                    <td class="px-2">{{ @$line->contentDetail()->{"Chronic or Acute"} }}</td>
                    <td class="px-1">
                        <textarea rows="4"
                                  v-model="items['{{$line->uid}}'].prognosis"
                                  v-on:change="generatePayload()"
                                  class="form-control form-control-sm outline-0 width-100pc outline-0">
                        </textarea>
                    </td>
                    <td class="px-1">
                        <textarea rows="4"
                                  v-model="items['{{$line->uid}}'].goal"
                                  v-on:change="generatePayload()"
                                  class="form-control form-control-sm outline-0 width-100pc outline-0"></textarea>
                    </td>
                    <td class="px-1">
                        <textarea rows="4"
                                  v-model="items['{{$line->uid}}'].plan"
                                  v-on:change="generatePayload()"
                                  class="form-control form-control-sm outline-0 width-100pc outline-0"></textarea>
                    </td>
                    <td class="px-2 text-center delete-column">
                        <span moe wide relative class="mr-1">
                            <a class="on-hover-opaque" start show title="Edit">
                                <i class="font-size-11 fa fa-edit"></i>
                            </a>
                            <form url="/api/clientInfoLine/updateContent" right>
                                <p class="text-left mb-1"><b>Note: This will update this entry in the patient's main Dx list</b></p>
                                <input type="hidden" name="uid" value="{{ $line->uid }}">
                                <input type="hidden" name="clientUid" value="{{ $patient->uid }}">
                                <input type="hidden" name="category" value="dx">
                                <input type="hidden" name="IsCurrent" value="{{ $isCurrent ? 1 : 0 }}">
                                <div class="mb-2">
                                    <label for="" class="d-block text-sm mb-1 text-left">ICD</label>
                                    <input type="text" class="form-control form-control-sm" name="ICD"
                                           value="{{ @$line->contentDetail()->{"ICD"} }}" placeholder="">
                                </div>
                                <div class="mb-2">
                                    <label for="" class="d-block text-sm mb-1 text-left">Title</label>
                                    <input type="text" class="form-control form-control-sm" name="contentText"
                                           value="{{$line->content_text}}" placeholder="Title">
                                </div>
                                <div class="mb-2">
                                    <label for="" class="d-block text-sm mb-1 text-left">Chronic or Acute (select one)</label>
                                    <select name="Chronic or Acute" class="form-control form-control-sm pl-1">
                                        <option value="">Chronic or Acute (select one)</option>
                                        <option
                                            {{ @$line->contentDetail()->{"Chronic or Acute"} === 'Chronic' ? 'selected' : '' }} value="Chronic">Chronic</option>
                                        <option
                                            {{ @$line->contentDetail()->{"Chronic or Acute"} === 'Acute' ? 'selected' : '' }} value="Acute">Acute</option>
                                    </select>
                                </div>
                                <div class="mb-2">
                                    <label for="" class="d-block text-sm mb-1 text-left">Prognosis</label>
                                    <input type="text" class="form-control form-control-sm" name="Prognosis"
                                           value="{{ @$line->contentDetail()->{"Prognosis"} }}" placeholder="">
                                </div>
                                <div class="mb-2">
                                    <label for="" class="d-block text-sm mb-1 text-left">History</label>
                                    <textarea type="text" class="form-control form-control-sm" name="History"
                                              placeholder="">{{ @$line->contentDetail()->{"History"} }}</textarea>
                                </div>
                                <div class="mb-2">
                                    <label for="" class="d-block text-sm mb-1 text-left">Treatment Goal</label>
                                    <textarea type="text" class="form-control form-control-sm" name="Treatment Goal"
                                              placeholder="">{{ @$line->contentDetail()->{"Treatment Goal"} }}</textarea>
                                </div>
                                <div class="mb-2">
                                    <label for="" class="d-block text-sm mb-1 text-left">Treatment Plan</label>
                                    <textarea type="text" class="form-control form-control-sm" name="Treatment Plan"
                                              placeholder="">{{ @$line->contentDetail()->{"Treatment Plan"} }}</textarea>
                                </div>
                                <div class="d-flex align-items-center">
                                    <button class="btn btn-sm btn-primary mr-2" type="button" submit>Save</button>
                                    <button class="btn btn-sm btn-default mr-2 border" type="button"
                                            cancel>Cancel</button>
                                </div>
                            </form>
                        </span>
                        <span moe relative>
                            <a start show class="on-hover-opaque"><i class="fa fa-trash-alt text-danger"></i></a>
                            <form url="/api/clientInfoLine/remove" right>
                                <input type="hidden" name="uid" value="{{ $line->uid }}">
                                <p class="small text-left">Are you sure you want to delete this entry?</p>
                                <p class="small text-left"><b>Note: This will delete this entry from the patient's main Dx list</b></p>
                                <div class="d-flex align-items-center">
                                    <button class="btn btn-sm btn-danger mr-2" submit>Delete</button>
                                    <button class="btn btn-sm btn-default mr-2 border" cancel>Cancel</button>
                                </div>
                            </form>
                        </span>
                    </td>
                </tr>
            @endforeach

            </tbody>
        </table>
    </div>
    <form processed id="assessment_form_{{ $formID }}">
        <?php if($section): ?>
        <input type="hidden" name="section_uid" value="<?= $section->uid?>">
        <?php else: ?>
        <input type="hidden" name="note_uid" value="<?= $note->uid?>">
        <input type="hidden" name="section_template_uid" value="<?= $sectionTemplate->uid ?>">
        <?php endif; ?>
        <input type="hidden" name="items" v-model="payload">
    </form>
</div>
<script>

    (function() {

        function init() {

            <?php

                $contentData = false;
                if($section){
                    $contentData = json_decode($section->content_data, true);
                }
                if(!$contentData || !isset($contentData["items"])) {
                    $contentData = [
                        "items" => []
                    ];
                }
                else {
                    $contentData["items"] = json_decode($contentData["items"], true);
                }

                $plainRows = [];
                foreach($dxRows as $line) {

                    // use main data by default
                    $plainRows[$line->uid] = [
                        "included" => false,
                        "uid" => $line->uid,
                        "title" => $line->content_text,
                        "icd" => @$line->contentDetail()->{"ICD"},
                        "coa" => @$line->contentDetail()->{"Chronic or Acute"},
                        "prognosis" => @$line->contentDetail()->{"Prognosis"},
                        "history" => @$line->contentDetail()->{"History"},
                        "goal" => @$line->contentDetail()->{"Goal"},
                        "plan" => @$line->contentDetail()->{"Plan"},
                    ];

                    // overwrite with data saved in section if available
                    if(isset($contentData["items"]) && isset($contentData["items"][$line->uid])) {
                        $plainRows[$line->uid]["included"] = $contentData["items"][$line->uid]["included"];
                        $plainRows[$line->uid]["prognosis"] = $contentData["items"][$line->uid]["prognosis"];
                        $plainRows[$line->uid]["history"] = $contentData["items"][$line->uid]["history"];
                        $plainRows[$line->uid]["goal"] = $contentData["items"][$line->uid]["goal"];
                        $plainRows[$line->uid]["plan"] = $contentData["items"][$line->uid]["plan"];
                    }
                }

            ?>

            window.assessmentApp = new Vue({
                el: '#assessmentSection',
                data: {
                    includeAll: false,
                    items: {!! json_encode($plainRows)  !!},
                    payload: '',
                },
                methods: {
                    includeAllChanged: function() {
                        for(let x in this.items) {
                            if(this.items.hasOwnProperty(x)) {
                                this.items[x].included = this.includeAll;
                            }
                        }
                        this.generatePayload();
                    },
                    includeChanged: function() {
                        let all = true;
                        for(let x in this.items) {
                            if(this.items.hasOwnProperty(x)) {
                                if(!this.items[x].included) {
                                    all = false;
                                    break;
                                }
                            }
                        }
                        this.includeAll = all;
                        this.generatePayload();
                    },
                    generatePayload: function() {
                        let payload = {};
                        for(let x in this.items) {
                            if(this.items.hasOwnProperty(x)) {
                                payload[x] = {
                                    included: this.items[x].included,
                                    uid: this.items[x].uid,
                                    title: this.items[x].title,
                                    icd: this.items[x].icd,
                                    coa: this.items[x].coa,
                                    prognosis: this.items[x].prognosis,
                                    history: this.items[x].history,
                                    goal: this.items[x].goal,
                                    plan: this.items[x].plan,
                                }
                            }
                        }
                        this.payload = JSON.stringify(payload);
                    }
                },
                mounted: function() {
                    $('input[type="text"][name="ICD"]').each(function() {
                        var elem = this, dynID = 'icd-' + Math.ceil(Math.random() * 1000000);
                        $(elem).attr('id', dynID);
                        new window.Def.Autocompleter.Search(dynID,
                            'https://clinicaltables.nlm.nih.gov/api/icd10cm/v3/search?sf=code,name&ef=name',
                            {
                                tableFormat: true,
                                valueCols: [0],
                                colHeaders: ['Code', 'Name'],
                            }
                        );
                        window.Def.Autocompleter.Event.observeListSelections(dynID, function() {
                            var autocomp = elem.autocomp;
                            var name = autocomp.getSelectedItemData()[0].data['name'];
                            $(elem).closest('form').find('[name="contentText"]').val(name);
                            return false;
                        });
                    });

                    $('#assessmentSection [moe][initialized]').removeAttr('initialized');
                    initMoes();
                    this.includeChanged();
                    this.generatePayload();
                }
            });

        }
        addMCInitializer('assessment-section', init, '#assessmentSection');

    })();

</script>
