@extends(request()->input('popupmode') ? 'layouts.popup' : 'layouts.patient')

@section('inner-content')

    <?php

    $oPro = false;
    if(request()->input('opUid')) {
        $oPro = \App\Models\Pro::where('uid', request()->input('opUid'))->first();
    }

    function adjustBrightness($hex, $steps) {
        $steps = max(-255, min(255, $steps));
        $hex = str_replace('#', '', $hex);
        if (strlen($hex) == 3) {
            $hex = str_repeat(substr($hex,0,1), 2).str_repeat(substr($hex,1,1), 2).str_repeat(substr($hex,2,1), 2);
        }
        $color_parts = str_split($hex, 2);
        $return = '#';
        foreach ($color_parts as $color) {
            $color   = hexdec($color); // Convert to decimal
            $color   = max(0,min(255,$color + $steps)); // Adjust color
            $return .= str_pad(dechex($color), 2, '0', STR_PAD_LEFT); // Make two char hex code
        }
        return $return;
    }

    $palette = [
        ["bc" => '#522e92', "fc" => "#ffffff", "ac" => adjustBrightness('#522e92', 180) . 'aa'],
        ["bc" => '#003152', "fc" => "#ffffff", "ac" => adjustBrightness('#003152', 180) . 'aa'],
        ["bc" => '#111e6c', "fc" => "#ffffff", "ac" => adjustBrightness('#111e6c', 180) . 'aa'],
        ["bc" => '#1034a6', "fc" => "#ffffff", "ac" => adjustBrightness('#1034a6', 180) . 'aa'],
        ["bc" => '#0f52ba', "fc" => "#ffffff", "ac" => adjustBrightness('#0f52ba', 180) . 'aa'],
        ["bc" => '#447684', "fc" => "#ffffff", "ac" => adjustBrightness('#447684', 180) . 'aa'],
        ["bc" => '#d86700', "fc" => "#ffffff", "ac" => adjustBrightness('#d86700', 180) . 'aa'],
        ["bc" => '#643c07', "fc" => "#ffffff", "ac" => adjustBrightness('#643c07', 180) . 'aa'],
        ["bc" => '#ff3f3f', "fc" => "#ffffff", "ac" => adjustBrightness('#ff3f3f', 180) . 'aa'],
        ["bc" => '#ffa395', "fc" => "#222222", "ac" => adjustBrightness('#ffa395', 180) . 'aa'],
        ["bc" => '#6450ff', "fc" => "#ffffff", "ac" => adjustBrightness('#6450ff', 180) . 'aa'],
        ["bc" => '#8ec7f4', "fc" => "#222222", "ac" => adjustBrightness('#8ec7f4', 180) . 'aa'],
        ["bc" => '#522e92', "fc" => "#ffffff", "ac" => adjustBrightness('#522e92', 180) . 'aa'],
        ["bc" => '#111e6c', "fc" => "#ffffff", "ac" => adjustBrightness('#111e6c', 180) . 'aa'],
        ["bc" => '#003152', "fc" => "#ffffff", "ac" => adjustBrightness('#003152', 180) . 'aa'],
        ["bc" => '#1034a6', "fc" => "#ffffff", "ac" => adjustBrightness('#1034a6', 180) . 'aa'],
        ["bc" => '#0f52ba', "fc" => "#ffffff", "ac" => adjustBrightness('#0f52ba', 180) . 'aa'],
        ["bc" => '#447684', "fc" => "#ffffff", "ac" => adjustBrightness('#447684', 180) . 'aa'],
        ["bc" => '#d86700', "fc" => "#ffffff", "ac" => adjustBrightness('#d86700', 180) . 'aa'],
        ["bc" => '#643c07', "fc" => "#ffffff", "ac" => adjustBrightness('#643c07', 180) . 'aa'],
        ["bc" => '#ff3f3f', "fc" => "#ffffff", "ac" => adjustBrightness('#ff3f3f', 180) . 'aa'],
        ["bc" => '#ffa395', "fc" => "#222222", "ac" => adjustBrightness('#ffa395', 180) . 'aa'],
        ["bc" => '#6450ff', "fc" => "#ffffff", "ac" => adjustBrightness('#6450ff', 180) . 'aa'],
        ["bc" => '#8ec7f4', "fc" => "#222222", "ac" => adjustBrightness('#8ec7f4', 180) . 'aa'],
    ];
    ?>



    <link href="/select2/select2.min.css" rel="stylesheet" />
    <script src="/select2/select2.min.js"></script>
    <link href='/fullcalendar-5.3.2/lib/main.css' rel='stylesheet' />
    <script src='/fullcalendar-5.3.2/lib/main.js'></script>

    <?php
    if(!$currentAppointment || !$currentAppointment->id) {
        $currentAppointment = false;
    }
    ?>

    {{-- appts list --}}
    @if(!request()->input('popupmode'))
    <div class="">
        <div class="d-flex align-items-end pb-3">
            <h4 class="font-weight-bold m-0 font-size-16">{{ $patient->displayName() }}'s Appointments</h4>
        </div>
        <table class="table table-striped table-sm table-bordered mb-4">
            @if($appointments && count($appointments))
                <thead class="bg-light">
                <tr>
                    <th class="text-secondary border-bottom-0">Date & Time</th>
                    <th class="text-secondary border-bottom-0">Pro</th>
                    <th class="text-secondary border-bottom-0">Title</th>
                    <th class="text-secondary border-bottom-0">Description</th>
                    <th class="text-secondary border-bottom-0">Status</th>
                    <th class="text-secondary border-bottom-0">Confirmation</th>
                </tr>
                </thead>
                <tbody>
                @foreach($appointments as $appointment)
                    <tr>
                        <td>
                            <a href="/patients/view/{{$patient->uid}}/calendar/{{$appointment->uid}}" class="text-nowrap">
                                {{friendly_date($appointment->raw_date) . ' ' . friendly_time($appointment->raw_start_time)}}
                            </a>
                        </td>
                        <td>{{ $appointment->pro->displayName() }}</pre></td>
                        <td>{{ $appointment->title }}</td>
                        <td>{{ $appointment->description }}</td>
                        <td>
                            {{ $appointment->status }}
                            @if($appointment->status_memo)
                                <hr>
                                {{$appointment->status_memo}}
                            @endif
                        </td>
                        <td>
                            @if($appointment->status !== 'CANCELLED' && $appointment->status !== 'COMPLETED')
                                @include('app.patient.partials.appointment-confirmation')
                            @endif
                        </td>
                    </tr>
                @endforeach
                </tbody>
            @else
                <tbody>
                <tr>
                    <td class="text-secondary p-3">No recent or upcoming appointments</td>
                </tr>
                </tbody>
            @endif
        </table>
    </div>
    @endif

    <div id="calendarApp-{{$patient->id}}">

        @if(!request()->input('popupmode'))
        <div class="d-flex align-items-center mb-2">
            <h4 class="font-weight-bold m-0 font-size-16">
                {{ $patient->displayName() }}'s Calendar
            </h4>
            <button v-on:click.prevent="clickThruMode = !clickThruMode"
                    class="ml-3 btn btn-sm outline-0" :class="clickThruMode ? 'btn-info font-weight-bold' : 'btn-outline-info'">
                Click Through Mode
            </button>
            <div class="ml-auto d-inline-flex align-items-center">
                <label class="mr-2 my-0 text-secondary">Show</label>
                <select id="eventTypes"
                        class="form-control form-control-sm"
                        v-model="eventTypes"
                        v-on:change="refreshEvents()">
                    <option value="APPOINTMENTS">Active Appointments</option>
                    <option value="APPOINTMENTS_ALL">All Appointments</option>
                    <option value="PRO_AVAILABILITY">Pro Availability</option>
                    <option value="BOTH">Pro Availability &amp; Active Appointments</option>
                    <option value="BOTH_ALL">Pro Availability &amp; All Appointments</option>
                </select>
            </div>
            <div class="ml-3 d-inline-flex align-items-center">
                <label class="mr-2 my-0 text-secondary">Timezone</label>
                <select id="eventTz" name="timeZone"
                        class="form-control form-control-sm w-180"
                        v-model="timezone">
                    <option value="EASTERN" selected>Eastern</option>
                    <option value="CENTRAL">Central</option>
                    <option value="MOUNTAIN">Mountain</option>
                    <option value="PACIFIC">Pacific</option>
                    <option value="ALASKA">Alaska</option>
                    <option value="HAWAII">Hawaii</option>
                    <option value="PUERTO_RICO">Puerto Rico</option>
                </select>
            </div>
        </div>
        @endif
        <div class="d-block appt-form">
            @if(!request()->input('popupmode'))
            <form class="appt-form-col w-100 d-flex align-items-center mb-2">
                <label class="mr-2 my-0 text-secondary text-nowrap">Show all appointments for</label>
                <select id="eventPros" name="proUid"
                        class="form-control form-control-sm flex-grow-1" multiple
                        v-model="proIds">
                    @if($oPro)
                        <option value="{{$oPro->id}}">{{$oPro->displayName()}}</option>
                    @endif
                </select>
            </form>
            <hr class="my-2">
            @endif
            <div class="appt-calendar-col" :class="clickThruMode ? 'click-through' : ''">
                <div class="stag-fc-container"></div>
            </div>
        </div>
        <div class="stag-popup stag-popup-sm mcp-theme-1" stag-popup-key="client-add-appointment">
            <form method="POST" action="/api/appointment/create" id="newApptForm">
                <h3 class="stag-popup-title">
                    <span>Book New Appointment</span>
                    <a href="#" class="ml-auto text-secondary"
                       onclick="return closeStagPopup()"><i class="fa fa-times-circle"></i></a>
                </h3>
                <input type="hidden" name="clientUid" :value="newAppointment.clientUid">
                <div class="row mb-2">
                    <div class="col-3 text-secondary">
                        Patient
                    </div>
                    <div class="col-9 font-weight-bold">
                        <input type="text"
                               class="form-control form-control-sm"
                               :value="client.nameStr" readonly>
                    </div>
                </div>
                <div class="row mb-2">
                    <div class="col-3 text-secondary">
                        Pro
                    </div>
                    <div class="col-9 font-weight-bold">
                        <select id="addApptPro" name="proUid" {{$pro->pro_type !== 'ADMIN' ? '' : 'provider-search'}}
                                v-model="newAppointment.proUid"
                                :data-pro-uid="newAppointment.proUid"
                                no-auto-pro-suggest-init
                                class="form-control form-control-sm">
                            @if($pro->pro_type !== 'ADMIN')
                                @foreach($pros as $iPro)
                                    <option value="{{$iPro->uid}}">
                                        {{$iPro->displayName()}}
                                    </option>
                                @endforeach
                            @endif
                        </select>
                    </div>
                </div>
                <hr class="my-2">
                <input type="hidden" name="referringProUid" value="{{ $pro->uid }}">
                <div class="row mb-2">
                    <div class="col-3 text-secondary">
                        Date
                    </div>
                    <div class="col-9 font-weight-bold">
                        <input type="date" name="date" required
                               class="form-control form-control-sm"
                               v-model="newAppointment.date">
                    </div>
                </div>
                <div class="row mb-2">
                    <div class="col-3 text-secondary">
                        Start Time
                    </div>
                    <div class="col-9 font-weight-bold">
                        <input type="time" name="startTime" required
                               class="form-control form-control-sm"
                               v-model="newAppointment.startTime">
                    </div>
                </div>
                <div class="row mb-2">
                    <div class="col-3 text-secondary">
                        End Time
                    </div>
                    <div class="col-9 font-weight-bold">
                        <input type="time" name="endTime"
                               class="form-control form-control-sm"
                               v-model="newAppointment.endTime">
                    </div>
                </div>
                <input type="hidden" name="timeZone" :value="timezone">
                <div class="row mb-2">
                    <div class="col-3 text-secondary">
                        Timezone
                    </div>
                    <div class="col-9 font-weight-bold">
                        <input type="text"
                               class="form-control form-control-sm"
                               :value="timezone" readonly>
                        <div class="text-secondary font-weight-normal py-1 text-sm">Timezone as set in the calendar</div>
                    </div>
                </div>
                <div class="row mb-2">
                    <div class="col-3 text-secondary">
                        Title
                    </div>
                    <div class="col-9 font-weight-bold">
                        <input type="text" name="title"
                               class="form-control form-control-sm"
                               v-model="newAppointment.title">
                    </div>
                </div>
                <div class="row mb-2">
                    <div class="col-3 text-secondary">
                        Description
                    </div>
                    <div class="col-9 font-weight-bold">
                        <textarea name="description"
                                  class="form-control form-control-sm"
                                  v-model="newAppointment.description"></textarea>
                    </div>
                </div>
                <div class="d-flex align-items-center justify-content-center">
                    <button class="btn btn-sm btn-primary mr-2"
                            :disabled="inProgress"
                            v-on:click.prevent="addAppointment()">Submit</button>
                    <button class="btn btn-sm btn-default border"
                            onclick="return closeStagPopup()">Cancel</button>
                </div>
            </form>
        </div>
        <div class="stag-popup stag-popup-sm mcp-theme-1" stag-popup-key="client-edit-appointment">
            <form method="POST" action="/api/appointment/updateDateAndTime" id="editApptForm"
                  :class="editAppointment.isTrainingEvent ? 'non-interactive' : ''">
                <h3 class="stag-popup-title">
                    <span>Edit Date &amp; Time</span>
                    <a native target="_blank" v-if="editAppointment.isTrainingEvent" class="ml-3"
                       :href="'{{config('app.hrm2_url')}}/patients/view/' + editAppointment.clientUid + '/calendar/' + editAppointment.uid">
                        <i class="fa fa-external-link-alt"></i>
                        Open in HRM
                    </a>
                    <a href="#" class="ml-auto text-secondary"
                       onclick="return closeStagPopup()"><i class="fa fa-times-circle"></i></a>
                </h3>
                <div class="form-content" :title="editAppointment.isTrainingEvent ? 'Training appointment. Please open in HRM.' : ''">
                <input type="hidden" name="uid" :value="editAppointment.uid">
                <div class="row mb-2">
                    <div class="col-3 text-secondary">
                        Patient
                    </div>
                    <div class="col-9 font-weight-bold">
                        <input type="text"
                               class="form-control form-control-sm"
                               :value="editAppointment.clientName" readonly>
                    </div>
                </div>
                <div class="row mb-2">
                    <div class="col-3 text-secondary">
                        Pro
                    </div>
                    <div class="col-9 font-weight-bold">
                        <!-- <input type="text"
                               class="form-control form-control-sm"
                               :value="editAppointment.proName" readonly> -->
                        <!-- -- -->
                        <select id="updateApptPro" name="proUid" {{$pro->pro_type !== 'ADMIN' ? '' : 'pros-can-access-client-search'}}
                                v-model="editAppointment.proUid"
                                :data-pro-uid="editAppointment.proUid"
                                no-auto-pro-suggest-init
                                class="form-control form-control-sm">
                            @if($pro->pro_type !== 'ADMIN')
                                @foreach($pros as $iPro)
                                    <option value="{{$iPro->uid}}">
                                        {{$iPro->displayName()}}
                                    </option>
                                @endforeach
                            @else
                                <option :value="editAppointment.proUid" selected>@{{ editAppointment.proName }}</option>
                            @endif
                        </select>
                    </div>
                </div>
                <div class="row mb-2">
                    <div class="col-3 text-secondary">
                        Date
                    </div>
                    <div class="col-9 font-weight-bold">
                        <input type="date" name="date" required
                               class="form-control form-control-sm"
                               v-model="editAppointment.date">
                    </div>
                </div>
                <div class="row mb-2">
                    <div class="col-3 text-secondary">
                        Start Time
                    </div>
                    <div class="col-9 font-weight-bold">
                        <input type="time" name="startTime" required
                               class="form-control form-control-sm"
                               v-model="editAppointment.startTime">
                    </div>
                </div>
                <div class="row mb-2">
                    <div class="col-3 text-secondary">
                        End Time
                    </div>
                    <div class="col-9 font-weight-bold">
                        <input type="time" name="endTime"
                               class="form-control form-control-sm"
                               v-model="editAppointment.endTime">
                    </div>
                </div>
                <input type="hidden" name="timeZone" :value="timezone">
                <div class="row mb-2">
                    <div class="col-3 text-secondary">
                        Timezone
                    </div>
                    <div class="col-9 font-weight-bold">
                        <input type="text"
                               class="form-control form-control-sm"
                               :value="timezone" readonly>
                        <div class="text-secondary font-weight-normal py-1 text-sm">Timezone as set in the calendar</div>
                    </div>
                </div>
                <div class="row mb-2">
                    <div class="col-3 text-secondary">
                        Status
                    </div>
                    <div class="col-9 font-weight-bold">
                        <select id="editApptStatus" readonly
                                v-model="editAppointment.status"
                                class="form-control form-control-sm font-weight-bold px-1">
                            <option value="PENDING">PENDING</option>
                            <option value="CONFIRMED">CONFIRMED</option>
                            <option value="CANCELLED">CANCELLED</option>
                            <option value="COMPLETED">COMPLETED</option>
                        </select>
                    </div>
                </div>
                <div class="row mb-2">
                    <div class="col-3 text-secondary">
                        Title
                    </div>
                    <div class="col-9 font-weight-bold">
                        <input type="text" readonly
                               class="form-control form-control-sm"
                               v-model="editAppointment.title">
                    </div>
                </div>
                <div class="row mb-2">
                    <div class="col-3 text-secondary">
                        Description
                    </div>
                    <div class="col-9 font-weight-bold">
                        <textarea readonly
                                  class="form-control form-control-sm"
                                  v-model="editAppointment.description"></textarea>
                    </div>
                </div>
                <div v-if="editAppointment.allowEdit" class="d-flex align-items-center justify-content-center">
                    <button class="btn btn-sm btn-primary mr-2"
                            :disabled="inProgress"
                            v-on:click.prevent="updateAppointment_Timing()">Save Date &amp; Time</button>
                    <button class="btn btn-sm btn-default border"
                            onclick="return closeStagPopup()">Cancel</button>
                </div>
                <div v-else class="alert alert-secondary mb-0">
                    You cannot make changes to this appointment.
                </div>
                </div>
            </form>
        </div>
        <div class="stag-popup stag-popup-sm mcp-theme-1" stag-popup-key="client-edit-appointment-status">
            <form method="POST" action="/api/appointment/updateStatus" id="editApptForm_Status"
                  :class="editAppointment.isTrainingEvent ? 'non-interactive' : ''">
                <h3 class="stag-popup-title">
                    <span>Edit Status</span>
                    <a native target="_blank" v-if="editAppointment.isTrainingEvent" class="ml-3"
                       :href="'{{config('app.hrm2_url')}}/patients/view/' + editAppointment.clientUid + '/calendar/' + editAppointment.uid">
                        <i class="fa fa-external-link-alt"></i>
                        Open in HRM
                    </a>
                    <a href="#" class="ml-auto text-secondary"
                       onclick="return closeStagPopup()"><i class="fa fa-times-circle"></i></a>
                </h3>
                <div class="form-content" :title="editAppointment.isTrainingEvent ? 'Training appointment. Please open in HRM.' : ''">
                    <input type="hidden" name="uid" :value="editAppointment.uid">
                    <div class="row mb-2">
                        <div class="col-3 text-secondary">
                            Patient
                        </div>
                        <div class="col-9 font-weight-bold">
                            <input type="text"
                                   class="form-control form-control-sm"
                                   :value="editAppointment.clientName" readonly>
                        </div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-3 text-secondary">
                            Pro
                        </div>
                        <div class="col-9 font-weight-bold">
                            <input type="text"
                                   class="form-control form-control-sm"
                                   :value="editAppointment.proName" readonly>
                        </div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-3 text-secondary">
                            Date
                        </div>
                        <div class="col-9 font-weight-bold">
                            <input type="date" readonly
                                   class="form-control form-control-sm"
                                   v-model="editAppointment.date">
                        </div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-3 text-secondary">
                            Start Time
                        </div>
                        <div class="col-9 font-weight-bold">
                            <input type="time" readonly
                                   class="form-control form-control-sm"
                                   v-model="editAppointment.startTime">
                        </div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-3 text-secondary">
                            End Time
                        </div>
                        <div class="col-9 font-weight-bold">
                            <input type="time" readonly
                                   class="form-control form-control-sm"
                                   v-model="editAppointment.endTime">
                        </div>
                    </div>
                    <input type="hidden" :value="timezone">
                    <div class="row mb-2">
                        <div class="col-3 text-secondary">
                            Timezone
                        </div>
                        <div class="col-9 font-weight-bold">
                            <input type="text"
                                   class="form-control form-control-sm"
                                   :value="timezone" readonly>
                            <div class="text-secondary font-weight-normal py-1 text-sm">Timezone as set in the calendar</div>
                        </div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-3 text-secondary">
                            Status
                        </div>
                        <div class="col-9 font-weight-bold">
                            <select id="editApptStatus" name="status"
                                    v-model="editAppointment.status"
                                    class="form-control form-control-sm font-weight-bold px-1">
                                <option value="PENDING">PENDING</option>
                                <option value="CONFIRMED">CONFIRMED</option>
                                <option value="CANCELLED">CANCELLED</option>
                                <option value="COMPLETED">COMPLETED</option>
                            </select>
                        </div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-3 text-secondary">
                            Title
                        </div>
                        <div class="col-9 font-weight-bold">
                            <input type="text" readonly
                                   class="form-control form-control-sm"
                                   v-model="editAppointment.title">
                        </div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-3 text-secondary">
                            Description
                        </div>
                        <div class="col-9 font-weight-bold">
                        <textarea readonly
                                  class="form-control form-control-sm"
                                  v-model="editAppointment.description"></textarea>
                        </div>
                    </div>
                    <div v-if="editAppointment.allowEdit" class="d-flex align-items-center justify-content-center">
                        <button class="btn btn-sm btn-primary mr-2"
                                :disabled="inProgress"
                                v-on:click.prevent="updateAppointment_Status()">Save Status</button>
                        <button class="btn btn-sm btn-default border"
                                onclick="return closeStagPopup()">Cancel</button>
                    </div>
                    <div v-else class="alert alert-secondary mb-0">
                        You cannot make changes to this appointment.
                    </div>
                </div>
            </form>
        </div>
        <div class="stag-popup stag-popup-sm mcp-theme-1" stag-popup-key="client-edit-appointment-basic-details">
            <form method="POST" action="/api/appointment/updateBasic" id="editApptForm_BasicDetails"
                  :class="editAppointment.isTrainingEvent ? 'non-interactive' : ''">
                <h3 class="stag-popup-title">
                    <span>Edit Basic Details</span>
                    <a native target="_blank" v-if="editAppointment.isTrainingEvent" class="ml-3"
                       :href="'{{config('app.hrm2_url')}}/patients/view/' + editAppointment.clientUid + '/calendar/' + editAppointment.uid">
                        <i class="fa fa-external-link-alt"></i>
                        Open in HRM
                    </a>
                    <a href="#" class="ml-auto text-secondary"
                       onclick="return closeStagPopup()"><i class="fa fa-times-circle"></i></a>
                </h3>
                <div class="form-content" :title="editAppointment.isTrainingEvent ? 'Training appointment. Please open in HRM.' : ''">
                    <input type="hidden" name="uid" :value="editAppointment.uid">
                    <div class="row mb-2">
                        <div class="col-3 text-secondary">
                            Patient
                        </div>
                        <div class="col-9 font-weight-bold">
                            <input type="text"
                                   class="form-control form-control-sm"
                                   :value="editAppointment.clientName" readonly>
                        </div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-3 text-secondary">
                            Pro
                        </div>
                        <div class="col-9 font-weight-bold">
                            <input type="text"
                                   class="form-control form-control-sm"
                                   :value="editAppointment.proName" readonly>
                        </div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-3 text-secondary">
                            Date
                        </div>
                        <div class="col-9 font-weight-bold">
                            <input type="date" readonly
                                   class="form-control form-control-sm"
                                   v-model="editAppointment.date">
                        </div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-3 text-secondary">
                            Start Time
                        </div>
                        <div class="col-9 font-weight-bold">
                            <input type="time" readonly
                                   class="form-control form-control-sm"
                                   v-model="editAppointment.startTime">
                        </div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-3 text-secondary">
                            End Time
                        </div>
                        <div class="col-9 font-weight-bold">
                            <input type="time" readonly
                                   class="form-control form-control-sm"
                                   v-model="editAppointment.endTime">
                        </div>
                    </div>
                    <input type="hidden" :value="timezone">
                    <div class="row mb-2">
                        <div class="col-3 text-secondary">
                            Timezone
                        </div>
                        <div class="col-9 font-weight-bold">
                            <input type="text"
                                   class="form-control form-control-sm"
                                   :value="timezone" readonly>
                            <div class="text-secondary font-weight-normal py-1 text-sm">Timezone as set in the calendar</div>
                        </div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-3 text-secondary">
                            Status
                        </div>
                        <div class="col-9 font-weight-bold">
                            <select id="editApptStatus" readonly
                                    v-model="editAppointment.status"
                                    class="form-control form-control-sm font-weight-bold px-1">
                                <option value="PENDING">PENDING</option>
                                <option value="CONFIRMED">CONFIRMED</option>
                                <option value="CANCELLED">CANCELLED</option>
                                <option value="COMPLETED">COMPLETED</option>
                            </select>
                        </div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-3 text-secondary">
                            Title
                        </div>
                        <div class="col-9 font-weight-bold">
                            <input type="text" name="title"
                                   class="form-control form-control-sm"
                                   v-model="editAppointment.title">
                        </div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-3 text-secondary">
                            Description
                        </div>
                        <div class="col-9 font-weight-bold">
                        <textarea name="description"
                                  class="form-control form-control-sm"
                                  v-model="editAppointment.description"></textarea>
                        </div>
                    </div>
                    <div v-if="editAppointment.allowEdit" class="d-flex align-items-center justify-content-center">
                        <button class="btn btn-sm btn-primary mr-2"
                                :disabled="inProgress"
                                v-on:click.prevent="updateAppointment_BasicDetails()">Save Basic Details</button>
                        <button class="btn btn-sm btn-default border"
                                onclick="return closeStagPopup()">Cancel</button>
                    </div>
                    <div v-else class="alert alert-secondary mb-0">
                        You cannot make changes to this appointment.
                    </div>
                </div>
            </form>
        </div>
        <div class="stag-menu bg-white border calendar-event-menu pt-1" style="display: none">
            <a start show href="#" class="px-2 pb-1 d-block text-nowrap" data-action="showEditAppointmentModal_BasicDetails">Edit basic details</a>
            <a start show href="#" class="px-2 pb-1 d-block text-nowrap" data-action="showEditAppointmentModal">Edit date and time</a>
            <a start show href="#" class="px-2 pb-1 d-block text-nowrap" data-action="showEditAppointmentModal_Status">Edit status</a>
        </div>
    </div>
    
    <script>
        (function() {

            <?php
            $patient->nameStr = $patient->displayName();
            $clientObject = json_encode($patient);
            ?>

            function init() {
                window.calendarApp = new Vue({
                    el: '#calendarApp-{{$patient->id}}',
                    data: {
                        client: {!! json_encode($patient) !!},
                        eventTypes: '{{ $currentAppointment ? 'BOTH_ALL' : 'APPOINTMENTS' }}',
                        calendar: null,
                        proIds: ['{{ $currentAppointment ? $currentAppointment->pro_id : ($oPro ? $oPro->id : ($patient->mcp ? $patient->mcp->id : $pro->id)) }}'],
                        lastSelectedProUid: '',
                        timezone: '{{ $currentAppointment ? $currentAppointment->timezone : 'EASTERN' }}',
                        today: new Date('{{ date('Y-m-d 00:00:00') }}'),

                        // user clicks/selection
                        selectedSlot: null,
                        selectedEvent: null,

                        // new appt.
                        newAppointment: {
                            proUid: '',
                            referringProUid: '',
                            date: '',
                            startTime: '',
                            endTime: '',
                            timeZone: '',
                            title: '',
                            description: '',
                        },

                        // edit appt.
                        editAppointment: {
                            proUid: '',
                            clientName: '',
                            clientUid: '',
                            allowEdit: true,
                            date: '',
                            startTime: '',
                            endTime: '',
                            timeZone: '',
                            title: '',
                            description: '',
                            status: '',
                            isTrainingEvent: false,
                        },

                        // availability
                        availability: {},

                        inProgress: false,
                        editHonored: false,

                        clickThruMode: false,

                        // dynamic palette (pros are no longer available on page load)
                        nextPaletteIndex: 0,
                        palette: {!! json_encode($palette) !!},
                        proMeta: {},
                        updateProUid:false,
                    },
                    methods: {
                        // init
                        init: function() {
                            this.initSelect2();
                            this.initCalendar();
                        },
                        ensureProMeta: function(_uid) {
                            if(!this.proMeta['' + _uid]) {
                                this.proMeta['' + _uid] = this.palette[this.nextPaletteIndex++];
                                if(this.nextPaletteIndex === this.palette.length) this.nextPaletteIndex = 0;
                            }
                        },
                        initSelect2: function () {
                            let self = this;
                            $('#eventTz')
                                .select2({
                                    templateResult: function(_state) {
                                        return $('<span class="mcp-theme-1"><span>' + _state.text + '</span></span>');
                                    }
                                })
                                .on('change', function() {
                                    self.timezone = $(this).val();
                                    localStorage.stagCalendarTZ = self.timezone;
                                    self.refreshEvents();
                                });
                            $('#eventPros')
                                .select2({

                                    // ajax driven pros listing
                                    ajax: {
                                        url: '/pro-suggest',
                                        dataType: 'json',
                                        data: function (params) {
                                            return {
                                                term: params.term,
                                                json: true
                                            };
                                        }
                                    },

                                    closeOnSelect: true,

                                    // dropdown options
                                    templateResult: function(_state) {
                                        let element = _state.element;
                                        self.ensureProMeta(_state.uid);
                                        if(!element || !element.value) {
                                            return $('<span class="mcp-theme-1"><span>' + _state.text + '</span></span>');
                                        }
                                        element = $(element);
                                        return $('<span class="mcp-theme-1 pro-option" ' +
                                            '<span class="pro-option-initials" ' +
                                            'style="background: ' + self.proMeta[_state.uid].bc + '; color: ' + self.proMeta[_state.uid].fc + '">' +
                                            self.initials + '</span>' +
                                            _state.text +
                                            '</span></span>');
                                    },

                                    // selected items
                                    templateSelection: function(_state) {
                                        let element = _state.element;
                                        self.ensureProMeta(_state.uid);
                                        if(!element || !element.value) {
                                            return $('<span class="mcp-theme-1"><span>' + _state.text + '</span></span>');
                                        }
                                        element = $(element);
                                        return $('<span class="pro-selection" ' +
                                            'style="background: ' + self.proMeta[_state.uid].bc + '; color: ' + self.proMeta[_state.uid].fc + '">' +
                                            _state.text + '</span>');
                                    }
                                })
                                .on('change', function() {
                                    self.proIds = $(this).val();
                                    localStorage.stagCalendarProIds = JSON.stringify(self.proIds);
                                    self.refreshEvents();
                                    self.lastSelectedProUid = '';
                                    @if($pro->pro_type === 'ADMIN')
                                    if(self.proIds && self.proIds.length) {
                                        $.get('/pro-uid/' + self.proIds[self.proIds.length - 1], _data => {
                                            self.lastSelectedProUid = _data;
                                        });
                                    }
                                    @endif
                                });

                            // change from select2 to pro-suggest
                            $('#addApptPro').on('change', function() {
                                self.newAppointment.proUid = $(this).val();
                            });
                            $('#editApptPro').on('change', function() {
                                self.editAppointment.proUid = $(this).val();
                            });
                            $('#updateApptPro').on('change', function() {
                                self.editAppointment.proUid = $(this).val();
                                if(!self.updateProUid){
                                    self.updateProUid = true;
                                }
                            });
                        },
                        initCalendar: function () {
                            let self = this;
                            <?php
                            $initialDate = date('Y-m-d');
                            if($currentAppointment) {
                                $initialDate = trim(preg_replace("/ .*/", "", $currentAppointment->start_time));
                            }
                            ?>
                            this.calendar = new FullCalendar.Calendar($('.stag-fc-container')[0], {
                                allDaySlot: false,
                                headerToolbar: {
                                    left: 'prev,next today',
                                    center: 'title',
                                    right: 'dayGridMonth,timeGridWeek,timeGridDay'
                                },
                                initialView: 'timeGridWeek',
                                initialDate: '{{ $initialDate }}',
                                editable: true,
                                selectable: true,
                                navLinks: true,
                                dayMaxEvents: false,
                                slotMinTime: '00:00',
                                slotMaxTime: '23:59',
                                scrollTime: '06:00:00',
                                slotDuration: '00:15:00',
                                events: function(info, successCallback, failureCallback) {
                                    // if(!self.proIds || !self.proIds.length) {
                                    //     successCallback([]); // no events if no pro selected
                                    //     return;
                                    // }
                                    if(!self.timezone) {
                                        successCallback([]); // no events if no tz selected
                                        return;
                                    }
                                    $.get('/appointment/getAllAppointmentsForPros' +
                                        '?proIds=' + self.proIds +
                                        '&clientId=' + self.client.id +
                                        '&start=' + info.startStr.substr(0, 10) +
                                        '&end=' + info.endStr.substr(0, 10) +
                                        '&timeZone=' + self.timezone, function(_data) {
                                        if(_data && Array.isArray(_data)) {
                                            let events = _data, displayEvents = [];
                                            for(let e in events) {
                                                self.ensureProMeta(events[e].proUid);
                                                if(!self.proMeta[events[e].proUid]) {
                                                    self.proMeta[events[e].proUid] = {
                                                        ac: '#000',
                                                        bc: '#c1f966',
                                                        fc: '#222'
                                                    };
                                                }
                                                if(events.hasOwnProperty(e) && self.proMeta[events[e].proUid]) {
                                                    let ev = events[e], meta = self.proMeta[ev.proUid];
                                                    if(ev.type === 'appointment') {
                                                        if(self.eventTypes.indexOf('APPOINTMENTS') === 0 || self.eventTypes.indexOf('BOTH') === 0) {
                                                            ev.backgroundColor =  meta.bc;
                                                            ev.borderColor = meta.bc;
                                                            ev.textColor = meta.fc;
                                                            ev.initials = meta.initials;
                                                            ev.display = 'block';
                                                            ev.editable = true;

                                                            // active/all
                                                            if(['CANCELLED', 'COMPLETED'].indexOf(ev.status) !== -1) {
                                                                if(self.eventTypes === 'APPOINTMENTS_ALL' || self.eventTypes === 'BOTH_ALL') {
                                                                    displayEvents.push(ev);
                                                                }
                                                            }
                                                            else {
                                                                displayEvents.push(ev);
                                                            }
                                                        }
                                                    }
                                                    else {
                                                        if(self.eventTypes === 'PRO_AVAILABILITY' || self.eventTypes.indexOf('BOTH') === 0) {
                                                            ev.backgroundColor = meta.ac;
                                                            ev.borderColor = meta.bc;
                                                            ev.textColor = meta.bc;
                                                            ev.initials = meta.initials;
                                                            ev.display = 'block';
                                                            ev.editable = false;
                                                            displayEvents.push(ev);
                                                        }
                                                    }
                                                }
                                            }
                                            successCallback(displayEvents);
                                        }
                                        else {
                                            failureCallback('Unable to refresh appointments!');
                                        }
                                    }, 'json');
                                },
                                eventDidMount: function(arg) {
                                    self.afterRenderingEvents();
                                    if(arg.event.extendedProps.type === 'appointment') {
                                        console.log(arg.event)
                                    }
                                },
                                eventClassNames: function(arg) {
                                    let classes = [];
                                    if (arg.event.extendedProps.clientOnly) {
                                        classes.push('client-only');
                                    }
                                    if (arg.event.extendedProps.otherClient) {
                                        classes.push('other-client');
                                    }
                                    if (arg.event.extendedProps.type === 'availability') {
                                        classes.push('availability');
                                    }
                                    if (['CANCELLED', 'COMPLETED'].indexOf(arg.event.extendedProps.status) !== -1) {
                                        classes.push('inactive-appointment');
                                    }
                                    if (arg.event.extendedProps.type === 'appointment') {
                                        classes.push('appointment-' + arg.event.extendedProps.appointmentUid);
                                    }
                                    return classes;
                                },
                                loading: function(bool) {

                                },
                                eventClick: function(info) {
                                    self.selectedEvent = info.event;
                                    // self.showEditAppointmentModal();
                                    self.showEventMenu(info.el);
                                },
                                selectAllow: function(info) { // allow only single selections
                                    let seconds = info.end.getTime() - info.start.getTime(),
                                        maxDelta = 86400000;
                                    console.log(seconds);
                                    if(!info.allDay) {
                                        maxDelta = 1800000;
                                    }
                                    return seconds <= maxDelta;
                                },
                                select: function(info) {
                                    self.selectedSlot = info;
                                    if(self.today.getTime() <= self.selectedSlot.start.getTime()) {
                                        $('<a href="#" class="add-overlay ' +
                                            (info.allDay ? 'add-overlay-day-grid' : 'add-overlay-time-grid') + '">Add</a>')
                                            .on('mousedown', function() {
                                                self.showAddAppointmentModal();
                                                return false;
                                            })
                                            .appendTo('.fc-highlight');
                                    }
                                },
                                eventDrop: self.eventMovedOrResized,
                                eventResize: self.eventMovedOrResized
                            });
                            $(document).on('mousedown', '.fc-highlight', function() {
                                 if(self.selectedSlot && self.today.getTime() <= self.selectedSlot.start.getTime()) {
                                     self.showAddAppointmentModal();
                                 }
                            });
                            this.calendar.render();

                            // ugly fix/hack to force scrollTime option to work
                            setTimeout(() => {
                                $('.fc-timeGridWeek-button').click();
                            }, 750);
                        },
                        afterRenderingEvents: function() {
                            let self = this;
                            $('.fc .availability').each(function () {
                                $(this).parent('.fc-timegrid-event-harness').css('pointer-events', 'none');
                            });
                            @if($currentAppointment)
                            if(!self.editHonored) {
                                window.setTimeout(function() {
                                    let allEvents = self.calendar.getEvents();
                                    if(allEvents) {
                                        let currentEvent = allEvents.filter(function(_ev) {
                                            return _ev.extendedProps.appointmentUid === '{{ $currentAppointment->uid }}';
                                        });
                                        if(currentEvent) currentEvent = currentEvent[0];
                                        if(currentEvent) {
                                            self.selectedEvent = currentEvent;
                                            self.showEditAppointmentModal();
                                            self.editHonored = true;
                                        }
                                    }
                                }, 250);
                            }
                            @endif
                            setTimeout(() => {
                                $('.fc-toolbar-title .tz-display').remove();
                                $('<span/>')
                                    .addClass('pl-2 tz-display text-secondary')
                                    .text('(Timezone: ' + this.timezone + ')')
                                    .appendTo($('.fc-toolbar-title'));
                            }, 0);
                        },
                        dateStr: function(_dateTime) {
                            return _dateTime.getFullYear() + "-" +
                                ("0"+(_dateTime.getMonth()+1)).slice(-2) + "-" +
                                ("0" + _dateTime.getDate()).slice(-2);
                        },
                        timeStr: function(_dateTime) {
                            return ("0" + _dateTime.getHours()).slice(-2) + ":" +
                                ("0" + _dateTime.getMinutes()).slice(-2);
                        },
                        eventMovedOrResized: function (info) {
                            let self = this;
                            if(!window.confirm('Are you sure?')) {
                                this.refreshEvents();
                                return;
                            }
                            let date = this.dateStr(info.event.start);
                            let startTime = this.timeStr(info.event.start);
                            let endTime = null;
                            if(info.event.end) {
                                endTime = this.timeStr(info.event.end);
                            }
                            $.post('/api/appointment/updateDateAndTime', {
                                uid: info.event.extendedProps.appointmentUid,
                                date: date,
                                startTime: startTime,
                                endTime: endTime,
                                timeZone: this.timezone,
                            }, function(_data) {
                                self.refreshEvents();
                                if(_data) {
                                    if(!_data.success) {
                                        toastr.error(_data.message);
                                    }
                                }
                                else {
                                    toastr.error('Unable to update the appointment!');
                                }
                            }, 'json');
                        },
                        refreshEvents: function() {
                            this.calendar.refetchEvents();
                        },
                        showAddAppointmentModal: function() {
                            // setup model data
                            this.inProgress = false;
                            let startTime = this.timeStr(this.selectedSlot.start);
                            let endTime = this.timeStr(this.selectedSlot.end);
                            this.newAppointment.clientUid = this.client.uid;
                            this.newAppointment.proUid = '';
                            if(this.lastSelectedProUid) {
                                this.newAppointment.proUid = this.lastSelectedProUid;
                            }
                            else {
                                @if($oPro)
                                    this.newAppointment.proUid = '{{$oPro->uid}}';
                                @elseif($pro->is_hcp && $pro->is_enrolled_as_mcp)
                                    this.newAppointment.proUid = '{{$pro->uid}}';
                                @elseif($patient->mcp)
                                    this.newAppointment.proUid = '{{$patient->mcp->uid}}';
                                @endif
                            }
                            this.newAppointment.referringProUid = '';
                            this.newAppointment.date = this.dateStr(this.selectedSlot.start);
                            this.newAppointment.startTime = startTime === '00:00' ? '' : startTime;
                            this.newAppointment.endTime = (this.selectedSlot.allDay || endTime === '00:00') ? '' : endTime;
                            this.newAppointment.timeZone = this.timezone;
                            this.newAppointment.title = '';
                            this.newAppointment.description = '';
                            Vue.nextTick(function() {
                                $('#addApptPro').find('option').prop('selected', false);
                                $('#addApptPro').trigger('change');
                                showStagPopup('client-add-appointment', true);
                                $('#addApptPro').removeAttr('no-auto-pro-suggest-init').removeAttr('pro-suggest-initialized');
                                initProSuggest();
                            });
                        },
                        addAppointment: function() {
                            let form = $('#newApptForm');
                            if(!form[0].checkValidity()) {
                                form[0].reportValidity();
                                return false;
                            }
                            this.inProgress = true;
                            let self = this;
                            showMask();

                            // force ser proUid
                            if(!$('#addApptPro').is(':visible')) {
                                $('#addApptPro').val($('#addApptPro option[selected]').first().attr('value'));
                            }

                            $.post(form.attr('action'), form.serialize(), function(_data) {
                                if(_data) {
                                    if(_data.success) {
                                        self.refreshEvents();
                                        closeStagPopup();

                                        // if fromNoteUid, associate as follow-up appt. and close calendar popup
                                        @if(request()->input('fromNoteUid'))
                                            $.post('/api/note/updateFollowUpStatus', {
                                                uid: '{{request()->input('fromNoteUid')}}',
                                                isFollowUpNeeded: 1,
                                                followUpAppointmentUid: _data.data
                                            }, _data => {
                                                if(!hasResponseError(_data)) {
                                                    closeStagPopup();
                                                }
                                            }, 'json');
                                        @endif
                                    }
                                    else {
                                        toastr.error(_data.message);
                                    }
                                }
                                else {
                                    toastr.error('Unable to book appointment!');
                                }
                                self.inProgress = false;
                                hideMask();
                            }, 'json');
                        },
                        showEventMenu: function(_el) {
                            _el = $(_el);
                            let menu = _el.closest('.fc-timegrid-body').find('.calendar-event-menu').first();
                            if(!menu.length) {
                                menu = $('.calendar-event-menu').clone().removeClass('.calendar-event-menu').appendTo(_el.closest('.fc-timegrid-body'));
                            }
                            menu
                                .show()
                                .css({
                                    top: (_el.parent().position().top + _el.parent().outerHeight()) + 'px',
                                    left: _el.closest('td').position().left + 'px',
                                });
                        },
                        showEditAppointmentModal: function() {
                            var self = this;
                            // setup model data
                            this.inProgress = false;
                            this.editAppointment.uid = this.selectedEvent.extendedProps.appointmentUid;
                            this.editAppointment.clientUid = this.selectedEvent.extendedProps.clientUid;
                            @if($pro->isDefaultNA())
                                this.editAppointment.allowEdit = false;
                                this.editAppointment.clientName = this.selectedEvent.extendedProps.clientName.split(/\s+/).map(_x => _x[0]).join('');
                                $.get('/can-access-patient/' + this.editAppointment.clientUid, _data => {
                                    if(!hasResponseError(_data)) {
                                        if(_data.data) {
                                            this.editAppointment.allowEdit = true;
                                            this.editAppointment.clientName = this.selectedEvent.extendedProps.clientName;
                                        }
                                    }
                                }, 'json');
                            @else
                                this.editAppointment.allowEdit = true;
                                this.editAppointment.clientName = this.selectedEvent.extendedProps.clientName;
                            @endif

                            this.editAppointment.proUid = this.selectedEvent.extendedProps.proUid;
                            this.editAppointment.proName = this.selectedEvent.extendedProps.proName;
                            this.editAppointment.date = this.dateStr(this.selectedEvent.start);
                            this.editAppointment.startTime = this.timeStr(this.selectedEvent.start);
                            this.editAppointment.endTime = this.selectedEvent.end ? this.timeStr(this.selectedEvent.end) : '';
                            this.editAppointment.timeZone = this.timezone;
                            this.editAppointment.title = this.selectedEvent.extendedProps._title;
                            this.editAppointment.description = this.selectedEvent.extendedProps.description;
                            this.editAppointment.status = this.selectedEvent.extendedProps.status;
                            this.editAppointment.isTrainingEvent = this.selectedEvent.extendedProps.isTrainingEvent;
                            Vue.nextTick(function() {
                                showStagPopup('client-edit-appointment', true);
                                self.initAutoSuggestAppointmentProsAllowedToAccessClients();

                            });

                            setTimeout(() => {
                                $('.stag-menu').hide();
                            }, 100);
                        },
                        showEditAppointmentModal_BasicDetails: function() {
                            // setup model data
                            this.inProgress = false;
                            this.editAppointment.uid = this.selectedEvent.extendedProps.appointmentUid;
                            this.editAppointment.clientUid = this.selectedEvent.extendedProps.clientUid;
                            @if($pro->isDefaultNA())
                                this.editAppointment.allowEdit = false;
                            this.editAppointment.clientName = this.selectedEvent.extendedProps.clientName.split(/\s+/).map(_x => _x[0]).join('');
                            $.get('/can-access-patient/' + this.editAppointment.clientUid, _data => {
                                if(!hasResponseError(_data)) {
                                    if(_data.data) {
                                        this.editAppointment.allowEdit = true;
                                        this.editAppointment.clientName = this.selectedEvent.extendedProps.clientName;
                                    }
                                }
                            }, 'json');
                            @else
                                this.editAppointment.allowEdit = true;
                                this.editAppointment.clientName = this.selectedEvent.extendedProps.clientName;
                            @endif

                            this.editAppointment.proUid = this.selectedEvent.extendedProps.proUid;
                            this.editAppointment.proName = this.selectedEvent.extendedProps.proName;
                            this.editAppointment.date = this.dateStr(this.selectedEvent.start);
                            this.editAppointment.startTime = this.timeStr(this.selectedEvent.start);
                            this.editAppointment.endTime = this.selectedEvent.end ? this.timeStr(this.selectedEvent.end) : '';
                            this.editAppointment.timeZone = this.timezone;
                            this.editAppointment.title = this.selectedEvent.extendedProps._title;
                            this.editAppointment.description = this.selectedEvent.extendedProps.description;
                            this.editAppointment.status = this.selectedEvent.extendedProps.status;
                            this.editAppointment.isTrainingEvent = this.selectedEvent.extendedProps.isTrainingEvent;
                            Vue.nextTick(function() {
                                showStagPopup('client-edit-appointment-basic-details', true);
                            });

                            setTimeout(() => {
                                $('.stag-menu').hide();
                            }, 100);
                        },
                        showEditAppointmentModal_Status: function() {
                            // setup model data
                            this.inProgress = false;
                            this.editAppointment.uid = this.selectedEvent.extendedProps.appointmentUid;
                            this.editAppointment.clientUid = this.selectedEvent.extendedProps.clientUid;
                            @if($pro->isDefaultNA())
                                this.editAppointment.allowEdit = false;
                            this.editAppointment.clientName = this.selectedEvent.extendedProps.clientName.split(/\s+/).map(_x => _x[0]).join('');
                            $.get('/can-access-patient/' + this.editAppointment.clientUid, _data => {
                                if(!hasResponseError(_data)) {
                                    if(_data.data) {
                                        this.editAppointment.allowEdit = true;
                                        this.editAppointment.clientName = this.selectedEvent.extendedProps.clientName;
                                    }
                                }
                            }, 'json');
                            @else
                                this.editAppointment.allowEdit = true;
                                this.editAppointment.clientName = this.selectedEvent.extendedProps.clientName;
                            @endif

                            this.editAppointment.proUid = this.selectedEvent.extendedProps.proUid;
                            this.editAppointment.proName = this.selectedEvent.extendedProps.proName;
                            this.editAppointment.date = this.dateStr(this.selectedEvent.start);
                            this.editAppointment.startTime = this.timeStr(this.selectedEvent.start);
                            this.editAppointment.endTime = this.selectedEvent.end ? this.timeStr(this.selectedEvent.end) : '';
                            this.editAppointment.timeZone = this.timezone;
                            this.editAppointment.title = this.selectedEvent.extendedProps._title;
                            this.editAppointment.description = this.selectedEvent.extendedProps.description;
                            this.editAppointment.status = this.selectedEvent.extendedProps.status;
                            this.editAppointment.isTrainingEvent = this.selectedEvent.extendedProps.isTrainingEvent;
                            Vue.nextTick(function() {
                                showStagPopup('client-edit-appointment-status', true);
                            });

                            setTimeout(() => {
                                $('.stag-menu').hide();
                            }, 100);
                        },
                        updateAppointment: function() {
                            let form = $('#editApptForm');
                            if(!form[0].checkValidity()) {
                                form[0].reportValidity();
                                return false;
                            }

                            // confirming if changing to cancelled, completed
                            if(this.selectedEvent.extendedProps.status !== this.editAppointment.status &&
                                ['CANCELLED', 'COMPLETED'].indexOf(this.editAppointment.status) !== -1) {
                                if(!window.confirm('CANCELLED and COMPLETED appointments will ' +
                                    'not be displayed in the calendar by default.\n\n' +
                                    'Are you sure you want to update the status of this appointment to ' + this.editAppointment.status + '?')) {
                                    return false;
                                }
                            }

                            this.inProgress = true;
                            let self = this;
                            showMask();
                            $.post(form.attr('action'), form.serialize(), function(_data) {
                                if(_data) {
                                    if(_data.success) {
                                        self.refreshEvents();
                                        closeStagPopup();
                                    }
                                    else {
                                        toastr.error(_data.message);
                                    }
                                }
                                else {
                                    toastr.error('Unable to update appointment!');
                                }
                                self.inProgress = false;
                                hideMask();
                            }, 'json');
                        },
                        updateAppointment_Status: function() {
                            let form = $('#editApptForm_Status');
                            if(!form[0].checkValidity()) {
                                form[0].reportValidity();
                                return false;
                            }

                            // confirming if changing to cancelled, completed
                            if(this.selectedEvent.extendedProps.status !== this.editAppointment.status &&
                                ['CANCELLED', 'COMPLETED'].indexOf(this.editAppointment.status) !== -1) {
                                if(!window.confirm('CANCELLED and COMPLETED appointments will ' +
                                    'not be displayed in the calendar by default.\n\n' +
                                    'Are you sure you want to update the status of this appointment to ' + this.editAppointment.status + '?')) {
                                    return false;
                                }
                            }

                            this.inProgress = true;
                            let self = this;
                            showMask();
                            $.post(form.attr('action'), form.serialize(), function(_data) {
                                if(_data) {
                                    if(_data.success) {
                                        self.refreshEvents();
                                        closeStagPopup();
                                    }
                                    else {
                                        toastr.error(_data.message);
                                    }
                                }
                                else {
                                    toastr.error('Unable to update appointment!');
                                }
                                self.inProgress = false;
                                hideMask();
                            }, 'json');
                        },
                        updateAppointment_Timing: function() {
                            let form = $('#editApptForm');
                            if(!form[0].checkValidity()) {
                                form[0].reportValidity();
                                return false;
                            }
                            
                            var url = form.attr('action');
                            if(this.updateProUid){
                                url = '/api/appointment/updateProDateAndTime';
                            }

                            this.inProgress = true;
                            let self = this;
                            showMask();
                            $.post(url, form.serialize(), function(_data) {
                                if(_data) {
                                    if(_data.success) {
                                        self.updateProUid = false;
                                        self.refreshEvents();
                                        closeStagPopup();
                                    }
                                    else {
                                        toastr.error(_data.message);
                                    }
                                }
                                else {
                                    toastr.error('Unable to update appointment!');
                                }
                                self.inProgress = false;
                                hideMask();
                            }, 'json');
                        },
                        updateAppointment_BasicDetails: function() {
                            let form = $('#editApptForm_BasicDetails');
                            if(!form[0].checkValidity()) {
                                form[0].reportValidity();
                                return false;
                            }

                            this.inProgress = true;
                            let self = this;
                            showMask();
                            $.post(form.attr('action'), form.serialize(), function(_data) {
                                if(_data) {
                                    if(_data.success) {
                                        self.refreshEvents();
                                        closeStagPopup();
                                    }
                                    else {
                                        toastr.error(_data.message);
                                    }
                                }
                                else {
                                    toastr.error('Unable to update appointment!');
                                }
                                self.inProgress = false;
                                hideMask();
                            }, 'json');
                        },
                        initAutoSuggestAppointmentProsAllowedToAccessClients: function(){
                            var select2 = $("[pros-can-access-client-search]").select2({
                            placeholder: "Search Pro",
                            minimumInputLength: 2,
                            ajax: {
                                url: '/pro-suggest',
                                dataType: 'json',
                                type: "GET",
                                quietMillis: 50,
                                data: function (params) {
                                    return {
                                        term: params.term,
                                        json: true,
                                        canAccessClientUid: "{{ $patient->uid }}"
                                    };
                                },
                                processResults: function (data) {
                                    data = data.results || [];
                                    return {
                                        results: $.map(data, function (item) {
                                            return {
                                                text: item.text,
                                                id: item.uid
                                            }
                                        })
                                    };
                                }
                            }
                        });
                        },
                    },
                    mounted: function() {
                        this.init();
                        @if(!$currentAppointment)
                        if(localStorage.stagCalendarTZ) {
                            this.timezone = localStorage.stagCalendarTZ;
                            Vue.nextTick(function() {
                                $('#eventTz').trigger('change');
                            });
                        }
                        if(localStorage.stagCalendarProIds) {
                            let lsProIds = JSON.parse(localStorage.stagCalendarProIds);
                            if(lsProIds && lsProIds.length) {
                                this.proIds = lsProIds;
                                Vue.nextTick(function () {
                                    $('#eventPros').trigger('change');
                                });
                            }
                        }
                        @endif

                        $(document)
                            .off('mousedown.discard-stag-menu')
                            .on('mousedown.discard-stag-menu', function (_e) {
                                if($(_e.target).closest('.stag-menu').length) return;
                                $('.stag-menu').hide();
                            });

                        let self = this;
                        $(document)
                            .off('click.stag-menu-action', '.stag-menu>a[data-action]')
                            .on('click.stag-menu-action', '.stag-menu>a[data-action]', function (_e) {
                                self[$(this).attr('data-action')].call(self);
                                return false;
                            });

                    }
                });
            }

            addMCInitializer('patient-calendar-{{$patient->id}}', init, '#calendarApp-{{$patient->id}}');
        })();
    </script>
@endsection
