<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">Delivery 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/delivery_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 Delivery Request (<?php echo date('Y') ?>)</h6>
                            <br>
                            <div class="row">
                                <table id="table_delivery" 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>Delivery Request Details</h4>

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

                <a href="<?php echo base_url('hr/serviceform_report/delivery_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['all_modules_access'][0]['access_lvl'] == 'admin' || $_SESSION['user']['division_id'] == 4){ ?>    
                                    <div class="form-group row">
                                        <label for="sv_delivery_filter_dept" class="col-lg-3">Department</label>
                                        <div class="col-lg-4" >
                                            <select class="custom-select" name="sv_delivery_filter_dept" id="sv_delivery_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_delivery_filter_status" class="col-lg-3">Status</label>
                                    <div class="col-lg-4" >
                                        <select class="custom-select" id="sv_delivery_filter_status" name="sv_delivery_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="Completed">Completed</option>
                                            <option value="Rejected">Rejected</option>
                                            <option value="Cancel">Cancel</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="form-group row">
                                    <label for="sv_delivery_filter_task" class="col-lg-3">Task</label>
                                    <div class="col-lg-4" >
                                        <select class="custom-select" id="sv_delivery_filter_task" name="sv_delivery_filter_task">
                                            <option value="-1">[All]</option>
                                            <option value="payment">Payment</option>
                                            <option value="banking">Banking</option>
                                            <option value="delivery">Delivery</option>
                                            <option value="collection">Collection</option>
                                            <option value="return">Return</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="form-group row">
                                    <label for="sv_delivery_filter_year" class="col-lg-3">Year</label>
                                    <div class="col-lg-4">
                                        <input type="text" class="form-control datepicker-yyyy" name="sv_delivery_filter_year" id="sv_delivery_filter_year">
                                    </div>
                                </div>
                                <div class="form-group row">
                                    <label for="sv_delivery_filter_month" class="col-lg-3">Month</label>
                                    <div class="col-lg-4">
                                        <input type="text" class="form-control datepicker-mm" name="sv_delivery_filter_month" id="sv_delivery_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_delivery" class="table table-bordered p-0 m-0" width="100%">
                                    <thead>
                                        <th class="text-center" width="1%">#</th>
                                        <th class="text-center" width="29%">Requestor / Creator</th>
                                        <th class="text-center" width="10%">Date</th>
                                        <th class="text-center" width="10%">Department</th>
                                        <!-- <th class="text-center">Task</th> -->
                                        <th class="text-center" width="35%">Details</th>
                                        <th class="text-center" width="10%">Status</th>
                                        <th class="text-center" width="5%">Action</th>           
                                    </thead>
                                    <tbody>
                                        <?php if($delivery_list) foreach($delivery_list as $key => $row){ ?>
                                            <tr>
                                                <td class="text-center"><?php echo $key+1; ?></td>
                                                <td>
                                                    <?php if($row['requester_department_id']){ ?>
                                                        <b>Requested By : </b><br><?php echo $row['requester_dept'].' ['.$row['requester_branch'].']'; ?>
                                                        <br><br>
                                                    <?php } ?>
                                                    <b>Created By : </b><br><?php echo $row['created_name'].' ['.$row['created_email'].']' ?>
                                                </td>
                                                <td class="text-center"><?php echo date('d-m-Y',strtotime($row['date'])) ?></td>
                                                <td><?php echo $row['requester_dept'].' ['.$row['requester_branch'].']' ?></td>
                                                <!-- <td><?php //echo ucfirst($row['task']); ?></td> -->
                                                <td>
                                                    <?php 
                                                        if($row['task'] == 'payment')
                                                        {
                                                            echo 'Task : '.ucfirst($row['task']);
                                                            echo '<br>Detail : N/A';
                                                        }else{
                                                            if($row['task'] == 'banking')
                                                            {
                                                                echo 'Task : '.ucfirst($row['task']);
                                                                echo '<br>Bank Name : '.strtoupper($row['detail_name']);
                                                                echo '<br>Remark : '.$row['detail_remark'];
                                                            }else{
                                                                echo 'Task : '.ucfirst($row['task']);
                                                                echo '<br>'.ucfirst($row['task']).' Name : '.$row['detail_name'];
                                                                echo '<br>Address : '.$row['detail_address'];
                                                                echo '<br>Item : '.$row['detail_item'];
                                                                echo '<br>Remarks : '.$row['detail_remark'];
                                                            }
                                                        }
                                                    ?>
                                                </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'] == 'Completed')
                                                        {
                                                            $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/delivery_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/delivery_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/delivery_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_delivery_filter_dept'); ?>
        <?php $this->session->unset_userdata('sv_delivery_filter_status'); ?>
        <?php $this->session->unset_userdata('sv_delivery_filter_year'); ?>
        <?php $this->session->unset_userdata('sv_delivery_filter_month'); ?>
        <?php $this->session->unset_userdata('sv_delivery_filter_task'); ?>
        <?php $this->session->unset_userdata('sv__delivery'); ?>

        $('#searchBtn').click(function(){
            getData();
        });
        
        $('#table_delivery').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');

                var task_name = hover_item.task;
                var task = (task_name.charAt(0).toUpperCase()) + (task_name.slice(1));
                if(hover_item.detail_name != '') var detail_name = hover_item.detail_name; else var detail_name = 'N/A'; 
                if(hover_item.detail_address != '') var detail_address = hover_item.detail_address; else var detail_address = 'N/A'; 
                if(hover_item.detail_item != '') var detail_item = hover_item.detail_item; else var detail_item = 'N/A'; 
                if(hover_item.detail_remark != '') var detail_remark = hover_item.detail_remark; else var detail_remark = 'N/A'; 

                if(task_name == 'payment')
                {
                    var delivery_detail = '';
                }else{
                    if(task_name == 'banking')
                    {
                        var delivery_detail = 'Bank Name : '+detail_name.toUpperCase()+'<br>Remark : '+detail_remark;
                    }else{
                        var delivery_detail = task+' Name : '+detail_name+'<br>Address : '+detail_address+'<br>Item : '+detail_item+'<br>Remarks : '+detail_remark;
                    }
                }

                if(hover_item.requester_department_id > 0)
                {
                    var department = hover_item.requester_dept+' ['+hover_item.requester_branch+']';
                }else{
                    var department = 'N/A';
                }

                tooltip = '<div class="tooltipevent"> Requested By : '+department+'<br>Task : '+task+' <br> Date : '+date+'<br>'+delivery_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 delivery booking list?", function() {
            $.ajax({
                url:'<?php echo base_url('hr/serviceform/deleteDeliveryList') ?>',
                data: {
                    deliveryID : ID,
                },
                type: 'post',
                dataType: 'json',
                success: (data) => {
                    if(data.status == "Success") {

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

                       location.reload();

                        // redirect(base_url('hr/serviceform/hotel_list'));
                    }
                }
            });
        });
    }

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

        frmData.append('sv_delivery_filter_dept',$('#sv_delivery_filter_dept').val());
        frmData.append('sv_delivery_filter_status', $('#sv_delivery_filter_status').val());
        frmData.append('sv_delivery_filter_year',$('#sv_delivery_filter_year').val());
        frmData.append('sv_delivery_filter_month',$('#sv_delivery_filter_month').val());
        frmData.append('sv_delivery_filter_task',$('#sv_delivery_filter_task').val());
        
        $.ajax({
            url:"<?php echo base_url('/hr/api/serviceform/get_delivery_filter'); ?>",
            type:'post',
            dataType:'json',
            data:frmData,
            processData: false,
            contentType: false,
            success:function(data)
            {
                iziToast.success({
                    position: 'bottomRight',
                    message: 'filtering data',
                });

                let delivery = data.table;

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

                        var requestor_name = '<b>Requested By : </b><br>'+content.requester_dept+' ['+content.requester_branch+']';
                        var creator_name = '<b>Created By : </b><br>'+content.created_name+' ['+content.created_email+']';
                        var department = content.dept_name+' ['+content.branchName+']';

                        if(content.date != '0000-00-00')
                        {
                            var date = moment(content.date).format('DD-MM-YYYY');;
                        }

                        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 == 'Completed')
                        {
                            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/delivery_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/delivery_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/delivery_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;
                        }

                        var task = (((content.task).charAt(0).toUpperCase()) + (content.task).slice(1));
                        if(content.task == 'payment')
                        {
                            var detail = 'Task : ' + task + '<br>Detail : N/A';
                        }else{
                            if(content.task == 'banking')
                            {
                                if(content.detail_name != null && content.detail_name != '')
                                {
                                    var content = ((content.detail_name).toUpperCase());
                                }else{
                                    var content = '';
                                }
                                var detail = 'Task : ' + task + '<br>Bank Name : ' + content + '<br>Remark : ' + content.detail_remark;
                            }else{
                                var detail = 'Task : ' + task + '<br>' + task + ' Name : ' + content.detail_name + '<br>Address : ' + content.detail_address + '<br>Item : ' + content.detail_item + '<br>Remarks : ' + content.detail_remark;
                            }
                        }

                        table.row.add({
                            0   : '<div class="text-center">'+i+'</div>',
                            1   : requestor_name+'<br><br>'+creator_name,
                            2   : '<div class="text-center">'+date+'</div>',
                            3   : department,
                            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.'
                });
            }
        });
    }
</script>