@extends ('layouts.template')

@section('content')
<div class="p-3">
    <div class="m-0 mt-4">
        <div class="row mcp-theme-1" id="pro-dashboard-container" v-cloak>
            <div class="col-md-3 mcp-theme-1">
                <div class="mb-4" v-show="tab==='appointments'">
                    <div class="pro-dashboard-inline-calendar"></div>
                </div>
                <div class="card mb-4">
                    <div class="card-header pl-2">
                        <strong>
                            Key Numbers
                        </strong>
                    </div>
                    <div class="card-body p-0">
                        <table class="table mb-0">
                            <tbody>
                                <tr>
                                    <th class="border-top-0 px-2 text-center">{{$keyNumbers['totalPatients']}}</th>
                                    <th class="border-top-0 pl-2"><a href="/patients">Total patients</a></th>
                                </tr>
                                <tr>
                                    <th class="px-2 text-center">{{$keyNumbers['patientsNotSeenYet']}}</th>
                                    <th class="pl-2"><a href="/patients/not-yet-seen">Patients I have not seen yet</a></th>
                                </tr>
                                <tr>
                                    <th class="px-2 text-center">{{$keyNumbers['pendingBillsToSign']}}</th>
                                    <th class="pl-2"><a href="/practice-management/bills/not-yet-signed">Pending bills to sign</a></th>
                                </tr>
                                <tr>
                                    <th class="px-2 text-center">{{$keyNumbers['pendingNotesToSign']}}</th>
                                    <th class="pl-2"><a href="/practice-management/notes/not-yet-signed">Pending notes to sign</a></th>
                                </tr>
                                <tr>
                                    <th class="px-2 text-center">{{$keyNumbers['numOpenTickets']}}</th>
                                    <th class="pl-2"><a href="/practice-management/my-tickets/open">Open tickets</a></th>
                                </tr>
                                <tr>
                                    <th class="px-2 text-center">{{$keyNumbers['measurementsToBeStamped']}}</th>
                                    <th class="pl-2">
                                        <a native target="_top"
                                           href="#"
                                           v-on:click.prevent="tab='measurements'">Unstamped Measurements</a>
                                    </th>
                                </tr>
                                <tr>
                                    <th class="px-2 text-center">{{$keyNumbers['unacknowledgedCancelledBills']}}</th>
                                    <th class="pl-2">
                                        <a href="/practice-management/unacknowledged-cancelled-bills">Unacknowledged Cancelled Bills</a>
                                    </th>
                                </tr>
                                <tr>
                                    <th class="px-2 text-center">{{$keyNumbers['patientsHavingBirthdayToday']}}</th>
                                    <th class="pl-2">
                                        <a href="/patients/having-birthday-today">Patients having birthday today</a>
                                    </th>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="card mb-4">
                    <div class="card-header pl-2">
                        <strong>
                            Reimbursement
                        </strong>
                    </div>
                    <div class="card-body p-0">
                        <table class="table mb-0">
                            <tbody>
                                <tr>
                                    <th class="border-top-0 px-2">${{friendly_money($reimbursement['currentBalance'])}}</th>
                                    <th class="border-top-0 pl-2 w-100"><a href="/practice-management/financial-transactions">Current balance</a></th>
                                </tr>
                                <!-- <tr>
                                    <th class="px-2">{{friendly_date_time($reimbursement['nextPaymentDate'], false)}}</th>
                                    <th class="pl-2">Next Payment Date</th>
                                </tr> -->
                                <tr>
                                    <th class="px-2">${{friendly_money($reimbursement['nextPaymentAmount'])}}</th>
                                    <th class="pl-2">Processing</th>
                                </tr>
                                {{--
                                <tr>
                                    <th class="px-2">{{$reimbursement['lastPayment']}}</th>
                                    <th class="pl-2"><a href="/practice-management/financial-transactions">Last payment</a></th>
                                </tr>
                                <tr>
                                    <th class="px-2">{{friendly_date_time($reimbursement['lastPaymentDate'], false)}}</th>
                                    <th class="pl-2"><a href="/practice-management/financial-transactions">Last payment date</a></th>
                                </tr>
                                --}}
                            </tbody>
                        </table>
                    </div>
                </div>
                @if($pro->pro_type === 'ADMIN')
                <div class="card mb-4">
                    <div class="card-header pl-2">
                        <strong>
                            Bills &amp; Claims
                        </strong>
                    </div>
                    <div class="card-body p-0">
                        <table class="table mb-0">
                            <tbody>
                            <tr>
                                <th class="border-top-0 px-2 text-center">{{$businessNumbers['notesWithBillsToResolve']}}</th>
                                <th class="border-top-0 pl-2">
                                    <a href="/practice-management/billing-manager">Notes with bills to resolve</a>
                                </th>
                            </tr>
                            <tr>
                                <th class="border-top-0 px-2 text-center">{{$businessNumbers['notesPendingBillingClosure']}}</th>
                                <th class="border-top-0 pl-2">
                                    <a href="/practice-management/billing-manager">Notes pending billing closure</a>
                                </th>
                            </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
                @endif
            </div>
            <div class="col-md-9">

                <ul class="nav nav-tabs">
                    <li class="nav-item">
                        <a native data-tab="appointments" class="nav-link"
                           :class="tab == 'appointments' ? 'active' : ''" href="#"
                           v-on:click.prevent="tab='appointments'; initLoadAppointments();">
                            Appointments
                        </a>
                    </li>
                    <li class="nav-item">
                        <a native data-tab="measurements" class="nav-link"
                           :class="tab == 'measurements' ? 'active' : ''" href="#"
                           v-on:click.prevent="tab='measurements'">
                            Measurements
                        </a>
                    </li>
                    <li class="nav-item">
                        <a native data-tab="incoming_reports" class="nav-link {{count($incomingReports) ? 'text-danger font-weight-bold' : ''}}"
                           :class="tab == 'incoming_reports' ? 'active' : ''" href="#"
                           v-on:click.prevent="tab='incoming_reports'">
                            Incoming Reports ({{count($incomingReports)}})
                        </a>
                    </li>
                    <li class="nav-item">
                        <a native data-tab="erx" class="nav-link {{$numERx ? 'text-danger font-weight-bold' : ''}}"
                           :class="tab == 'erx' ? 'active' : ''" href="#"
                           v-on:click.prevent="tab='erx'">
                            ERx ({{$numERx}})
                        </a>
                    </li>
                    <li class="nav-item">
                        <a native data-tab="labs" class="nav-link {{$numLabs ? 'text-danger font-weight-bold' : ''}}"
                           :class="tab == 'labs' ? 'active' : ''" href="#"
                           v-on:click.prevent="tab='labs'">
                            Labs ({{$numLabs}})
                        </a>
                    </li>
                    <li class="nav-item">
                        <a native data-tab="imaging" class="nav-link {{$numImaging ? 'text-danger font-weight-bold' : ''}}"
                           :class="tab == 'imaging' ? 'active' : ''" href="#"
                           v-on:click.prevent="tab='imaging'">
                            Imaging ({{$numImaging}})
                        </a>
                    </li>
                    <li class="nav-item">
                        <a native data-tab="supply_orders" class="nav-link {{$numSupplyOrders ? 'text-danger font-weight-bold' : ''}}"
                           :class="tab == 'supply_orders' ? 'active' : ''" href="#"
                           v-on:click.prevent="tab='supply_orders'">
                            Supply Orders ({{$numSupplyOrders}})
                        </a>
                    </li>
                </ul>

                <div class="border-left border-right border-bottom p-3">
                    <div v-show="tab==='appointments'">
                        <div class="d-flex align-items-end mb-3">
                            <b class="large"><span class="text-secondary">Today:</span> @{{ selectedDate }}</b>
                            <div class="ml-auto d-inline-flex align-items-center">
                                <label class="text-secondary mr-2 my-0 text-nowrap">Filter by status:</label>
                                <select v-model="filterStatus"
                                        class="form-control form-control-sm">
                                    <option value="">All</option>
                                    <option value="CREATED">Created</option>
                                    <option value="CONFIRMED">Confirmed</option>
                                    <option value="CANCELLED">Cancelled</option>
                                    <option value="COMPLETED">Completed</option>
                                    <option value="ABANDONED">Abandoned</option>
                                </select>
                            </div>
                        </div>
                        <div v-for="event in events" class="align-items-end p-3 border rounded mb-3"
                             :class="event.dateYMD === selectedDate && (filterStatus === '' || filterStatus === event.status) ? 'd-flex' : 'd-none'">
                            <div class="patient-avatar mr-3 align-self-center">@{{ event.proInitials }}</div>
                            <div>
                                <div class="pb-1">
                                    <b class="text-info">@{{ event.proName }}</b>
                                    &nbsp;/&nbsp;
                                    @{{ event.friendlyStartTime }} - @{{ event.friendlyEndTime }} <span class="text-secondary">@{{ event.timezone }}</span>
                                    &nbsp;/&nbsp;
                                    <span class="d-inline-block ml- 2 text-secondary font-weight-bold">@{{ event.title }}</span>
                                </div>
                                <div class="pb-1">
                                    <a target="_blank" :href="'/patients/view/' + event.clientUid" class="font-weight-bold">@{{ event.clientName }}</a>
                                    <span class="small d-inline-block pl-2 text-secondary font-weight-normal">@{{ event.clientSummary }}</span>
                                </div>
                                <div>
                                    Status: <b class="text-secondary">@{{ event.status }}</b>
                                    &nbsp;/&nbsp;
                                    <a :href="'/patients/view/' + event.clientUid + '/calendar/' + event.uid">
                                        <i class="fa fa-edit"></i>
                                        Edit Appointment
                                    </a>
                                </div>
                            </div>
                            <div class="ml-auto">
                                <select v-model="event.newStatus"
                                        class="form-control form-control-sm bg-light"
                                        v-on:change="updateStatus(event)">
                                    <option value="CREATED">CREATED</option>
                                    <option value="CONFIRMED">CONFIRMED</option>
                                    <option value="CANCELLED">CANCELLED</option>
                                    <option value="COMPLETED">COMPLETED</option>
                                    <option value="ABANDONED">ABANDONED</option>
                                </select>
                                <div v-if="selectedDate === '{{ date('Y-m-d') }}'"
                                     class="pt-1 text-right" :class="event.started ? 'text-danger': 'text-secondary'">
                                    @{{ event.inHowManyHours }}
                                </div>
                            </div>
                        </div>
                        <div v-if="numEventsForDate === 0" class="bg-light p-3 text-secondary border bounded">
                        <span v-if="filterStatus === ''">You have no appointments on <b>@{{ selectedDate }}</b></span>
                        <span v-if="filterStatus !== ''">You have no appointments on <b>@{{ selectedDate }}</b> with status <b>@{{ filterStatus }}</b></span>
                    </div>
                    </div>
                    <div v-show="tab==='measurements'">
                        @include('app.dashboard.measurements')
                    </div>
                    <div v-show="tab==='incoming_reports'">
                        @include('app.dashboard.incoming_reports')
                    </div>
                    <div v-show="tab==='erx'">
                        @include('app.dashboard.erx')
                    </div>
                    <div v-show="tab==='labs'">
                        @include('app.dashboard.labs')
                    </div>
                    <div v-show="tab==='imaging'">
                        @include('app.dashboard.imaging')
                    </div>
                    <div v-show="tab==='supply_orders'">
                        @include('app.dashboard.supply_orders')
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="stag-popup stag-popup-md ticket-popup mcp-theme-1" stag-popup-key="ticket-popup"></div>

<script>
    (function() {
        function init() {
            window.apapp = new Vue({
                el: '#pro-dashboard-container',
                delimiters: ['@{{', '}}'],
                data: {
                    tab: '{{ request()->input('tab') ? request()->input('tab') : 'measurements' }}',
                    selectedDate: '{{ date('Y-m-d') }}',
                    selectedStatus: 'CREATED',
                    events: [],
                    numEventsForDate: 0,
                    filterStatus: '',
                    calendarElem: null,
                    currentMonth: null,
                    currentYear: null,
                    measurementFilterStatus: 'ALL',
                    measurements: {!! $pro->pro_type === 'ADMIN' ? '[]' : json_encode($pro->getMeasurements()) !!},
                    appointmentsLoaded: false,
                },
                methods: {
                    formatDate: function (date) {
                        let d = new Date(date),
                            month = '' + (d.getMonth() + 1),
                            day = '' + d.getDate(),
                            year = d.getFullYear();

                        if (month.length < 2)
                            month = '0' + month;
                        if (day.length < 2)
                            day = '0' + day;

                        return [year, month, day].join('-');
                    },
                    onDateChange: function (_newDate) {
                        // this.loadEvents();

                        let self = this;
                        self.selectedDate = _newDate;
                        showMask();
                        this.loadEvents(function() {
                            self.highlightDatesWithEvents();
                            // self.updateNumEventsForDate();
                            self.appointmentsLoaded = true;
                            hideMask();
                        });
                    },
                    selectToday: function () {
                        $('.pro-dashboard-inline-calendar table td[data-date]').removeClass('active');
                        $('.pro-dashboard-inline-calendar table td[data-date="{{ $milliseconds }}"]')
                            .addClass('active');
                        // this.onDateChange('{{ date('Y-m-d') }}');
                    },
                    highlightDatesWithEvents: function () {
                        $('.pro-dashboard-inline-calendar table td[data-date]').removeAttr('has-events');
                        for (let i = 0; i < this.events.length; i++) {
                            $('.pro-dashboard-inline-calendar table td[data-date="' + this.events[i].milliseconds + '"]')
                                .attr('has-events', 1);
                        }
                    },
                    updateNumEventsForDate: function() {
                        this.numEventsForDate = 0;
                        for (let i = 0; i < this.events.length; i++) {
                            if(this.events[i].dateYMD === this.selectedDate &&
                                (this.filterStatus === '' || this.filterStatus === this.events[i].status)) {
                                this.numEventsForDate++;
                                break;
                            }
                        }
                        Vue.nextTick(() => {
                            initFastLoad($('#pro-dashboard-container'));
                        });
                    },
                    updateStatus: function(_event) {
                        $.post('/api/appointment/updateStatus', {
                            uid: _event.uid,
                            status: _event.newStatus
                        }, function(_data) {
                            if(!_data) {
                                toastr.error('Unable to update appointment status!');
                            }
                            else {
                                if(!_data.success) {
                                    toastr.error(_data.message);
                                }
                                else {
                                    _event.status = _event.newStatus;
                                    toastr.success('The appointment has been updated');
                                }
                            }
                        }, 'json')
                    },
                    showEditForm: function(_trigger) {
                        let form = $(_trigger).closest('[moe]').find('form').first();
                        showMoeFormMask();
                        form.show();
                        setTimeout(function() {
                            initPrimaryForm(form);
                        }, 0);
                    },
                    submitEditForm: function(_trigger) {
                        let form = $(_trigger).closest('[moe]').find('form').first();
                        if(!form[0].checkValidity()) {
                            form[0].reportValidity();
                            return;
                        }
                        $.post(form.attr('url'), form.serialize(), function(_data) {
                            if(_data && _data.success) {
                                fastReload();
                            }
                            else {
                                if(_data.message) {
                                    toastr.error(_data.message);
                                }
                                else {
                                    toastr.error('Unable to update the appointment');
                                }
                            }
                        });
                    },
                    cancelEditForm: function(_trigger) {
                        let form = $(_trigger).closest('[moe]').find('form').first();
                        hideMoeFormMask();
                        form.hide();
                    },
                    loadEvents: function(_callback) {
                        let today = this.calendarElem.datepicker('getDate'),
                            firstOfMonth = new Date(today.getFullYear(), today.getMonth(), 1),
                            lastOfMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0),
                            self = this;
                        if(this.currentMonth === today.getMonth() && this.currentYear === today.getFullYear()) {
                            _callback.call(self);
                        }
                        else {
                            $.get('/pro-dashboard-events/' +
                                this.formatDate(firstOfMonth) + '/' +
                                this.formatDate(lastOfMonth), function(_data) {
                                self.events = _data;
                                self.currentMonth = firstOfMonth.getMonth();
                                self.currentYear = firstOfMonth.getFullYear();
                                _callback.call(self);
                            }, 'json');
                        }
                    },
                    updateMeasurements: function() {
                        $.get('/pro-dashboard-measurements/' + this.measurementFilterStatus, (_data) => {
                            this.measurements = _data;
                            Vue.nextTick(() => {
                                // this.initCMRTE();
                                $('#pro-dashboard-container').find('[moe][initialized]').removeAttr('initialized');
                                initMoes();
                            });
                        }, 'json');
                    },
                    setMeasurementStatus: function(_uid, _status) {
                        $.post('/api/measurement/updateStatus', {
                            uid: _uid,
                            status: _status
                        }, (_data) => {
                            this.updateMeasurements();
                        }, 'json');
                    },
                    initCMRTE: function() {
                        $('#pro-dashboard-container [cm-rte]').each(function() {

                            $(this).wrap(
                                $('<div class="border-left border-right rte-holder"/>')
                                    .attr('data-shortcuts', '')
                            );

                            // give a unique id to this editor instance
                            var editorID = Math.ceil(Math.random() * 99999), fieldName = $(this).attr('data-name');

                            var el = this;
                            var existingContent = $(el).attr('data-content');
                            var quill = new Quill(el, {
                                theme: 'snow',
                                modules: stagQuillConfig
                            });

                            var toolbar = $(quill.container).prev('.ql-toolbar');

                            // add button for new shortcut
                            var newSCButton = $('<button class="btn bg-white btn-sm btn-default text-primary w-auto px-2 border py-0 ' +
                                'text-sm add-shortcut" data-editor-id="' + editorID + '">+ Shortcut</button>');
                            toolbar.append(newSCButton);

                            quill.root.innerHTML = existingContent;

                            $('<input type="hidden" name="' + fieldName + '">').val(existingContent).insertAfter(el);

                            quill.on('text-change', function(delta, oldDelta, source) {
                                $(el).next('[name="' + fieldName + '"]').val(quill.root.innerHTML);
                            });

                            $(quill.container)
                                .find('.ql-editor[contenteditable]')
                                .attr('data-field', fieldName)
                                .attr('data-editor-id', editorID)
                                .attr('with-shortcuts', 1);

                        })
                    },
                    initLoadAppointments: function() {
                        if(this.appointmentsLoaded) return false;
                        this.selectToday();
                        this.updateNumEventsForDate();
                        $('.datepicker-days .day.active').trigger('click');
                    }
                },
                mounted: function () {
                    let self = this;
                    this.calendarElem = $('.pro-dashboard-inline-calendar');
                    this.calendarElem.datepicker({
                        format: 'yyyy-mm-dd'
                    });
                    this.calendarElem.on('changeDate', function () {
                        self.onDateChange(self.calendarElem.datepicker('getFormattedDate'));
                    });

                    // DEFER this till appts tab is clicked

                    // this.selectToday();
                    // this.updateNumEventsForDate();

                    // $('.datepicker-days .day.active').trigger('click');



                    // this.initCMRTE();
                    $('#pro-dashboard-container').find('[moe][initialized]').removeAttr('initialized');
                    initMoes();

                    // init fast load
                    initFastLoad($('#pro-dashboard-container'));

                }
            });
            // refresh once ticket popup is closed
            $('body').off('stag-popup-closed')
            $('body').on('stag-popup-closed', function() {
                if($('#pro-dashboard-container').length) {
                    let activeTab = $('.nav-link.active[data-tab]').attr('data-tab');
                    if(activeTab) {
                        fastLoad('/?tab=' + activeTab);
                    }
                }
            });
            // ticket-popup
            $(document)
                .off('click', '.ticket-popup-trigger')
                .on('click', '.ticket-popup-trigger', function() {
                    showMask();
                    window.noMc = true;
                    $.get(this.href, (_data) => {
                        $('.ticket-popup').html(_data);
                        showStagPopup('ticket-popup');
                        $('.ticket-popup .stag-popup.stag-slide').attr('close-all-with-self', 1);
                        runMCInitializer('patient-tickets'); // run specific mc initer
                        hideMask();
                    });
                    return false;
                });
        }
        addMCInitializer('pro-dashboard', init, '#pro-dashboard-container');
    })();
</script>
@endsection
