<?php

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

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

$medications = Point::getIntakePointsOfCategory($patient, 'MEDICATION', $note);

?>
<div>

    <div class="d-flex mb-2">
        <table class="table table-sm table-bordered table-striped mb-0 bg-white">
            <thead>
            <tr class="">
                <th class="border-bottom-0">Medication</th>
                <th class="border-bottom-0">Most Recent Subjective</th>
                <th class="border-bottom-0">Most Recent Plan</th>
            </tr>
            </thead>
            <?php foreach($medications as $medication): ?>
                <tr>
                    <td>
                        <div class="d-flex align-items-baseline">
                            <div class="<?= $medication->is_removed ? 'strike-through' : '' ?>">
                                <b><?= !!@($medication->data->name) ? @($medication->data->name) : '-' ?></b>
                                <?= !!@($medication->data->route) ? '/&nbsp;' . @($medication->data->route) : '' ?>
                                <?= !!@($medication->data->dose) ? '/&nbsp;' . @($medication->data->dose) : '' ?>
                                <?= !!@($medication->data->strength) ? '/&nbsp;' . @($medication->data->strength) : '' ?>
                                <?= !!@($medication->data->frequency) ? '/&nbsp;' . @($medication->data->frequency) : '' ?>
                            </div>

                            <!-- common actions -->
                            <div class="ml-auto d-inline-flex align-items-baseline pr-2">
                                <?php
                                $point = $medication;
                                $label = 'Medication';
                                include resource_path('views/app/patient/segment-templates/_common_actions/remove-undo.php');
                                ?>
                            </div>
                        </div>
                    </td>
                    <td>
                        <div class="d-flex align-items-start">
                            <div class="flex-grow-1">
                                <?php
                                $point = $medication;
                                include resource_path('views/app/patient/segment-templates/_child_review/last-review.php');
                                ?>
                            </div>
                            <a class="px-1 view-review-log"
                               native target="_blank"
                               open-in-stag-popup
                               popup-style="stag-popup-md"
                               title="Subjective log<?= !!@($medication->data->name) ? ' for ' . @($medication->data->name) : '' ?>"
                               href="/point/review-log/<?= $medication->uid ?>?popupmode=1">
                                <i class="fa fa-history"></i>
                            </a>
                        </div>
                    </td>
                    <td>
                        <div class="d-flex align-items-start">
                            <div class="flex-grow-1">
                                <?php
                                $point = $medication;
                                include resource_path('views/app/patient/segment-templates/_child_plan/last-plan.php');
                                ?>
                            </div>
                            <a class="px-1 view-review-log"
                               native target="_blank"
                               open-in-stag-popup
                               popup-style="stag-popup-md"
                               title="Plan log<?= !!@($medication->data->name) ? ' for ' . @($medication->data->name) : '' ?>"
                               href="/point/plan-log/<?= $medication->uid ?>?popupmode=1">
                                <i class="fa fa-history"></i>
                            </a>
                        </div>
                    </td>
                </tr>
            <?php endforeach; ?>
        </table>
    </div>

    <div visit-moe large class="mt-1">
        <a href="#" start show class="btn btn-sm btn btn-outline-primary">+ Add medication patient is ALREADY taking, prior to this visit</a>
        <form url="/api/visitPoint/addTopLevelOnIntake" class="mcp-theme-1">
            <input type="hidden" name="segmentUid" value="<?= $segment->uid ?>">
            <input type="hidden" name="category" value="MEDICATION">
            <input type="hidden" name="data">

            <input type="hidden" data-name="medNameId">
            <input type="hidden" data-name="route">
            <input type="hidden" data-name="dose">
            <input type="hidden" data-name="strength">
            <input type="hidden" data-name="medId">

            <p class="mb-2"><b>Add Medication (on intake)</b></p>

            <div class="mb-2">
                <label class="text-sm text-secondary mb-1">Name</label>
                <input type="text"
                       data-name="name"
                       class="form-control form-control-sm"
                       stag-suggest
                       stag-suggest-ep="/fdb-med-suggest/json">
            </div>
            <div class="mb-2">
                <label class="text-sm text-secondary mb-1">Route</label>
                <select data-name="routedMedId"
                        class="form-control form-control-sm"
                        disabled>
                </select>
            </div>
            <div class="mb-2">
                <label class="text-sm text-secondary mb-1">Dosage</label>
                <select data-name="routedDosageFormMedId"
                        class="form-control form-control-sm"
                        disabled>
                </select>
            </div>
            <div class="mb-2">
                <label class="text-sm text-secondary mb-1">Strength</label>
                <select data-name="gcnSeqno"
                        class="form-control form-control-sm"
                        disabled>
                </select>
            </div>
            <div class="mb-2">
                <label class="text-sm text-secondary mb-1">Frequency</label>
                <input type="text" class="form-control form-control-sm" data-name="frequency"
                       data-option-list="frequency-options" autocomplete="off">
                <div id="frequency-options" class="data-option-list">
                    <div>Once a day</div>
                    <div>Twice a day</div>
                </div>
            </div>
            <div class="mb-2">
                <label class="text-sm text-secondary mb-1">Description</label>
                <textarea type="text" data-name="description" class="form-control form-control-sm"></textarea>
            </div>

            <div>
                <button submit class="btn btn-sm btn-primary mr-2">Submit</button>
                <button cancel class="btn btn-sm btn-default border">Cancel</button>
            </div>
        </form>
    </div>
</div>


<script>
    window.segmentInitializers.<?= $segment->segmentTemplate->internal_name ?> = function() {
        // any JS can come here
        // will be run on page-load as well as whenever this segment is refreshed

        let parentSegment = $('[data-segment-template-name="<?= $segment->segmentTemplate->internal_name ?>"] ');
        parentSegment.find('input[stag-suggest][data-name="name"]')
            .off('stag-suggest-selected')
            .on('stag-suggest-selected', (_e, _input, _data) => {

                // _input is the textbox
                // _data is {med_name_id: "50567", text: "Children's Tylenol"}

                let medNameID = _data.med_name_id;
                parentSegment.find('input[data-name="medNameId"]').val(medNameID);

                let routeSelect = parentSegment.find('[data-name="routedMedId"]').empty().prop('disabled', true);
                let dosageSelect = parentSegment.find('[data-name="routedDosageFormMedId"]').empty().prop('disabled', true);
                let strengthSelect = parentSegment.find('[data-name="gcnSeqno"]').empty().prop('disabled', true);

                $.get('/fdb-routed-meds?med-name-id=' + medNameID, _data => {
                    routeSelect
                        .empty()
                        .append('<option value="">-- select --</option>');
                    for (let i = 0; i < _data.length; i++) {
                        routeSelect.append('<option value="' + _data[i].routed_med_id + '">' + _data[i].med_routed_med_id_desc + '</option>')
                    }
                    routeSelect.prop('disabled', false);
                    if(_data.length === 1) {
                        routeSelect.val(_data[0].routed_med_id).trigger('change');
                    }
                }, 'json');
            });

        // on route selection
        $(document).off('change', '[data-segment-template-name="<?= $segment->segmentTemplate->internal_name ?>"] [data-name="routedMedId"]');
        $(document).on('change', '[data-segment-template-name="<?= $segment->segmentTemplate->internal_name ?>"] [data-name="routedMedId"]', function () {

            // clear
            let dosageSelect = parentSegment.find('[data-name="routedDosageFormMedId"]').empty().prop('disabled', true);
            let strengthSelect = parentSegment.find('[data-name="gcnSeqno"]').empty().prop('disabled', true);
            let routedMedID = $(this).val();
            parentSegment.find('input[data-name="route"]').val($(this).find('option:selected').text());

            $.get('/fdb-routed-dosages?routed-med-id=' + routedMedID, _data => {
                dosageSelect
                    .empty()
                    .append('<option value="">-- select --</option>');
                for (let i = 0; i < _data.length; i++) {
                    dosageSelect.append('<option value="' + _data[i].routed_dosage_form_med_id + '">' + _data[i].med_routed_df_med_id_desc + '</option>')
                }
                dosageSelect.prop('disabled', false);
                if(_data.length === 1) {
                    dosageSelect.val(_data[0].routed_dosage_form_med_id).trigger('change');
                }
            }, 'json');
        });

        // on dosage selection
        $(document).off('change', '[data-segment-template-name="<?= $segment->segmentTemplate->internal_name ?>"] [data-name="routedDosageFormMedId"]');
        $(document).on('change', '[data-segment-template-name="<?= $segment->segmentTemplate->internal_name ?>"] [data-name="routedDosageFormMedId"]', function () {

            // clear
            let strengthSelect = parentSegment.find('[data-name="gcnSeqno"]').empty().prop('disabled', true);
            let dosageFormMedID = $(this).val();
            parentSegment.find('input[data-name="dose"]').val($(this).find('option:selected').text());

            $.get('/fdb-meds?dosage-form-med-id=' + dosageFormMedID, _data => {
                strengthSelect
                    .empty()
                    .append('<option value="">-- select --</option>');
                for (let i = 0; i < _data.length; i++) {
                    strengthSelect.append('<option data-medid="' + _data[i].medid + '" value="' + _data[i].gcn_seqno + '">' + _data[i].med_medid_desc + '</option>')
                }
                strengthSelect.prop('disabled', false);
                if(_data.length === 1) {
                    strengthSelect.val(_data[0].gcn_seqno).trigger('change');
                    $('input[data-name="description"]').focus();
                }
            }, 'json');
        });

        // on strength (medid) selection
        $(document).off('change', '[data-segment-template-name="<?= $segment->segmentTemplate->internal_name ?>"] [data-name="gcnSeqno"]');
        $(document).on('change', '[data-segment-template-name="<?= $segment->segmentTemplate->internal_name ?>"] [data-name="gcnSeqno"]', function () {

            parentSegment.find('input[data-name="medId"]').val($(this).find('option:selected').attr('data-medid'));
            parentSegment.find('input[data-name="strength"]').val($(this).find('option:selected').text());

        });

    };
</script>

