<section class="container-fluid" style="padding-bottom: 2rem;">
    <div class="row">
        <div class="col-md-6">
            <div class="card bg-light-transparent" style="margin-bottom: 2rem;">
                <div class="card-header bg-white">
                    <div class="float-left">
                        <h5 class="card-title">Calendar</h5>
                    </div>
                </div>
                <div class="card-body">
                    <div class="card bg-white no-shadow" style="height: 58rem;">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-12">
                                    <div id="calendar"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="card bg-light-transparent" style="margin-bottom: 2rem;">
                <div class="card-header bg-white">
                    <h5 class="card-title">QR Code CPD Request Summary</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-12">
                            <a class="btn btn-block btn-dark add-shadow" href="<?php echo base_url('hr/serviceform/qr_code_form'); ?>" style="padding-top: 1rem; padding-bottom: 1rem;">New Request</a>
                        </div>
                    </div>
                    <br>
                    <div class="card bg-white no-shadow">
                        <div class="card-body">
                            <h6>Total QR Code CPD Request (<?php echo date('Y') ?>)</h6>
                            <br>
                            <div class="row">
                                <table id="table_qr_code" class="table table-bordered table-striped table-hover mx-1">
                                    <thead>
                                        <th class="text-center">Department</th>
                                        <th class="text-center">Total Request</th>
                                    </thead>
                                    <tbody>
                                        <?php if($total_request) foreach($total_request as $total){ ?>
                                            <tr>
                                                <td><?php echo $total['dept_name'].'/'.$total['branchName']; ?></td>
                                                <td class="text-center"><?php echo $total['total_request']; ?></td>
                                            </tr>
                                        <?php } ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="card bg-light-transparent">  
        <div class="card-header bg-white">
            <div class="float-left">
                <h4>QR Code Request Details</h4>

                <a href="<?php echo base_url('hr/serviceform/qr_code_form'); ?>" class="btn btn-outline-dark btn-sm" title="Add New qr_code" target="_blank" ><i class="fa fa-plus"></i> Add New QR Code </a>

                <a href="<?php echo base_url('hr/serviceform_report/qr_code_print/'); ?>" target="_blank" class="btn btn-outline-dark btn-sm" title="Print"><i class="fa fa-print"></i>Print </a>

                <a id="btnShowFilters" type="button" class="btn btn-outline-dark btn-sm collapsed" data-trigger="hover" title="Show Filters Box" data-toggle="collapse" data-target="#collapseFilter" aria-expanded="false"><i class="fas fa-filter"></i>Show Filters</a> 
            </div>
        </div>
        <div class="collapse" id="collapseFilter">
            <div class="card-header">
                <div class="row">
                    <div class="col">
                        <div class="card no-shadow">
                            <div class="card-body">
                                <?php if($_SESSION['module_data']['role'] == 'admin'){ ?>    
                                    <div class="form-group row">
                                        <label for="sv_qr_code_filter_dept" class="col-lg-3">Department</label>
                                        <div class="col-lg-4" >
                                            <select class="custom-select" name="sv_qr_code_filter_dept" id="sv_qr_code_filter_dept">
                                                <option value="-1">[All]</option>
                                                <?php if($department) foreach($department as $row){ ?>
                                                    <option value="<?php echo $row['id']; ?>"><?php echo $row['name'].' ['.$row['branch_name'].']'; ?></option>
                                                <?php } ?>
                                            </select>
                                        </div>
                                    </div>
                                <?php } ?>
                                <div class="form-group row">
                                    <label for="sv_qr_code_filter_status" class="col-lg-3">Status</label>
                                    <div class="col-lg-4" >
                                        <select class="custom-select" id="sv_qr_code_filter_status" name="sv_qr_code_filter_status">
                                            <option value="-1">[All]</option>
                                            <option value="Pending">Pending</option>
                                            <option value="In_progress">In Progress</option>
                                            <option value="Verified">Verified</option>
                                            <option value="Approved">Approved</option>
                                            <option value="Rejected">Rejected</option>
                                            <option value="Cancel">Cancel</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="form-group row">
                                    <label for="sv_qr_code_filter_year" class="col-lg-3">Year</label>
                                    <div class="col-lg-4">
                                        <input type="text" class="form-control datepicker-yyyy" name="sv_qr_code_filter_year" id="sv_qr_code_filter_year">
                                    </div>
                                </div>
                                <div class="form-group row">
                                    <label for="sv_qr_code_filter_month" class="col-lg-3">Month</label>
                                    <div class="col-lg-4">
                                        <input type="text" class="form-control datepicker-mm" name="sv_qr_code_filter_month" id="sv_qr_code_filter_month">
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col d-print-none">
                                        <button class="btn btn-info" id="searchBtn">Search</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div> 
        <div class="tab-content">
            <div class="tab-pane fade active show" id="tableView" role="tabpanel" aria-labelledby="nav-table-tab">
                <div class="card-body">
                    <div class="card no-shadow">
                        <div class="card-body">
                            <div class="table-responsive">
                                <table id="filter_table_qr_code" class="table table-bordered p-0 m-0" width="100%">
                                    <thead>
                                        <th width="5%" class="text-center">#</th>
                                        <th width="22%" class="text-center">Requestor</th>
                                        <th width="14%" class="text-center">Department</th>
                                        <th width="14%" class="text-center">Date</th>
                                        <th width="30%" class="text-center">Details</th>
                                        <th width="10%" class="text-center">Status</th>
                                        <th width="5%" class="text-center">Action</th>           
                                    </thead>
                                    <tbody>
                                        <?php if($qr_code_list) foreach($qr_code_list as $key => $row){ ?>
                                            <tr>
                                                <td class="text-center"><?php echo $key+1; ?></td>
                                                <td>
                                                    <b>Requested By : </b><br><?php echo $row['requestor'].' ['.$row['requestor_email'].']'; ?>
                                                    <br><br>
                                                    <b>Created By : </b><br><?php echo $row['created_name'].' ['.$row['created_email'].']' ?>
                                                </td>
                                                <td><?php echo $row['dept_name'].' ['.$row['branchName'].']' ?></td>
                                                <td class="text-center">
                                                    <?php 
                                                        echo date('d-m-Y',strtotime($row['date'])); 
                                                        echo '<br>'.date('h:ia',strtotime($row['start_time'])).' - '.date('h:ia',strtotime($row['end_time'])); 
                                                    ?>
                                                </td>
                                                <td>
                                                    <?php
                                                        if($row['cpd_type_id'] == '000' || $row['cpd_type_id'] == '100') $cpd_type = 'Structured Technical';
                                                        if($row['cpd_type_id'] == '010' || $row['cpd_type_id'] == '110') $cpd_type = 'Unstructured Technical';
                                                        if($row['cpd_type_id'] == '001' || $row['cpd_type_id'] == '101') $cpd_type = 'Structured Non-Technical';
                                                        if($row['cpd_type_id'] == '011' || $row['cpd_type_id'] == '111') $cpd_type = 'Unstructured Non-Technical';

                                                        echo 'CPD Type : '.$cpd_type;
                                                        echo '<br>Title : '.$row['title'];
                                                        echo '<br>Category : '.$row['cpd_category'];
                                                        echo '<br>Topic : '.$row['topic'];
                                                        echo '<br>Organizer : '.$row['cpd_organizer'];
                                                        echo '<br>No. of Participant : '.$row['pax'];
                                                        echo '<br>CPD Hour : '.$row['cpd_hour'];
                                                        echo '<br>Event Cost : RM'.number_format($row['cost'],2);
                                                    ?>
                                                </td>
                                                <td class="text-center">
                                                    <?php 
                                                        if(($row['status_app']==null || $row['status_app']=='Pending'))
                                                        {
                                                            $status = 'Pending <i class="fa fa-exclamation-circle" style="color: #FFC107;"></i>';
                                                            $disabled = '';
                                                        }
                                                        if($row['status_app'] == 'In_progress')
                                                        {
                                                            $status = str_replace('_', ' ', $row['status_app']).' <i class="fa fa-hourglass-start" style="color: grey;"></i>';
                                                            $disabled = 'disabled style="cursor: not-allowed;"';
                                                        }
                                                        if($row['status_app'] == 'Verified')
                                                        {
                                                            $status = $row['status_app'].' <i class="fa fa-check-circle" style="color: green;"></i><p style="font-style: italic; font-size: 13px;">'.$row['status_reason'].'</p>';
                                                            $disabled = '';
                                                        }
                                                        if($row['status_app'] == 'Approved')
                                                        {
                                                            $status = $row['status_app'].' <i class="fa fa-check-circle" style="color: green;"></i>';
                                                            $disabled = 'disabled style="cursor: not-allowed;"';
                                                        }
                                                        if($row['status_app'] == 'Rejected')
                                                        {
                                                            $status = $row['status_app'].' <i class="fa fa-times-circle" style="color: red;"></i>';
                                                            $disabled = 'disabled style="cursor: not-allowed;"';
                                                        }
                                                        if($row['status_app'] == 'Cancel')
                                                        {
                                                            $status = $row['status_app'].' <i class="fa fa-times-circle" style="color: red;"></i>';
                                                            $disabled = 'disabled style="cursor: not-allowed;"';
                                                        }

                                                        echo $status;
                                                    ?> 
                                                </td>
                                                <td class="text-center">
                                                    <div class="btn-group btn-group-sm" role="group">
                                                        <a href="<?php echo base_url('hr/serviceform/qr_code_form/'.$row['ID'].'/view'); ?>" class="btn btn-outline-dark" data-trigger="hover" data-tooltip="tooltip" title="View Detail" target="_blank"><i class="fas fa-eye"></i></a>

                                                        <?php if(($_SESSION['user']['id'] == $row['requester_id']) || ($_SESSION['user']['id'] == $row['created_by'])){ ?>
                                                            <?php if($disabled == ''){ ?>
                                                                <a href="<?php echo base_url('hr/serviceform/qr_code_form/'.$row['ID']); ?>" target="_blank" class="btn btn-outline-dark" onclick="" data-trigger="hover" data-tooltip="tooltip" title="Edit"><i class="far fa-edit"></i></a>
                                                            <?php }else{ ?>
                                                                <button class="btn btn-outline-dark" data-trigger="hover" data-tooltip="tooltip" title="Edit" disabled style="cursor: not-allowed;"><i class="far fa-edit"></i></button>
                                                            <?php } ?>
                                                        <?php } ?>

                                                        <a type="button" class="btn btn-outline-dark" href="<?php echo base_url('hr/serviceform_report/qr_code_print/').$row['ID']; ?>" target="_blank" data-trigger="hover" data-tooltip="tooltip" title="Print Detail"><i class="fa fa-print"></i></a>

                                                        <?php if(($_SESSION['user']['id'] == $row['requester_id']) || ($_SESSION['user']['id'] == $row['created_by'])){ ?>
                                                            <button id="deleteButton" type="button" class="btn btn-outline-dark" onclick="deleteData(<?php echo $row['ID']; ?>);" data-trigger="hover" data-tooltip="tooltip" title="Delete" <?php echo ($disabled == '')?'':'disabled style="cursor: not-allowed;"'; ?>><i class="far fa-trash-alt"></i></button>
                                                        <?php } ?>
                                                    </div>
                                                </td>
                                            </tr>
                                        <?php } ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>      
    </div>
</section>

<style type="text/css">
    .tooltipevent
    {
        width:auto;
        height:auto;
        background:rgba(0,0,0,0.75);
        position:absolute;
        color: #fff;
        z-index:10001;
        padding:10px 10px 10px 10px ;  
        line-height: 200%;
    }
</style>

<script>
    $(document).ready(function()
    {
        <?php $this->session->unset_userdata('sv_qr_code_filter_dept'); ?>
        <?php $this->session->unset_userdata('sv_qr_code_filter_status'); ?>
        <?php $this->session->unset_userdata('sv_qr_code_filter_year'); ?>
        <?php $this->session->unset_userdata('sv_qr_code_filter_month'); ?>
        <?php $this->session->unset_userdata('sv__qr_code'); ?>

        $('#searchBtn').click(function(){
            getData();
        });
        
        $('#table_qr_code').DataTable().destroy();

        var fc_event= '';
        var resource = <?php echo $resource;?>;

        var fullcalendar = $('#calendar').fullCalendar({ 
            height: 860,
            themeSystem: 'bootstrap4',
            header: 
            {
                left: 'prev,next today',
                center: 'title',
                right: 'month,listMonth'
            },
            buttonText: {
                today: 'Today',
                month: 'Calendar',
                listMonth: 'List'
            },

            navLinks: true, // can click day/week names to navigate views
            editable: true,
            eventLimit: true, // allow "more" link when too many events
            events: <?php echo $fc_event; ?>,

            eventMouseover: function (data, event, param, resource = <?php echo $resource;?>) {
                var js_res = JSON.parse(JSON.stringify(resource));
                var hover_item = js_res[data.id];
                var title = JSON.stringify(data.title);
                var date = moment(hover_item.date).format('DD-MM-YYYY');

                if(hover_item.cpd_type_id == '000' || hover_item.cpd_type_id == '100') var cpd_type = 'Structured Technical';
                if(hover_item.cpd_type_id == '010' || hover_item.cpd_type_id == '110') var cpd_type = 'Unstructured Technical';
                if(hover_item.cpd_type_id == '001' || hover_item.cpd_type_id == '101') var cpd_type = 'Structured Non-Technical';
                if(hover_item.cpd_type_id == '011' || hover_item.cpd_type_id == '111') var cpd_type = 'Unstructured Non-Technical';

                var qr_code_detail = 'CPD Type : '+cpd_type+'<br>Title : '+hover_item.title+'<br>CPD Hour : '+hover_item.cpd_hour;

                tooltip = '<div class="tooltipevent"> Staff name : '+hover_item.requestor+' <br> Date : '+date+'<br>'+qr_code_detail+'</div>';

                $("body").append(tooltip);
                $(this).mouseover(function (e) {
                    $(this).css('z-index', 10000);
                    $('.tooltipevent').fadeIn('500');
                    $('.tooltipevent').fadeTo('10', 1.9);
                }).mousemove(function (e) {
                    $('.tooltipevent').css('top', e.pageY + 10);
                    $('.tooltipevent').css('left', e.pageX + 20);
                });
            },

            eventMouseout: function(data, event) {
                $(this).css('z-index', 8);
                $('.tooltipevent').remove();
            },
        });

        fullcalendar.fullCalendar();
    });

    function deleteData(ID)
    {
        validateForm("#deleteButton", "Delete this QR Code CPD Request list?", function() {
            $.ajax({
                url:'<?php echo base_url('hr/serviceform/deleteQRCodeList') ?>',
                data: {
                    qr_codeID : ID,
                },
                type: 'post',
                dataType: 'json',
                success: (data) => {
                    if(data.status == "Success") {

                       localStorage.setItem("status", data.status);
                       localStorage.setItem("msg", data.msg);

                       location.reload();
               }
           }
       });
        });
    }

    function getData() 
    {
        var table = $('#filter_table_qr_code').DataTable();
        table.clear().draw();
        var frmData = new FormData();

        frmData.append('sv_qr_code_filter_dept',$('#sv_qr_code_filter_dept').val());
        frmData.append('sv_qr_code_filter_status', $('#sv_qr_code_filter_status').val());
        frmData.append('sv_qr_code_filter_year',$('#sv_qr_code_filter_year').val());
        frmData.append('sv_qr_code_filter_month',$('#sv_qr_code_filter_month').val());
        
        $.ajax({
            url:"<?php echo base_url('/hr/api/serviceform/get_qr_code_filter'); ?>",
            type:'post',
            dataType:'json',
            data:frmData,
            processData: false,
            contentType: false,
            success:function(data)
            {
                iziToast.success({
                    position: 'bottomRight',
                    message: 'filtering data',
                });

                let qr_code = data.table;

                if(qr_code != null){
                    $.each(qr_code,function(key,content)
                    {
                        var i = key + 1;

                        var requestor_name = '<b>Requested By : </b><br>'+content.requestor+' ['+content.requestor_email+']';
                        var creator_name = '<b>Created By : </b><br>'+content.created_name+' ['+content.created_email+']';

                        if(content.date != '0000-00-00')
                        {
                            var date = moment(content.date).format('DD-MM-YYYY');
                            var start_time = moment(content.date+' '+content.start_time).format('h:mma');
                            var end_time = moment(content.date+' '+content.end_time).format('h:mma');
                        }

                        if(content.status_app == null || content.status_app == 'Pending')
                        {
                            var status      = 'Pending <i class="fa fa-exclamation-circle" style="color: #FFC107;"></i>';
                            var disabled    = '';
                        }
                        if(content.status_app == 'In_progress')
                        {
                            var status      = ((content.status_app).replace('_',' '))+' <i class="fa fa-hourglass-start" style="color: grey;"></i>';
                            var disabled    = 'disabled style="cursor: not-allowed;"';
                        }
                        if(content.status_app == 'Verified')
                        {
                            var status      = content.status_app+' <i class="fa fa-check-circle" style="color: green;"></i><p style="font-style: italic; font-size: 13px;">'+content.status_reason+'</p>';
                            var disabled    = '';
                        }
                        if(content.status_app == 'Approved')
                        {
                            var status      = content.status_app+' <i class="fa fa-check-circle" style="color: green;"></i>';
                            var disabled    = 'disabled style="cursor: not-allowed;"';
                        }
                        if(content.status_app == 'Rejected')
                        {
                            var status      = content.status_app+' <i class="fa fa-times-circle" style="color: red;"></i>';
                            var disabled    = 'disabled style="cursor: not-allowed;"';
                        }
                        if(content.status_app == 'Cancel')
                        {
                            var status      = content.status_app+' <i class="fa fa-times-circle" style="color: red;"></i>';
                            var disabled    = 'disabled style="cursor: not-allowed;"';
                        }

                        var btn_view = '<a href="<?php echo base_url(); ?>hr/serviceform/qr_code_form/'+content.ID+'/view" class="btn btn-outline-dark" data-trigger="hover" data-tooltip="tooltip" title="View Detail" target="_blank"><i class="fas fa-eye"></i></a>';
                        
                        var btn_print = '<a type="button" class="btn btn-outline-dark" href="<?php echo base_url();?>hr/serviceform_report/qr_code_print/'+content.ID+'" target="_blank" data-trigger="hover" data-tooltip="tooltip" title="Print Detail"><i class="fa fa-print"></i></a>';

                        if(disabled == '')
                        {
                            var btn_edit = '<a type="button" class="btn btn-outline-dark" href="<?php echo base_url();?>hr/serviceform/qr_code_form/'+content.ID+'" data-trigger="hover" data-tooltip="tooltip" title="Edit"><i class="far fa-edit"></i></a>';
                        }else{
                            var btn_edit = '<button class="btn btn-outline-dark" data-trigger="hover" data-tooltip="tooltip" title="Edit" '+disabled+'><i class="far fa-edit"></i></button>';
                        }

                        var btn_delete = '<button type="button" class="btn btn-outline-dark" onclick="deleteData('+content.ID+')" data-trigger="hover" data-tooltip="tooltip" title="Delete"'+disabled+'><i class="far fa-trash-alt"></i></button>';

                        if(('<?php echo $_SESSION['user']['id']; ?>' == content.requester_id) || ('<?php echo $_SESSION['user']['id']; ?>' == content.created_by))
                        {
                            var btn = btn_view+btn_edit+btn_print+btn_delete;
                        }else{
                            var btn = btn_view+btn_print;
                        }

                        if(content.cpd_type_id == '000' || content.cpd_type_id == '100') var cpd_type = 'Structured Technical';
                        if(content.cpd_type_id == '010' || content.cpd_type_id == '110') var cpd_type = 'Unstructured Technical';
                        if(content.cpd_type_id == '001' || content.cpd_type_id == '101') var cpd_type = 'Structured Non-Technical';
                        if(content.cpd_type_id == '011' || content.cpd_type_id == '111') var cpd_type = 'Unstructured Non-Technical';

                        var cost = number_format(content.cost,2,'.',',');

                        var detail = 'CPD Type : ' + cpd_type + '<br>Title : ' + content.title + '<br>Category : ' + content.cpd_category + '<br>Topic : ' + content.topic + '<br>Organizer : ' + content.cpd_organizer + '<br>No. of Participant : ' + content.pax + '<br>CPD Hour : ' + content.cpd_hour + '<br>Event Cost : RM' + cost;

                        table.row.add({
                            0   : '<div class="text-center">'+i+'</div>',
                            1   : requestor_name+'<br><br>'+creator_name,
                            2   : content.dept_name+' ['+content.branchName+']',
                            3   : '<div class="text-center">'+date+'<br>'+start_time+' - '+end_time+'</div>',
                            4   : detail,
                            5   : '<div class="text-center">'+status+'</div>',
                            6   : '<div class="text-center"><div class="btn-group btn-group-sm" role="group">'+btn+'</div></div>',
                        }).draw();
                        console.log(data);
                    });
                }
            },
            error:function(){
                iziToast.warning({
                    position: 'bottomRight',
                    message: '500 Internal Server Error.'
                });
            }
        });
    }

    function number_format(number, decimals, dec_point, thousands_sep) {
        number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
        var n = !isFinite(+number) ? 0 : +number,
            prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
            sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
            dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
            s = '',
            toFixedFix = function (n, prec) {
                var k = Math.pow(10, prec);
                return '' + Math.round(n * k) / k;
            };
        // Fix for IE parseFloat(0.55).toFixed(0) = 0;
        s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
        if (s[0].length > 3) {
            s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
        }
        if ((s[1] || '').length < prec) {
            s[1] = s[1] || '';
            s[1] += new Array(prec - s[1].length + 1).join('0');
        }
        return s.join(dec);
    }
</script>