<?php include 'controller/pageCode.php' ?>
<!DOCTYPE html>

<html lang="en">
    
<head>
    <meta charset="utf-8">
    <title>Messaging</title>
    <?php include 'inc/meta_inc.php'; ?>
    <!-- base css -->
    <?php include 'inc/styles_inc.php'; ?>
    <link rel="stylesheet" media="screen, print" href="assets/css/markdown.css">
    <link rel="stylesheet" media="screen, print" href="assets/css/datagrid/datatables/datatables.bundle.css">
</head>
    <body class="mod-bg-1 ">
        <!-- DOC: script to save and load page settings -->
        <script>
    
            /**
             *	This script should be placed right after the body tag for fast execution 
            *	Note: the script is written in pure javascript and does not depend on thirdparty library
            **/
            'use strict';

            var classHolder = document.getElementsByTagName("BODY")[0],
                /** 
                 * Load from localstorage
                 **/
                themeSettings = (localStorage.getItem('themeSettings')) ? JSON.parse(localStorage.getItem('themeSettings')) :
                {},
                themeURL = themeSettings.themeURL || '',
                themeOptions = themeSettings.themeOptions || '';
            /** 
             * Load theme options
             **/
            if (themeSettings.themeOptions)
            {
                classHolder.className = themeSettings.themeOptions;
                console.log("%c✔ Theme settings loaded", "color: #148f32");
            }
            else
            {
                console.log("Heads up! Theme settings is empty or does not exist, loading default settings...");
            }
            if (themeSettings.themeURL && !document.getElementById('mytheme'))
            {
                var cssfile = document.createElement('link');
                cssfile.id = 'mytheme';
                cssfile.rel = 'stylesheet';
                cssfile.href = themeURL;
                document.getElementsByTagName('head')[0].appendChild(cssfile);
            }
            /** 
             * Save to localstorage 
             **/
            var saveSettings = function()
            {
                themeSettings.themeOptions = String(classHolder.className).split(/[^\w-]+/).filter(function(item)
                {
                    return /^(nav|header|mod|display)-/i.test(item);
                }).join(' ');
                if (document.getElementById('mytheme'))
                {
                    themeSettings.themeURL = document.getElementById('mytheme').getAttribute("href");
                };
                localStorage.setItem('themeSettings', JSON.stringify(themeSettings));
            }
            /** 
             * Reset settings
             **/
            var resetSettings = function()
            {
                localStorage.setItem("themeSettings", "");
            }

        </script>
        <!-- BEGIN Page Wrapper -->
        <div class="page-wrapper">
            <div class="page-inner">
                <!-- BEGIN Left Aside -->
                <?php include 'inc/aside_inc.php' ?>
                <!-- END Left Aside -->
                <div class="page-content-wrapper">
                    <!-- BEGIN Page Header -->
                    <?php include 'inc/header_inc.php' ?>    
                    <!-- END Page Header -->
                    <!-- BEGIN Page Content -->
                    <!-- the #js-page-content id is needed for some plugins to initialize -->
                    <main id="js-page-content" Messaging="main" class="page-content">
                        <div class="row">
                            <div class="col-md-3"></div>
                            <div class="col-md-6">
                            <div id="panel-1" class="panel">
                                    <div class="panel-hdr">
                                        <h2>
                                        Send SMS
                                        </h2>
                                        
                                    </div>
                                    <div class="panel-container show">
                                        <div class="panel-content">
                                            <div class="form-row form-group">
                                            <div class="col-md-12 mb-3">
                                                    <label class="form-label" for="choice">Send To?<span class="text-danger">*</span> </label><br>  
                                                    <select class="custom-select select2"  id="choice" style="width:300px" name="choice" required>
                                                        <option value="">Send To</option>
                                                        <option value="*">Send To All Employees</option>
                                                        <option value="single">Send To Employee(s)</option>
                                                        <option value="group">Send To a Group/Role</option>
                                                        <option value="students">Send To students</option>
                                                        <option value="student">Send To student(s)</option>
                                                    </select>
                                                    <div class="invalid-feedback">
                                                        Please provide a valid value.
                                                    </div>
                                                </div>
                                                <div class="col-md-12 mb-3 role d-none">
                                                    <label class="form-label" for="role">Select Group/Role<span class="text-danger">*</span> </label><br>  
                                                    <select class="custom-select select2" multiple id="roles" style="width:300px" name="role" required>
                                                        <option value="">Select Group/Role</option>
                                                        <?php foreach($roles as $key): ?>
                                                        <option value="<?php echo $key['role_id']; ?>"><?php echo $key['role_name']; ?></option>
                                                        <?php endforeach ?>
                                                    </select>
                                                    <div class="invalid-feedback">
                                                        Please provide a valid value.
                                                    </div>
                                                </div>
                                                <div class="col-md-12 mb-3 employee d-none">
                                                    <label class="form-label" for="employee">Select Employee(s)<span class="text-danger">*</span> </label><br>  
                                                    <select class="custom-select select2" multiple id="employee" style="width:300px" name="student" required>
                                                        <option value="">Select Employee(s)</option>
                                                        <?php foreach($employees as $key): ?>
                                                        <option value="<?php echo $key['employee_phone']; ?>"><?php echo $key['employee_name'].' | '.$key['role_name'].' | '.$key['employee_phone']; ?></option>
                                                        <?php endforeach ?>
                                                    </select>
                                                    <div class="invalid-feedback">
                                                        Please provide a valid value.
                                                    </div>
                                                </div>
                                                <div class="col-md-12 mb-3 student d-none">
                                                    <label class="form-label" for="student">Select Student(s)<span class="text-danger">*</span> </label><br>  
                                                    <select class="custom-select select2"  id="student" style="width:300px" name="student" required>
                                                        <option value="">Select Student</option>
                                                        <?php foreach($students as $key): ?>
                                                        <option value="<?php echo $key['student_id']; ?>"><?php echo $key['student_name'].' | '.$key['student_email'].' | '.$key['student_phone']; ?></option>
                                                        <?php endforeach ?>
                                                    </select>
                                                    <div class="invalid-feedback">
                                                        Please provide a valid value.
                                                    </div>
                                                </div>
                                            <div class="col-md-12 mb-3">
                                                <label class="form-label" for="reason">Provide Reason <span class="text-danger"></span> </label>
                                                <input type="text" class="form-control" name="reason" id="reason" placeholder="Provide Reason" value="" >
                                                <div class="valid-feedback">
                                                    Looks good.
                                                </div>
                                            </div>
                                            <div class="col-md-12 mb-3">
                                                <label class="form-label" for="message">Provide Message <span class="text-danger"></span> </label>
                                                <textarea type="text" class="form-control" name="message" id="message" placeholder="Message" ></textarea>
                                                <div class="valid-feedback">
                                                    Looks good.
                                                </div>
                                            </div>

                                            <div class="col-md-12 mb-3 save_btn">
                                                <button class="btn btn-primary ml-auto" id="send_btn" type="submit" >Send SMS</button>
                                            </div>

                                </div>
                                </div>
                                </div>
                                </div>
                            </div>
                            <div class="col-md-3"></div>
                        </div>
                        <div class="row">
                            <div class="col-md-12">
                                <div id="panel-1" class="panel">
                                    <div class="panel-hdr">
                                        <h2>
                                        Messaging History
                                        </h2>
                                        
                                    </div>
                                    <div class="panel-container show">
                                        <div class="panel-content">
                                            
                                        <div class="row">
                                                <div class="col-md-12">
                                                    <!-- datatable start -->
                                                    <table id="dt-basic-example" class="table table-bordered table-hover table-striped w-100"></table>
                                                    <!-- datatable end -->
                                                </div>
                                            
                                            </div>
                                            
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </main>
                    <!-- this overlay is activated only when mobile menu is triggered -->
                    <div class="page-content-overlay" data-action="toggle" data-class="mobile-nav-on"></div> <!-- END Page Content -->
                    <!-- BEGIN Page Footer -->
                <?php include 'inc/footer_inc.php' ?>
        <?php include 'inc/script_inc.php' ?>
        <script src="assets/js/datagrid/datatables/datatables.bundle.js"></script>
        <script src="assets/js/datagrid/datatables/datatables.export.js"></script>
        <script>
            $(document).ready(function()
            {
                toastr.options = {
                    "closeButton": true,
                    "debug": false,
                    "newestOnTop": true,
                    "progressBar": true,
                    "positionClass": "toast-top-right",
                    "preventDuplicates": true,
                    "onclick": null,
                    "showDuration": 300,
                    "hideDuration": 5000,
                    "timeOut": 5000,
                    "extendedTimeOut": 1000,
                    "showEasing": "swing",
                    "hideEasing": "linear",
                    "showMethod": "fadeIn",
                    "hideMethod": "fadeOut"
                }
                
                var container;
                //SMS
                $('#choice').on('change',function(){
                    var choice = $('#choice').val();
                    if(choice =='*'){
                        $('.role').addClass('d-none');
                        $('.employee').addClass('d-none');
                        $('.student').addClass('d-none');
                        container = '*';
                    }else if(choice == 'group'){
                        $('.role').removeClass('d-none');
                        $('.employee').addClass('d-none');
                        $('.student').addClass('d-none');
                        container = 'group';
                    }else if(choice == 'single'){
                        container = 'single';
                        $('.student').addClass('d-none');
                        $('.employee').removeClass('d-none');
                        $('.role').addClass('d-none');
                    }else if(choice == 'students'){
                        container = 'students';
                        $('.role').addClass('d-none');
                        $('.employee').addClass('d-none');
                        $('.student').addClass('d-none');
                    }else if(choice == 'student'){
                        container = 'student';
                        $('.student').removeClass('d-none');
                        $('.role').addClass('d-none');
                        $('.employee').addClass('d-none');
                    }
                    else{
                        $('.role').addClass('d-none');
                        $('.employee').addClass('d-none');
                        $('.student').addClass('d-none');
                    }
                });

                $('#send_btn').click(function(){
                    var choice =  $('#choice').val();
                    if(!choice){
                        $('#send_btn').text('Send');
                        Swal.fire(
                        {
                            type: "error",
                            title: "Select an Entity to continue",
                            showConfirmButton: false,
                            timer: 2500
                        });
                        return false;
                    }else{
                        $('#send_btn').text('Sending...');
                    }
                    
                    var reason = $('#reason').val();
                    var message = $('#message').val();
                    var serverData = {

                    };
                    if(container=='single'){
                        var employee = $('#employee').val();
                        serverData = {
                            all:'',
                            roles:'',
                            students:'',
                            student:'',
                            employee:employee,
                            message:message,
                            reason:reason,
                            send_sms:''
                        };
                    }else if(container=='group'){
                        var roles = $('#roles').val();
                        serverData = {
                            all:'',
                            roles:roles,
                            employee:'',
                            students:'',
                            student:'',
                            message:message,
                            reason:reason,
                            send_sms:''
                        };
                    }else if(container=='*'){
                        var employees = $('#employees').val();
                        serverData = {
                            all:'*',
                            roles:'',
                            employee:'',
                            student:'',
                            students:'',
                            message:message,
                            reason:reason,
                            send_sms:''
                        };
                    }else if(container=='students'){
                        var employee = $('#employee').val();
                        serverData = {
                            all:'',
                            roles:'',
                            students:'students',
                            student:'',
                            employee:'',
                            message:message,
                            reason:reason,
                            send_sms:''
                        };
                    }else if(container=='student'){
                        var student = $('#student').val();
                        serverData = {
                            all:'',
                            roles:'',
                            students:'',
                            student:student,
                            employee:'',
                            message:message,
                            reason:reason,
                            send_sms:''
                        };
                    }

                    $.post('controller/messagingCode.php',serverData,function(res){
                        console.log(res);
                        var response = JSON.parse(res);
                        $('#send_btn').text('Send SMS');
                        if(response.message=="success"){
                            $('#dt-basic-example').DataTable().ajax.reload();
                            Swal.fire(
                                {
                                    type: "success",
                                    title: "Sent Successfully",
                                    showConfirmButton: false,
                                    timer: 2500
                                });
                                
                        }else{
                            Swal.fire(
                                {
                                    type: "error",
                                    title: "Chech your connection or SMS bundle. Some SMS might not have been sent",
                                    showConfirmButton: false,
                                    timer: 2500
                                });
                        }
                    });
                });

                // Event Lot
                var events = $("#app-eventlog");
                // Column Definitions
                var columnSet = [
                {
                    title: "RowId",
                    id: "messaging_id",
                    data: "messaging_id",
                    placeholderMsg: "Server Generated ID",
                    "visible": false,
                    "searchable": false,
                    type: "hidden"
                },
                {
                    title: "Message",
                    id: "message",
                    data: "message",
                    placeholderMsg: "Message",
                    type: "readonly",
                },
                {
                    title: "Receiver",
                    id: "receiver",
                    data: "receiver",
                    placeholderMsg: "Receiver",
                    type: "readonly",
                },
                {
                    title: "Reason",
                    id: "reason",
                    data: "reason",
                    placeholderMsg: "Reason",
                    type: "readonly",
                },
                {
                    title: "Date Created",
                    id: "date_created",
                    data: "date_created",
                    type: "readonly",
                }

                
            ]

                //Get domain
                var BaseUrl = window.location.origin;
                /* start data table */
                var myTable = $('#dt-basic-example').dataTable(
                {
                    /* check datatable buttons page for more info on how this DOM structure works */
                    dom: "<'row mb-3'<'col-sm-12 col-md-6 d-flex align-items-center justify-content-start'f><'col-sm-12 col-md-6 d-flex align-items-center justify-content-end'B>>" +
                        "<'row'<'col-sm-12'tr>>" +
                        "<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
                    ajax: "controller/messagingCode.php?::=",
                    columns: columnSet,
                    /* selecting multiple rows will not work */
                    select: 'single',
                    /* altEditor at work */
                    altEditor: true,
                    responsive: true,
                    /* buttons uses classes from bootstrap, see buttons page for more details */
                    buttons: [
                        {
                        extend: 'colvis',
                        text: 'Visibility',
                        titleAttr: 'Col visibility',
                        className: 'btn-xs btn-outline-default'
                    },
                    {
                        extend: 'pdfHtml5',
                        text: 'PDF',
                        titleAttr: 'Generate PDF',
                        className: 'btn-danger btn-xs mr-1'
                    },
                    
                    {
                        extend: 'csvHtml5',
                        text: 'CSV',
                        titleAttr: 'Generate CSV',
                        className: 'btn-success btn-xs mr-1'
                    },
                    {
                        extend: 'copyHtml5',
                        text: 'Copy',
                        titleAttr: 'Copy to clipboard',
                        className: 'btn-dark btn-xs mr-1'
                    },
                    {
                        extend: 'print',
                        text: 'Print',
                        titleAttr: 'Print Table',
                        className: 'btn-outline-primary btn-xs'
                    },
                    {
                        extend: 'selected',
                        text: '<i class="fal fa-times mr-1"></i> Delete',
                        name: 'delete',
                        className: 'btn-danger btn-xs mr-1'
                    },
                    {
                        text: '<i class="fal fa-sync mr-1"></i>',
                        name: 'refresh',
                        className: 'btn-primary btn-xs'
                    }],
                    columnDefs: [
                    {
                        
                    }
                    ],
                    /* default callback for insertion: mock webservice, always success */
                    onAddRow: function(dt, rowdata, success, error)
                    {
                        var myFormData = new FormData();
                        myFormData.append('Messaging_name',rowdata.Messaging_name);
                        myFormData.append('add_Messaging','');
                        rowdata['messaging_id'] = '';
                        success(rowdata);
                        
                        $.ajax({
                            url: 'controller/messagingCode.php',
                            type: 'POST',
                            processData: false, // important
                            contentType: false, // important
                            dataType : 'json',
                            data: myFormData,
                            beforeSend:function(res){
                            },
                            complete:function(res){
                            },
                            success:function(res){
                                console.log(res);
                                Swal.fire(
                                {
                                    type: "success",
                                    Messaging: "Add Successful",
                                    showConfirmButton: false,
                                    timer: 2500
                                });
                            },
                            error:function(res){
                            console.log(res);
                            }
                        });
                        

                        // demo only below:
                        events.prepend('<p class="text-success fw-500">' + JSON.stringify(rowdata, null, 4) + '</p>');
                    },
                    onEditRow: function(dt, rowdata, success, error)
                    {
                        success(rowdata);
                        var myFormData = new FormData();
                        myFormData.append('messaging_id',rowdata.messaging_id);
                        myFormData.append('Messaging_name',rowdata.Messaging_name);
                        myFormData.append('edit_Messaging','');
                        success(rowdata);
                        console.log(myFormData);
                        $.ajax({
                            url: 'controller/messagingCode.php',
                            type: 'POST',
                            processData: false, // important
                            contentType: false, // important
                            dataType : 'json',
                            data: myFormData,
                            beforeSend:function(res){
                                // console.log(e);
                            },
                            complete:function(res){
                            },
                            success:function(res){
                                Swal.fire(
                                    {
                                        type: "success",
                                        Messaging: "Edit Successful",
                                        showConfirmButton: false,
                                        timer: 2500
                                    });
                            },
                            error:function(res){
                            console.log(res);
                            }
                        });

                        // demo only below:
                        events.prepend('<p class="text-info fw-500">' + JSON.stringify(rowdata, null, 4) + '</p>');
                    },
                    onDeleteRow: function(dt, rowdata, success, error)
                    {
                        Swal.fire(
                        {
                            type: "success",
                            Messaging: "Delete Successful",
                            showConfirmButton: false,
                            timer: 2500
                        });
                        success(rowdata);
                        console.log(rowdata);
                        var messaging_id = rowdata.messaging_id;
                        $.post('controller/messagingCode.php?del_Messaging='+messaging_id,function(del_res){
                            Swal.fire(
                            {
                                type: "success",
                                Messaging: "Delete Successful",
                                showConfirmButton: false,
                                timer: 2500
                            });
                        });
                    

                        // demo only below:
                        events.prepend('<p class="text-danger fw-500">' + JSON.stringify(rowdata, null, 4) + '</p>');
                    },
                });

                $('.select2').select2();

                $(".select2-placeholder-multiple").select2(
                {
                    placeholder: "Select State"
                });
                $(".js-hide-search").select2(
                {
                    minimumResultsForSearch: 1 / 0
                });
                $(".js-max-length").select2(
                {
                    maximumSelectionLength: 2,
                    placeholder: "Select maximum 2 items"
                });
                $(".select2-placeholder").select2(
                {
                    placeholder: "Select a state",
                    allowClear: true
                });

                $(".js-select2-icons").select2(
                {
                    minimumResultsForSearch: 1 / 0,
                    templateResult: icon,
                    templateSelection: icon,
                    escapeMarkup: function(elm)
                    {
                        return elm
                    }
                });

                function icon(elm)
                {
                    elm.element;
                    return elm.id ? "<i class='" + $(elm.element).data("icon") + " mr-2'></i>" + elm.text : elm.text
                }

            });

        </script>
    </body>

</html>
