@extends ('layouts.patient')
@section('inner-content')
    <?php // $pro->pro_type = 'INDIVIDUAL'; ?>
    <link href="/select2/select2.min.css" rel="stylesheet" />
    <script src="/select2/select2.min.js"></script>
    <div id="programsComponent">
        <div class="d-flex align-items-center pb-3">
            <h4 class="font-weight-bold m-0">Programs</h4>
            {{-- add program --}}
            @if($pro->pro_type === 'ADMIN')
            <span class="mx-2 text-secondary">|</span>
            <div moe large>
                <a start show href="#">Add</a>
                <form url="/api/clientProgram/create">
                    <input type="hidden" name="clientUid" value="{{$patient->uid}}">
                    <div class="mb-2">
                        <label class="mb-1 text-sm text-secondary">Title</label>
                        <input type="text" name="title" value=""
                               class="form-control form-control-sm"
                               placeholder="Title" required>
                    </div>
                    <div class="mb-2">
                        <label class="mb-1 text-sm text-secondary">Measurement Types</label>
                        <input type="hidden" name="measurementLabels" v-model="newMeasurementLabels">
                        <select multiple add class="form-control form-control-sm">
                            <option value=""></option>
                            <option value="BP">Blood Pressure</option>
                            <option value="BS">Blood Sugar</option>
                            <option value="WEIGHT">Weight</option>
                        </select>
                    </div>
                    <div class="form-group mb-0">
                        <button class="btn btn-primary btn-sm mr-1" submit>Submit</button>
                        <button class="btn btn-default border btn-sm" cancel>Cancel</button>
                    </div>
                </form>
            </div>
            @endif
            <select class="ml-auto max-width-200px form-control form-control-sm"
                    onchange="fastLoad('/patients/view/{{$patient->uid}}/programs/' + this.value, true, false, false)">
                <option value="" {{ $filter === '' ? 'selected' : '' }}>Current Month</option>
                <option value="all" {{ $filter === 'all' ? 'selected' : '' }}>All Time</option>
            </select>
        </div>

        @foreach($patient->clientPrograms as $program)
        <?php
            $programCategories = explode('|', $program->measurement_labels);
            $programCategories = array_filter($programCategories, function($_item) {
                return !empty($_item);
            });
            $programICDs = explode('|', $program->icds);
            $programICDs = array_filter($programICDs, function($_item) {
                return !empty($_item);
            });
            $programMonth = null;
            if($filter === '') {
                $programMonth = $program->getProgramMonth(strtoupper(date('F')), date('Y'));
            }
        ?>
        <div class="card mb-4">

            <div class="card-header d-flex align-items-start px-3 py-2 border-bottom">
                <div class="pr-2">
                    <span class="mr-1 font-weight-bold">{{ $program->title }}</span>
                    @if($pro->pro_type === 'ADMIN')
                    <div moe>
                        <a href="#" show start class="on-hover-opaque"><i class="fa fa-edit"></i></a>
                        <form url="/api/clientProgram/updateTitle">
                            <input type="hidden" name="uid" value="{{ $program->uid }}">
                            <div class="mb-2">
                                <label class="mb-1 text-sm text-secondary">Program Title</label>
                                <input type="text" name="title"
                                       class="form-control form-control-sm"
                                       placeholder="Title" value="{{ $program->title }}" required>
                            </div>
                            <div class="form-group mb-0">
                                <button class="btn btn-primary btn-sm" submit>Submit</button>
                                <button class="btn btn-default border btn-sm" cancel>Cancel</button>
                            </div>
                        </form>
                    </div>
                    @endif
                </div>

                <div class="px-2 ml-auto border-right">
                    <div class="d-flex">
                        <span class="mr-2"><span class="text-secondary">MCP:</span>
                            {{ $program->mcp ? $program->mcp->displayName() : '-' }}
                        </span>
                        @if($pro->pro_type === 'ADMIN')
                        <div moe relative class="ml-auto">
                            <a href="#" show start class="on-hover-opaque"><i class="fa fa-edit"></i></a>
                            <form url="/api/clientProgram/changeMcp" right>
                                <input type="hidden" name="uid" value="{{ $program->uid }}">
                                <div class="mb-2">
                                    <label class="mb-1 text-sm text-secondary">Program MCP</label>
                                    <select name="newMcpProUid" class="form-control form-control-sm" provider-search >
                                        <option value="">-- Select MCP --</option>
                                        @foreach($pros as $iPro)
                                            <option value="{{ $iPro->uid }}" {{ $iPro->id === $program->mcp_pro_id ? 'selected' : ''  }}>
                                                {{ $iPro->displayName() }}
                                            </option>
                                        @endforeach
                                    </select>
                                </div>
                                <div class="mb-0">
                                    <button class="btn btn-primary btn-sm" submit>Submit</button>
                                    <button class="btn btn-default border btn-sm" cancel>Cancel</button>
                                </div>
                            </form>
                        </div>
                        @endif
                    </div>
                </div>

                <div class="pl-2">
                    <div class="d-flex">
                        <span class="mr-2"><span class="text-secondary">Manager:</span>
                            {{ $program->manager ? $program->manager->displayName() : '-' }}
                        </span>
                        @if($pro->pro_type === 'ADMIN')
                        <div moe relative class="ml-auto">
                            <a href="#" show start class="on-hover-opaque"><i class="fa fa-edit"></i></a>
                            <form url="/api/clientProgram/changeManager" right>
                                <input type="hidden" name="uid" value="{{ $program->uid }}">
                                <div class="mb-2">
                                    <label class="mb-1 text-sm text-secondary">Program Manager</label>
                                    <select name="newManagerProUid" class="form-control form-control-sm" provider-search >
                                        <option value="">-- Select Manager --</option>
                                        @foreach($pros as $iPro)
                                            <option value="{{ $iPro->uid }}" {{ $iPro->id === $program->manager_pro_id ? 'selected' : ''  }}>
                                                {{ $iPro->displayName() }}
                                            </option>
                                        @endforeach
                                    </select>
                                </div>
                                <div class="mb-0">
                                    <button class="btn btn-primary btn-sm" submit>Submit</button>
                                    <button class="btn btn-default border btn-sm" cancel>Cancel</button>
                                </div>
                            </form>
                        </div>
                        @endif
                    </div>
                </div>
            </div>

            <div class="card-body p-0">

                <div class="row">
                    <div class="col-4 pr-0 border-right">
                        <div class="">
                            {{-- setup --}}
                            <div class="border-bottom py-1 px-3">
                                <span class="mr-1 text-secondary">Setup</span>
                                @if($program->is_setup_complete === 'YES')
                                    <i class="fa fa-check text-success"></i>
                                @else
                                    <i class="fa fa-exclamation-triangle text-warning"></i>
                                @endif
                                @if($pro->pro_type === 'ADMIN')
                                <div moe relative class="ml-1">
                                    <a start show class="py-0 font-weight-normal on-hover-opaque"><i class="fa fa-edit"></i></a>
                                    <form url="/api/clientProgram/editSetupInfo">
                                        <input type="hidden" name="uid" value="{{ $program->uid }}">
                                        <div class="mb-2">
                                            <label class="text-sm mb-1 text-secondary">Setup Status</label>
                                            <select class="form-control form-control-sm bg-light" name="isSetupComplete" required>
                                                <option value="">-- select --</option>
                                                <option value="YES" {{ $program->is_setup_complete === 'YES' ? 'selected' : '' }}>Yes</option>
                                                <option value="NO" {{ $program->is_setup_complete === 'NO' ? 'selected' : '' }}>No</option>
                                                <option value="UNKNOWN" {{ $program->is_setup_complete === 'UNKNOWN' ? 'selected' : '' }}>Unknown</option>
                                            </select>
                                        </div>
                                        <div class="mb-2">
                                            <label class="text-sm mb-1 text-secondary">Setup Status Memo</label>
                                            <textarea class="form-control form-control-sm" rows="2" name="setupStatusMemo" value="{{ $program->setup_status_memo }}" placeholder="Memo"></textarea>
                                        </div>
                                        <div class="mb-2">
                                            <label class="text-sm mb-1 text-secondary">Setup Detail</label>
                                            <textarea class="form-control form-control-sm" rows="2" name="setupDetail" value="{{ $program->setup_detail }}" placeholder="Detail"></textarea>
                                        </div>
                                        <div class="mb-2">
                                            <label class="text-sm mb-1 text-secondary">Device Identifier</label>
                                            <input type="text" class="form-control form-control-sm" name="deviceIdentifier" value="{{ $program->device_identifier }}" placeholder="Device ID">
                                        </div>
                                        <div class="d-flex align-items-center">
                                            <button class="btn btn-sm btn-primary mr-2" submit>Ok</button>
                                            <button class="btn btn-sm btn-default mr-2 border" cancel>Cancel</button>
                                        </div>
                                    </form>
                                </div>
                                @endif
                            </div>

                            {{-- onboarding --}}
                            <div class="border-bottom py-1 px-3">
                                <span class="mr-1 text-secondary">Onboarding</span>
                                @if($program->has_mcp_done_onboarding_visit === 'YES')
                                    <i class="fa fa-check text-success"></i>
                                @else
                                    <i class="fa fa-exclamation-triangle text-warning"></i>
                                @endif
                                @if($pro->pro_type === 'ADMIN')
                                <div moe relative class="ml-1">
                                    <a start show class="py-0 font-weight-normal on-hover-opaque"><i class="fa fa-edit"></i></a>
                                    <form url="/api/clientProgram/editMcpOnboardingVisitInfo">
                                        <input type="hidden" name="uid" value="{{ $program->uid }}">
                                        <div class="mb-2">
                                            <label class="text-sm mb-1 text-secondary">OB Visit Done?</label>
                                            <select class="form-control form-control-sm bg-light" name="hasMcpDoneOnboardingVisit" required>
                                                <option value="">-- select --</option>
                                                <option value="YES" {{ $program->has_mcp_done_onboarding_visit === 'YES' ? 'selected' : '' }}>Yes</option>
                                                <option value="NO" {{ $program->has_mcp_done_onboarding_visit === 'NO' ? 'selected' : '' }}>No</option>
                                                <option value="UNKNOWN" {{ $program->has_mcp_done_onboarding_visit === 'UNKNOWN' ? 'selected' : '' }}>Unknown</option>
                                            </select>
                                        </div>
                                        <div class="mb-2">
                                            <label class="text-sm mb-1 text-secondary">Date</label>
                                            <input type="date" class="form-control form-control-sm" name="mcpOnboardingVisitDate" value="{{ $program->mcp_onboarding_visit_date }}" placeholder="">
                                        </div>
                                        <div class="d-flex align-items-center">
                                            <button class="btn btn-sm btn-primary mr-2" submit>Ok</button>
                                            <button class="btn btn-sm btn-default mr-2 border" cancel>Cancel</button>
                                        </div>
                                    </form>
                                </div>
                                @endif
                            </div>

                            {{-- measurement labels --}}
                            <div class="border-bottom py-1 px-3">
                                <div class="d-flex">
                                    <span class="mr-2 text-secondary">Measurement Types: </span>
                                    <?php
                                    $labels = '-';
                                    if ($programCategories && count($programCategories)) {
                                        $labels = implode(", ", $programCategories);
                                    }
                                    ?>
                                    <span class="mr-2">{{ $labels }}</span>
                                    @if($pro->pro_type === 'ADMIN')
                                    <div moe large>
                                        <a href="#" show start class="on-hover-opaque"><i class="fa fa-edit"></i></a>
                                        <form url="/api/clientProgram/updateCategories">
                                            <input type="hidden" name="uid" value="{{ $program->uid }}">
                                            <div class="mb-2">
                                                <label class="mb-1 text-sm text-secondary">Measurement Types</label>
                                                <input type="hidden" name="measurementLabels" v-model="existingMeasurementLabels['{{ $program->uid }}']">
                                                <select multiple edit class="form-control form-control-sm" data-uid="{{ $program->uid }}">
                                                    <option value=""></option>
                                                    <option value="BP" {{ strpos($program->measurement_labels, "|BP|") !== FALSE ? 'selected' : '' }}>Blood Pressure</option>
                                                    <option value="BS" {{ strpos($program->measurement_labels, "|BS|") !== FALSE ? 'selected' : '' }}>Blood Sugar</option>
                                                    <option value="WEIGHT" {{ strpos($program->measurement_labels, "|WEIGHT|") !== FALSE ? 'selected' : '' }}>Weight</option>
                                                </select>
                                            </div>
                                            <div class="mb-0">
                                                <button class="btn btn-primary btn-sm" submit="">Submit</button>
                                                <button class="btn btn-default border btn-sm" cancel="">Cancel</button>
                                            </div>
                                        </form>
                                    </div>
                                    @endif
                                </div>
                            </div>

                            {{-- icds --}}
                            <div class="border-bottom py-1 px-3">
                                <div class="d-flex">
                                    <span class="mr-2 text-secondary">ICDs: </span>
                                    <?php
                                    $labels = '-';
                                    if ($programICDs && count($programICDs)) {
                                        $labels = implode(", ", $programICDs);
                                    }
                                    ?>
                                    <span class="mr-2">{{ $labels }}</span>
                                    @if($pro->pro_type === 'ADMIN')
                                    <div moe large>
                                        <a href="#" show start class="on-hover-opaque"><i class="fa fa-edit"></i></a>
                                        <form url="/api/clientProgram/updateIcds">
                                            <input type="hidden" name="uid" value="{{ $program->uid }}">
                                            <input type="hidden" name="icds" v-model="existingICDsFlattened['{{ $program->uid }}']">
                                            <div class="mb-2">
                                                <label class="mb-1 text-sm text-secondary">ICDs
                                                    <a href="#" class="ml-3"
                                                       v-on:click.prevent="addICDItem('{{ $program->uid }}')">+ Add</a>
                                                </label>
                                                <div v-for="(icd, index) in existingICDs['{{ $program->uid }}']" class="d-flex align-items-center mb-2">
                                                    <input required type="text"
                                                           data-field="icd" data-program="{{ $program->uid }}" :data-index="index"
                                                           v-model="existingICDs['{{ $program->uid }}'][index]"
                                                           class="form-control form-control-sm flex-grow-1">
                                                    <a v-if="existingICDs['{{ $program->uid }}'].length > 1"
                                                       class="on-hover-opaque text-danger ml-2"
                                                       v-on:click.prevent="existingICDs['{{ $program->uid }}'].splice(index, 1)">
                                                        <i class="fa fa-trash-alt"></i>
                                                    </a>
                                                </div>
                                            </div>
                                            <div class="mb-0">
                                                <button class="btn btn-primary btn-sm" submit="">Submit</button>
                                                <button class="btn btn-default border btn-sm" cancel="">Cancel</button>
                                            </div>
                                        </form>
                                    </div>
                                    @endif
                                </div>
                            </div>

                            {{-- work spec --}}
                            <div class="py-1 px-3">
                                <div class="d-flex">
                                    <span class="mr-2 text-secondary">Work Spec: </span>
                                    <span class="mr-2 font-weight-bold">{{ $program->min_monthly_time_in_minutes }}m - {{ $program->max_monthly_time_in_minutes }}m</span>
                                    @if($pro->pro_type === 'ADMIN')
                                    <div moe>
                                        <a start show class="py-0 font-weight-normal on-hover-opaque"><i class="fa fa-edit"></i></a>
                                        <form url="/api/clientProgram/editWorkSpec">
                                            <input type="hidden" name="uid" value="{{ $program->uid }}">
                                            <div class="mb-2">
                                                <label class="text-sm mb-1 text-secondary">Min Monthly Time (minutes)</label>
                                                <input type="number" class="form-control form-control-sm" name="minMonthlyTimeInMinutes" value="{{ $program->min_monthly_time_in_minutes }}" placeholder="">
                                            </div>
                                            <div class="mb-2">
                                                <label class="text-sm mb-1 text-secondary">Max Monthly Time (minutes)</label>
                                                <input type="number" class="form-control form-control-sm" name="maxMonthlyTimeInMinutes" value="{{ $program->max_monthly_time_in_minutes }}" placeholder="">
                                            </div>
                                            <div class="mb-2">
                                                <label class="text-sm mb-1 text-secondary">Time In Minutes Memo</label>
                                                <textarea class="form-control form-control-sm" rows="2" name="timeInMinutesMemo" value="{{ $program->time_in_minutes_memo }}" placeholder=""></textarea>
                                            </div>
                                            <div class="mb-2">
                                                <label class="text-sm mb-1 text-secondary">Goal</label>
                                                <textarea class="form-control form-control-sm" rows="2" name="goal" value="{{ $program->goal }}" placeholder=""></textarea>
                                            </div>
                                            <div class="mb-2">
                                                <label class="text-sm mb-1 text-secondary">Sticky Note</label>
                                                <textarea class="form-control form-control-sm" rows="2" name="stickyNote" value="{{ $program->sticky_note }}" placeholder=""></textarea>
                                            </div>
                                            <div class="mb-2">
                                                <label class="mb-1 text-secondary d-flex align-items-center">
                                                    <span class="mr-2">Change Current Month</span>
                                                    <input type="checkbox" name="changeCurrentMonth">
                                                </label>
                                            </div>
                                            <div class="d-flex align-items-center">
                                                <button class="btn btn-sm btn-primary mr-2" submit>Ok</button>
                                                <button class="btn btn-sm btn-default mr-2 border" cancel>Cancel</button>
                                            </div>
                                        </form>
                                    </div>
                                    @endif
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-8 pl-0">
                        <div class="border-bottom py-1 px-2 bg-light d-flex">
                            <span class="font-weight-bold">Measurements</span>
                            @if($programCategories && count($programCategories))
                                <div class="d-inline-flex">
                                @foreach($programCategories as $category)
                                    <span class="mx-2 text-secondary">|</span>
                                    <div moe relative>
                                        <a href="#" start show>+ {{ $category }}</a>
                                        <form url="/api/measurement/create">
                                            <input type="hidden" name="clientUid" value="{{ $patient->uid }}">
                                            <input type="hidden" name="label" value="{{ $category }}">
                                            <div class="mb-2">
                                                <label class="text-sm text-secondary mb-1 font-weight-bold">{{ $category }}</label>
                                                <input required autofocus type="text" class="form-control form-control-sm"
                                                       name="value" placeholder="Value">
                                            </div>
                                            <div class="mb-2">
                                                <input required type="date" class="form-control form-control-sm"
                                                       name="effectiveDate" max="{{ date('Y-m-d') }}" value="{{ date('Y-m-d') }}">
                                            </div>
                                            <div class="d-flex align-items-center">
                                                <button class="btn btn-sm btn-primary mr-2" submit>Save</button>
                                                <button class="btn btn-sm btn-default mr-2 border" cancel>Cancel</button>
                                            </div>
                                        </form>
                                    </div>
                                @endforeach
                                </div>
                            @endif
                            @if(!!$programMonth)
                                <div class="ml-auto pr-2">
                                    <b>{{ minutes_to_hhmm($programMonth->time_in_minutes) }}</b> billed,
                                    <b>{{ minutes_to_hhmm($program->max_monthly_time_in_minutes - $programMonth->time_in_minutes) }}</b> remaining
                                </div>
                            @endif
                        </div>
                        <?php
                        $programMeasurements = [];
                        foreach($patient->allMeasurements as $measurement) {
                            $measurementED = strtotime($measurement->effective_date);
                            if(in_array($measurement->label, $programCategories) !== FALSE) {
                                if($filter === 'all' ||
                                    (date('Y') === date('Y', $measurementED) && date('m') === date('m', $measurementED))) {
                                    $programMeasurements[] = $measurement;
                                }
                            }
                        }
                        ?>
                        @foreach($programMeasurements as $measurement)
                            <?php $minutes = $measurement->minutesEntered($pro); ?>
                            @include('app/patient/partials/measurement', ['measurement' => $measurement, 'child' => false])
                            @foreach($measurement->childMeasurements() as $childMeasurement)
                                @include('app/patient/partials/measurement', ['measurement' => $childMeasurement, 'child' => true])
                            @endforeach
                        @endforeach
                        @if(!count($programMeasurements))
                            <div class="text-secondary py-1 px-2 border-0">
                                No measurements to show
                            </div>
                        @endif
                    </div>
                </div>

            </div>

        </div>
        @endforeach

    </div>

    <script>
        <?php
            $measurementLabels = [];
            foreach($patient->clientPrograms as $program) {
                $measurementLabels[$program->uid] = $program->measurement_labels;
            }
            $icds = [];
            $icdsFlattened = [];
            foreach($patient->clientPrograms as $program) {
                $icds[$program->uid] = array_values(array_filter(explode("|", $program->icds), function($_item) {
                    return !empty($_item);
                }));
                $icdsFlattened[$program->uid] = $program->icds;
            }
        ?>
        (function() {
            function init() {
                window.programsComponent = new Vue({
                    el: '#programsComponent',
                    delimiters: ['@{{', '}}'],
                    data: {
                        newMeasurementLabels: '',
                        existingMeasurementLabels: <?= json_encode($measurementLabels) ?>,
                        existingICDs: <?= json_encode($icds) ?>,
                        existingICDsFlattened: <?= json_encode($icdsFlattened) ?>,
                    },
                    methods: {
                        combine: function(_array) {
                            if(!_array || !_array.length) return '';
                            let valid = _array.filter(function(_x) {
                                return !!_x;
                            });
                            if(!valid || !valid.length) return '';
                            return '|' + valid.join('|') + '|';
                        },
                        addICDItem: function(_programUid) {
                            this.existingICDs[_programUid].push('');
                            let self = this;
                            Vue.nextTick(function() {
                                self.initICDAutoSuggest();
                            });
                        },
                        initICDAutoSuggest: function() {
                            let self = this;
                            $('#programsComponent input[type="text"][data-field="icd"]:not([ac-initialized])').each(function() {
                                var elem = this,
                                    dynID = 'icd-' + Math.ceil(Math.random() * 1000000),
                                    vueIndex = $(this).attr('data-index');
                                $(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() {
                                    let autocomp = elem.autocomp, acData = autocomp.getSelectedItemData();
                                    self.existingICDs[$(elem).attr('data-program')][+$(elem).attr('data-index')] = acData[0].code;
                                    self.existingICDsFlattened[$(elem).attr('data-program')] = self.combine(self.existingICDs[$(elem).attr('data-program')]);
                                    return false;
                                });
                                $(elem).attr('ac-initialized', 1);
                            });
                        },
                    },
                    watch: {
                        existingICDs: {
                            handler: function(val, oldVal) {
                                let self = this;
                                for(let x in this.existingICDs) {
                                    if(this.existingICDs.hasOwnProperty(x)) {
                                        this.existingICDsFlattened[x] = this.combine(this.existingICDs[x]);
                                    }
                                }
                            },
                            deep: true
                        }
                    },
                    mounted: function() {
                        let self = this;
                        $('#programsComponent [moe][initialized]').removeAttr('initialized');
                        initMoes();
                        $('select[multiple][add]')
                            .select2({
                                width: '100%',
                                placeholder: '-- select --'
                            })
                            .on('change', function() {
                                if($(this).val() && $(this).val().length) {
                                    self.newMeasurementLabels = '|' + $(this).val().join('|') + '|';
                                }
                                else {
                                    self.newMeasurementLabels = '';
                                }
                            });
                        $('select[multiple][edit]')
                            .select2({
                                width: '100%',
                                placeholder: '-- select --'
                            })
                            .on('change', function() {
                                if($(this).val() && $(this).val().length) {
                                    self.existingMeasurementLabels[$(this).attr('data-uid')] = '|' + $(this).val().join('|') + '|';
                                }
                                else {
                                    self.existingMeasurementLabels[$(this).attr('data-uid')] = '';
                                }
                            });

                        // give 1 row min for editing
                        for(let x in this.existingICDs) {
                            if(this.existingICDs.hasOwnProperty(x)) {
                                if(!this.existingICDs[x] || !this.existingICDs[x].length || !Array.isArray(this.existingICDs[x])) {
                                    this.existingICDs[x] = [''];
                                }
                            }
                        }

                        Vue.nextTick(function() {
                            self.initICDAutoSuggest();
                        });

                    }
                });
            }
            addMCInitializer('programs', init, '#programsComponent');
        })();
    </script>
@endsection
