<?php
$parsed = null;
if($patient->rtm_msk_protocol_detail_json) {
    try {
        $parsed = json_decode($patient->rtm_msk_protocol_detail_json);
    }
    catch (Exception $e) {}
}
?>
<div class="popup-content-container px-3 min-height-300px" id="protocol-builder-{{$patient->uid}}">
    <div class="d-flex align-items-baseline mb-2">
        <b>Program Notes</b>
        <div class="flex-grow-1" v-if="!programNotesEditMode">
            <span class="ml-2" v-if="protocol.program_notes">@{{protocol.program_notes}}</span>
            <a href="#" class="ml-2" v-on:click.prevent="programNotesEditMode = !programNotesEditMode">Edit</a>
        </div>
        <div class="flex-grow-1 d-inline-flex align-items-stretch" v-if="programNotesEditMode">
            <input type="text" class="form-control form-control-sm ml-2" v-model="protocol.program_notes">
            <button class="btn btn-sm btn-primary ml-2" v-on:click.prevent="programNotesEditMode = !programNotesEditMode">Done</button>
        </div>
    </div>
    <div class="d-flex align-items-baseline mb-2">
        <b>Exercises</b>
        <div class="ml-3 position-relative">
            <a href="#" v-on:click.prevent="toggleLibrary()">Add From Library</a>
            <div v-if="showLibrary" class="position-absolute px-2 pt-2 border bg-white min-width-500px">
                <p class="mb-2 text-nowrap text-secondary d-flex align-items-baseline">
                    <span class="font-weight-bold">Exercises Library</span>
                    <span class="text-sm ml-2">(click to add)</span>
                    <input type="text" class="form-control form-control-sm min-width-unset mx-3" placeholder="Filter" v-model="filter">
                    <a href="#" class="ml-auto text-secondary" v-on:click.prevent="showLibrary = !showLibrary"><i class="fa fa-times-circle"></i></a>
                </p>
                <div class="max-height-400px overflow-auto">
                    <div v-for="(exercise, index) in library"
                         v-if="!$.trim(filter) || exercise.name.toLowerCase().indexOf(filter.toLowerCase()) !== -1"
                         class="p-2 border mb-2 on-hover-aliceblue c-pointer"
                         v-on:click.prevent="addActivity(exercise)">
                        <div class="d-flex align-items-baseline">
                            <img v-if="exercise.image" :src="exercise.image" :alt="exercise.name" class="image-w90px mr-2 align-self-start">
                            <div>
                                <div class="d-flex align-items-baseline">
                                    <div class="font-weight-bold">@{{exercise.name}}</div>
                                    <div class="text-success text-sm ml-2" v-if="isAdded(exercise.name)"><i class="fa fa-check"></i> Added</div>
                                </div>
                                <div class="text-secondary text-sm">@{{exercise.description}}</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <span class="mx-2 text-secondary">|</span>
        <div class="position-relative">
            <a href="#" v-on:click.prevent="showCustomAdd = !showCustomAdd">Add Custom</a>
            <div v-if="showCustomAdd" class="position-absolute px-2 pt-2 border bg-white min-width-500px">
                <p class="mb-2 text-nowrap text-secondary d-flex align-items-baseline">
                    <span class="font-weight-bold">Add Exercise</span>
                    <a href="#" class="ml-auto text-secondary" v-on:click.prevent="showCustomAdd = !showCustomAdd"><i class="fa fa-times-circle"></i></a>
                </p>
                <div class="mb-2">
                    <label class="text-sm text-secondary mb-1">Name</label>
                    <input type="text" class="form-control form-control-sm" v-model="customExercise.name">
                </div>
                <div class="mb-2">
                    <label class="text-sm text-secondary mb-1">Description</label>
                    <textarea class="form-control form-control-sm" rows="2" v-model="customExercise.description"></textarea>
                </div>
                <div class="mb-2">
                    <label class="text-sm text-secondary mb-1">Image URL:</label>
                    <input type="text" class="form-control form-control-sm" v-model="customExercise.image">
                </div>
                <div class="mb-2">
                    <label class="text-sm text-secondary mb-1">Video URL:</label>
                    <input type="text" class="form-control form-control-sm" v-model="customExercise.video">
                </div>
                <div class="d-flex align-items-baseline mb-2 pt-1">
                    <b class="text-secondary">Properties</b>
                    <a href="#" class="ml-3" v-on:click.prevent="addNewProperty()">Add</a>
                </div>
                <table class="table table-sm mb-2 table-bordered">
                    <thead>
                    <tr class="bg-light">
                        <th class="w-50 border-bottom-0 text-sm">Property</th>
                        <th class="w-50 border-bottom-0 text-sm">Value</th>
                        <th class="border-bottom-0 text-sm"></th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr v-if="customExercise.props.length" v-for="(prop, propIndex) in customExercise.props">
                        <td class="p-0">
                            <input type="text" class="form-control form-control-sm border-0 rounded-0" v-model="prop.name">
                        </td>
                        <td class="p-0">
                            <input type="text" class="form-control form-control-sm border-0 rounded-0" v-model="prop.value">
                        </td>
                        <td>
                            <a href="#" class="text-danger on-hover-opaque" v-on:click.prevent="customExercise.props.splice(propIndex, 1)">Remove</a>
                        </td>
                    </tr>
                    <tr v-else>
                        <td colspan="3">No properties defined.</td>
                    </tr>
                    </tbody>
                </table>
                <div class="d-flex align-items-baseline my-3">
                    <button class="btn btn-sm btn-primary font-weight-bold" v-on:click.prevent="addCustomExercise()">Save</button>
                    <button class="btn btn-sm btn-default border bg-white text-dark ml-2" v-on:click.prevent="showCustomAdd = !showCustomAdd">Close</button>
                </div>
            </div>
        </div>
    </div>
    <div v-if="!protocol.activities || !protocol.activities.length" class="text-secondary min-height-300px">No exercises defined yet!</div>
    <div v-else class="min-height-300px">

        <draggable v-model="protocol.activities" group="activities" @start="drag=true" @end="drag=false" handle=".sort-handle">
            <div v-for="(activity, activityIndex) in protocol.activities" :key="activity.name">
                <div class="d-flex align-items-baseline p-2 border mb-2">
                    <span class="sort-handle text-secondary mr-2 c-pointer px-1 bg-light"><i class="fa fa-sort"></i></span>
                    <img v-if="activity.image" :src="activity.image" :alt="activity.name" class="image-w90px mr-2 align-self-start">
                    <div class="flex-grow-1">
                        <div class="d-flex align-items-baseline">
                            <div class="font-weight-bold">@{{activity.name}}</div>
                            <a href="#" class="text-danger on-hover-opaque ml-auto" v-on:click.prevent="protocol.activities.splice(activityIndex, 1)">Remove</a>
                        </div>
                        <div class="d-flex align-items-baseline mt-2">
                            <div v-for="(prop, propIndex) in activity.props" class="d-inline-flex align-items-end mr-3">
                                <label class="d-inline-flex align-items-end m-0">
                                    <input type="checkbox" v-model="activity.props[propIndex].index" class="align-self-end mb-1">
                                    <span class="ml-2">@{{activity.props[propIndex].name}}</span>
                                </label>
                                <input type="text" class="form-control form-control-sm min-width-unset width-70px ml-2 rtm-prop-input" v-model="activity.props[propIndex].value">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </draggable>
    </div>
    <div class="d-flex align-items-baseline my-3">
        <button class="btn btn-sm btn-primary font-weight-bold" v-on:click.prevent="saveProtocol()">Save</button>
        <button class="btn btn-sm btn-default border bg-white text-dark ml-2" onclick="return closeStagPopup()">Close</button>
    </div>
</div>
<?php
    $data = [
        'program_notes' => @$parsed->program_notes ?: '',
        'activities' => @$parsed->activities && count($parsed->activities) ? $parsed->activities : []
    ];
?>
<script>
    (function() {
        function init() {
            new Vue({
                'el': '#protocol-builder-{{$patient->uid}}',
                delimiters: ['@{{', '}}'],
                data: {
                    filter: '',
                    programNotesEditMode: false,
                    showLibrary: false,
                    showCustomAdd: false,
                    customExercise: {
                        name: '',
                        description: '',
                        image: '',
                        video: '',
                        props: [
                            {
                                name: 'Weekly',
                                value: '',
                                include: true,
                            },
                            {
                                name: 'Daily',
                                value: '',
                                include: true,
                            },
                            {
                                name: 'Sets',
                                value: '',
                                include: true,
                            },
                            {
                                name: 'Reps',
                                value: '',
                                include: true,
                            }
                        ],
                    },
                    protocol: {!! json_encode($data) !!},
                    library: {!! json_encode(config('rtm.exercises')) !!}
                },
                methods: {
                    toggleLibrary: function() {
                        this.showLibrary = !this.showLibrary;
                        if(this.showLibrary) {
                            this.filter = '';
                        }
                    },
                    toggleCustomAdd: function() {
                        if(!this.showCustomAdd) {
                            this.customExercise = {
                                name: '',
                                description: '',
                                image: '',
                                video: '',
                                props: [
                                    {
                                        name: 'Weekly',
                                        value: '',
                                        include: true,
                                    },
                                    {
                                        name: 'Daily',
                                        value: '',
                                        include: true,
                                    },
                                    {
                                        name: 'Sets',
                                        value: '',
                                        include: true,
                                    },
                                    {
                                        name: 'Reps',
                                        value: '',
                                        include: true,
                                    }
                                ],
                            };
                        }
                        this.showCustomAdd = !this.showCustomAdd;
                    },
                    addNewProperty: function() {
                        this.customExercise.props.push({
                            name: '',
                            value: '',
                            include: true,
                        });
                    },
                    addCustomExercise: function() {
                        this.protocol.activities.push(JSON.parse(JSON.stringify(this.customExercise)));
                        this.showCustomAdd = !this.showCustomAdd;
                    },
                    addActivity: function(_exercise) {
                        if(this.isAdded(_exercise.name)) return false;
                        let activity = {
                            name: _exercise.name,
                            description: _exercise.description,
                            image: _exercise.image,
                            video: _exercise.video,
                            props: [],
                        };
                        for(let i = 0; i < _exercise.props.length; i++) {
                            activity.props.push({
                                name: _exercise.props[i],
                                value: '',
                                include: true,
                            });
                        }
                        this.protocol.activities.push(activity);
                    },
                    isAdded: function(_name) {
                        return this.protocol.activities.filter(_x => _x.name === _name).length > 0;
                    },
                    saveProtocol: function() {
                        $.post('/api/clientRtm/updateRtmMskProtocolDetailJson', {
                            uid: '{{$patient->uid}}',
                            rtmMskProtocolDetailJson: JSON.stringify(this.protocol)
                        }, _data => {
                            if(!hasResponseError(_data)) {
                                toastr.success('Protocol saved!');
                            }
                        }, 'json');
                    }
                },
                mounted: function () {
                    Vue.nextTick(() => {
                        initMoes();
                    });
                }
            })
        }
        addMCInitializer('protocol-builder-{{$patient->uid}}', init, '#protocol-builder-{{$patient->uid}}');
    }).call(window);
</script>
