/* ----------------------------------------------------------------------------
 * Easy!Appointments - Open Source Web Scheduler
 *
 * @package     EasyAppointments
 * @author      A.Tselegidis <alextselegidis@gmail.com>
 * @copyright   Copyright (c) 2013 - 2018, Alex Tselegidis
 * @license     http://opensource.org/licenses/GPL-3.0 - GPLv3
 * @link        http://easyappointments.org
 * @since       v1.0.0
 * ---------------------------------------------------------------------------- */

(function () {

    'use strict';

    /**
     * CasesHelper Class
     *
     * This class contains the methods that are used in the backend casess page.
     *
     * @class CasesHelper
     */
    function CasesHelper() {
        this.filterResults = {};
    }

    /**
     * Binds the default event handlers of the backend casess page.
     */
    CasesHelper.prototype.bindEventHandlers = function () {
        var instance = this;

        /**
         * Event: Filter casess Form "Submit"
         */
        $('#filter-casess form').submit(function (event) {
            var key = $('#filter-casess .key').val();
            $('#filter-casess .selected').removeClass('selected');
            instance.resetForm();
            instance.filter(key);
            return false;
        });

        /**
         * Event: Filter casess Clear Button "Click"
         */
        $('#filter-casess .clear').click(function () {
            $('#filter-casess .key').val('');
            instance.filter('');
            instance.resetForm();
        });

        /**
         * Event: Filter Entry "Click"
         *
         * Display the cases data of the selected row.
         */
        $(document).on('click', '.entry', function () {
            if ($('#filter-casess .filter').prop('disabled')) {
                return; // Do nothing when user edits a cases record.
            }

            var casesId = $(this).attr('data-id');
            var cases = {};
            $.each(instance.filterResults, function (index, item) {
                if (item.RecordID == casesId) {
                    cases = item;
                    return false;
                }
            });

            instance.display(cases);
            $('#filter-casess .selected').removeClass('selected');
            $(this).addClass('selected');
            $('#edit-cases, #delete-cases').prop('disabled', false);
            $('#gen-appt').prop('disabled', false);

        });

        /**
         * Event: Appointment Row "Click"
         *
         * Display appointment data of the selected row.
         */
        $(document).on('click', '.appointment-row', function () {
            $('#cases-appointments .selected').removeClass('selected');
            $(this).addClass('selected');

            var casesId = $('#filter-casess .selected').attr('data-id');
            var appointmentId = $(this).attr('data-id');
            var appointment = {};

            $.each(instance.filterResults, function (index, c) {
                if (c.id === casesId) {
                    $.each(c.appointments, function (index, a) {
                        if (a.id == appointmentId) {
                            appointment = a;
                            return false;
                        }
                    });
                    return false;
                }
            });

            instance.displayAppointment(appointment);
        });

        /**
         * Event: Add cases Button "Click"
         */
        $('#add-cases').click(function () {
            instance.resetForm();
            $('#add-edit-delete-group').hide();
            $('#save-cancel-group').show();
            $('.record-details').find('input, textarea').prop('readonly', false);

            $('#filter-casess button').prop('disabled', true);
            $('#filter-casess .results').css('color', '#AAA');
        });

        /**
         * Event: Edit cases Button "Click"
         */
        $('#edit-cases').click(function () {
            $('.record-details').find('input, textarea').prop('readonly', false);
            $('#add-edit-delete-group').hide();
            $('#save-cancel-group').show();

            $('#filter-casess button').prop('disabled', true);
            $('#filter-casess .results').css('color', '#AAA');
        });




        $('#gen-appt').click(function () {
            var apptlink = {
                case_id: $('#cases-id').val(),
                service_id: $('#serviceforlink').val(),
            };
            instance.saveapptlink(apptlink)



            /*var methodid=$('#cases-id').val();
            var dedicatedUrl = GlobalVariables.baseUrl + '/view_config_doc.php?mid=' + methodid;
            window.open(dedicatedUrl, '_blank').focus();*/
        });

        /**
         * Event: Cancel cases Add/Edit Operation Button "Click"
         */
        $('#cancel-cases').click(function () {
            var id = $('#cases-id').val();
            instance.resetForm();
            if (id != '') {
                instance.select(id, true);
            }
        });

        /**
         * Event: Save Add/Edit cases Operation "Click"
         */
        $('#save-cases').click(function () {
            var cases = {
                first_name: $('#first-name').val(),
                last_name: $('#last-name').val(),
                email: $('#email').val(),
                phone_number: $('#phone-number').val(),
                address: $('#address').val(),
                city: $('#city').val(),
                zip_code: $('#zip-code').val(),
                notes: $('#notes').val(),
                birthdate: $('#birth-date').val(),
            };

            if ($('#cases-id').val() != '') {
                cases.id = $('#cases-id').val();
            }

            if (!instance.validate()) {
                return;
            }

            instance.save(cases);
        });

        /**
         * Event: Delete cases Button "Click"
         */
        $('#delete-cases').click(function () {
            var casesId = $('#cases-id').val();
            var buttons = [
                {
                    text: EALang.delete,
                    click: function () {
                        instance.delete(casesId);
                        $('#message_box').dialog('close');
                    }
                },
                {
                    text: EALang.cancel,
                    click: function () {
                        $('#message_box').dialog('close');
                    }
                }
            ];

            GeneralFunctions.displayMessageBox(EALang.delete_cases,
                EALang.delete_record_prompt, buttons);
        });
    };

    /**
     * Save a cases record to the database (via ajax post).
     *
     * @param {Object} cases Contains the cases data.
     */
    CasesHelper.prototype.save = function (cases) {
        var postUrl = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_save_cases';
        var postData = {
            csrfToken: GlobalVariables.csrfToken,
            cases: JSON.stringify(cases)
        };

        $.post(postUrl, postData, function (response) {
            if (!GeneralFunctions.handleAjaxExceptions(response)) {
                return;
            }

            Backend.displayNotification(EALang.cases_saved);
            this.resetForm();
            $('#filter-casess .key').val('');
            this.filter('', response.id, true);
        }.bind(this), 'json').fail(GeneralFunctions.ajaxFailureHandler);
    };


    CasesHelper.prototype.saveapptlink = function (apptlink) {
        var success = false;
        var postUrl = GlobalVariables.baseUrl + '/index.php/backend_api/add_apptlink';
        var postData = {
            csrfToken: GlobalVariables.csrfToken,
            apptlink: JSON.stringify(apptlink)
        };

        $.post(postUrl, postData, function (response) {
            if (!GeneralFunctions.handleAjaxExceptions(response)) {
                return;
            }else{
                success=true;

            }
            
            if(response.status == 'SUCCESS' && success==true){
            
            Backend.displayNotification('Link made');
            var dedicatedUrl = GlobalVariables.baseUrl + '/?apptlink=' + response.id;
            
            var buttons = [
               
                {
                    text: EALang.cancel,
                    click: function () {
                        $('#message_box').dialog('close');
                    }
                }
            ];

            GeneralFunctions.displayMessageBox('View Link',
               'Click here to view <br>'+ '<a href='+'"'+dedicatedUrl+'"'+' target="_blank">CLICK</a>', buttons);
                
            /*if(dedicatedUrl!==null && dedicatedUrl!==undefined){
            
            alert(dedicatedUrl);
            window.open(dedicatedUrl, '_blank').focus();
            }
            */
            
            }

        }.bind(this), 'json').fail(GeneralFunctions.ajaxFailureHandler);
    };


    /**
     * Delete a cases record from database.
     *
     * @param {Number} id Record id to be deleted.
     */
    CasesHelper.prototype.delete = function (id) {
        var postUrl = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_delete_cases';
        var postData = {
            csrfToken: GlobalVariables.csrfToken,
            cases_id: id
        };

        $.post(postUrl, postData, function (response) {
            if (!GeneralFunctions.handleAjaxExceptions(response)) {
                return;
            }

            Backend.displayNotification(EALang.cases_deleted);
            this.resetForm();
            this.filter($('#filter-casess .key').val());
        }.bind(this), 'json').fail(GeneralFunctions.ajaxFailureHandler);
    };

    /**
     * Validate cases data before save (insert or update).
     */
    CasesHelper.prototype.validate = function () {
        $('#form-message')
            .removeClass('alert-danger')
            .hide();
        $('.has-error').removeClass('has-error');

        try {
            // Validate required fields.
            var missingRequired = false;

            $('.required').each(function () {
                if ($(this).val() == '') {
                    $(this).closest('.form-group').addClass('has-error');
                    missingRequired = true;
                }
            });

            if (missingRequired) {
                throw EALang.fields_are_required;
            }

            // Validate email address.
            if (!GeneralFunctions.validateEmail($('#email').val())) {
                $('#email').closest('.form-group').addClass('has-error');
                throw EALang.invalid_email;
            }

            return true;
        } catch (message) {
            $('#form-message')
                .addClass('alert-danger')
                .text(message)
                .show();
            return false;
        }
    };

    /**
     * Bring the cases form back to its initial state.
     */
    CasesHelper.prototype.resetForm = function () {
        $('.record-details').find('input, textarea').val('');
        $('.record-details').find('input, textarea').prop('readonly', true);

        $('#cases-appointments').empty();
        $('#appointment-details').toggleClass('hidden', true).empty();
        $('#edit-cases, #delete-cases').prop('disabled', true);
        $('#gen-appt').prop('disabled', true);

        $('#add-edit-delete-group').show();
        $('#save-cancel-group').hide();

        $('.record-details .has-error').removeClass('has-error');
        $('.record-details #form-message').hide();

        $('#filter-casess button').prop('disabled', false);
        $('#filter-casess .selected').removeClass('selected');
        $('#filter-casess .results').css('color', '');
    };

    /**
     * Display a cases record into the form.
     *
     * @param {Object} cases Contains the cases record data.
     */
    CasesHelper.prototype.display = function (cases) {
        $('#cases-id').val(cases.RecordID);
        $('#contact-name').val(cases.ContactName);
        $('#entity').val(cases.Entity);
        $('#created-date').val(cases.CreatedDate);
        $('#created-by').val(cases.CreatedBy);
        $('#closed-date').val(cases.ClosedDate);
        $('#subject').val(cases.Subject);
        $('#description').val(cases.Description);


        $('#cases-appointments').empty();
        $.each(cases.appointments, function (index, appointment) {
            if (GlobalVariables.user.role_slug === Backend.DB_SLUG_PROVIDER && parseInt(appointment.id_users_provider) !== GlobalVariables.user.id) {
                return true; // continue
            }

            if (GlobalVariables.user.role_slug === Backend.DB_SLUG_SECRETARY && GlobalVariables.secretaryProviders.indexOf(appointment.id_users_provider) === -1) {
                return true; // continue
            }

            var start = GeneralFunctions.formatDate(Date.parse(appointment.start_datetime), GlobalVariables.dateFormat, true);
            var end = GeneralFunctions.formatDate(Date.parse(appointment.end_datetime), GlobalVariables.dateFormat, true);
            var html =
                '<div class="appointment-row" data-id="' + appointment.id + '">' +
                start + ' - ' + end + '<br>' +
                appointment.service.name + ', ' +
                appointment.provider.first_name + ' ' + appointment.provider.last_name +
                '</div>';
            $('#cases-appointments').append(html);
        });

        $('#appointment-details').empty();
    };

    /**
     * Filter cases records.
     *
     * @param {String} key This key string is used to filter the cases records.
     * @param {Number} selectId Optional, if set then after the filter operation the record with the given
     * ID will be selected (but not displayed).
     * @param {Boolean} display Optional (false), if true then the selected record will be displayed on the form.
     */
    CasesHelper.prototype.filter = function (key, selectId, display) {
        display = display || false;

        var selectedentity = GeneralFunctions.getUrlParameter(location.href, 'entity');
            if(selectedentity==''){
                var postUrl = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_filter_casess';
                var postData = {
                    csrfToken: GlobalVariables.csrfToken,
                    key: key
                };
            }else{
                var postUrl = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_filter_cases_fromentity';
                var postData = {
                    csrfToken: GlobalVariables.csrfToken,
                    key: selectedentity
                };

            }

        $.post(postUrl, postData, function (response) {
            if (!GeneralFunctions.handleAjaxExceptions(response)) {
                return;
            }

            this.filterResults = response;

            console.log(response);
            $('#filter-casess .results').html('');
            $.each(response, function (index, cases) {
                var html = this.getFilterHtml(cases);
                $('#filter-casess .results').append(html);
            }.bind(this));
            if (response.length == 0) {
                $('#filter-casess .results').html('<em>' + EALang.no_records_found + '</em>');
            }

            if (selectId != undefined) {
                this.select(selectId, display);
            }

        }.bind(this), 'json').fail(GeneralFunctions.ajaxFailureHandler);
    };

    /**
     * Get the filter results row HTML code.
     *
     * @param {Object} cases Contains the cases data.
     *
     * @return {String} Returns the record HTML code.
     */
    CasesHelper.prototype.getFilterHtml = function (cases) {

        var entity = cases.Entity;
        var name = 'Created' + ' ' + cases.CreatedDate;
        var info = 'Created By' +cases.CreatedBy;
        var html =
            '<div class="entry" data-id="' + cases.RecordID + '">' +
            '<strong>' +
            cases.Subject+
            '</strong><br>'+
            '<strong>' +
            entity +
            '</strong><br>' +

            '<strong>' +
            name +
            '</strong><br>' +
            info +
            '</div><hr>';

        return html;
    };

    /**
     * Select a specific record from the current filter results.
     *
     * If the cases id does not exist in the list then no record will be selected.
     *
     * @param {Number} id The record id to be selected from the filter results.
     * @param {Boolean} display Optional (false), if true then the method will display the record
     * on the form.
     */
    CasesHelper.prototype.select = function (id, display) {
        display = display || false;

        $('#filter-casess .selected').removeClass('selected');

        $('#filter-casess .entry').each(function () {
            if ($(this).attr('data-id') == id) {
                $(this).addClass('selected');
                return false;
            }
        });

        if (display) {
            $.each(this.filterResults, function (index, cases) {
                if (cases.RecordID == id) {
                    this.display(cases);
                    $('#edit-cases, #delete-cases').prop('disabled', false);
                    $('#gen-appt').prop('disabled', false);

                    return false;
                }
            }.bind(this));
        }
    };

    /**
     * Display appointment details on casess backend page.
     *
     * @param {Object} appointment Appointment data
     */
    CasesHelper.prototype.displayAppointment = function (appointment) {
        var start = GeneralFunctions.formatDate(Date.parse(appointment.start_datetime), GlobalVariables.dateFormat, true);
        var end = GeneralFunctions.formatDate(Date.parse(appointment.end_datetime), GlobalVariables.dateFormat, true);

        var html =
            '<div>' +
            '<strong>' + appointment.service.name + '</strong><br>' +
            appointment.provider.first_name + ' ' + appointment.provider.last_name + '<br>' +
            start + ' - ' + end + '<br>' +
            '<a style="color:green" href=' + '"' + GlobalVariables.baseUrl + '/index.php/backend?edit=y&apptid=' + appointment.id + '"' + ' target="_blank" > EDIT </a>'
            + '<br>' +
            '<a style="color:red" href=' + '"' + GlobalVariables.baseUrl + '/index.php/backend?del=y&apptid=' + appointment.id + '"' + ' target="_blank" > DELETE </a>'

        '</div>';

        $('#appointment-details').html(html).removeClass('hidden');
    };

    window.CasesHelper = CasesHelper;
})();
