@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>
                            <i class="fas fa-chart-bar"></i>
                            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 native target="_top" href="/patients">Total patients</a></th>
                                </tr>
                                <tr>
                                    <th class="px-2 text-center">{{$keyNumbers['patientsNotSeenYet']}}</th>
                                    <th class="pl-2"><a native target="_top" 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 native target="_top" 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 native target="_top" 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 native target="_top" 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>
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="card mt-3">
                    <div class="card-header">
                        <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 target="_top" href="/mc/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>
            </div>
            <div class="col-md-9">

                <ul class="nav nav-tabs">
                    <li class="nav-item">
                        <a class="nav-link" :class="tab == 'appointments' ? 'active' : ''" href="#" v-on:click.prevent="tab='appointments'">Appointments</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" :class="tab == 'measurements' ? 'active' : ''" href="#" v-on:click.prevent="tab='measurements'">Measurements</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"
                                        v-on:change="updateNumEventsForDate()">
                                    <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="_top" :href="'/mc/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 target="_top" :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>
            </div>
        </div>
    </div>
</div>

<script>
    (function() {
        function init() {
            window.apapp = new Vue({
                el: '#pro-dashboard-container',
                delimiters: ['@{{', '}}'],
                data: {
                    tab: 'measurements', // appointments | 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()) !!}
                },
                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;
                        this.loadEvents(function() {
                            self.highlightDatesWithEvents();
                            self.updateNumEventsForDate();
                        });
                    },
                    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++;
                            }
                        }
                    },
                    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);

                        })
                    }
                },
                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'));
                    });
                    this.selectToday();
                    this.updateNumEventsForDate();

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

                    // this.initCMRTE();
                    $('#pro-dashboard-container').find('[moe][initialized]').removeAttr('initialized');
                    initMoes();
                }
            });
        }
        addMCInitializer('pro-dashboard', init, '#pro-dashboard-container');
    })();
</script>
@endsection
