<div class="container-fluid" style="padding-bottom: 2rem;">
    <div class="container-fluid">
        <div class="card bg-light-transparent">  
            <div class="card-header bg-white">
                <h4>Job Request List</h4>
                <a href="<?php echo base_url('hr/serviceform/job_request_form'); ?>" class="btn btn-outline-dark btn-sm" title="Add New Job Request"><i class="fa fa-plus"></i> Add New Request</a>

                <a href="<?php echo base_url('hr/Serviceform_report/job_request_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 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'][1]['access_lvl'] == 'admin'){ ?>
                                        <div class="form-group row">
                                            <label for="sv_job_request_filter_dept" class="col-lg-3">
                                                Department
                                            </label>                           
                                            <div class="col-lg-4" >
                                                <select class="custom-select" name="sv_job_request_filter_dept" id="sv_job_request_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_job_request_filter_client_id" class="col-lg-3">
                                            Client
                                        </label>                           
                                        <div class="col-lg-4" >
                                            <select class="select" name="sv_job_request_filter_client_id" id="sv_job_request_filter_client_id">
                                                <option value="-1">[All]</option>
                                                <?php if($client) foreach($client as $row){ ?>
                                                    <option value="<?php echo $row->id; ?>"><?php echo $row->name; ?></option> 
                                                <?php } ?>
                                            </select>
                                        </div>
                                    </div>    
                                    <div class="form-group row">
                                        <label for="sv_job_request_filter_status" class="col-lg-3">
                                            Status
                                        </label>                           
                                        <div class="col-lg-4" >
                                            <select class="custom-select" id="sv_job_request_filter_status" name="sv_job_request_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_job_request_filter_year" class="col-lg-3">
                                            Year
                                        </label>                           
                                        <div class="col-lg-4" >
                                            <input type="text" name="sv_job_request_filter_year" id="sv_job_request_filter_year" class="form-control datepicker-yyyy">
                                        </div>
                                    </div>
                                    <div class="form-group row">
                                        <label for="sv_job_request_filter_month" class="col-lg-3">
                                            Requested Month
                                        </label>                           
                                        <div class="col-lg-4" >
                                            <input type="text" name="sv_job_request_filter_month" id="sv_job_request_filter_month" class="form-control datepicker-mm">
                                        </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_job_request" class="table table-bordered p-0 m-0" width="100%">
                                        <thead>
                                            <th class="text-center" width="1%">#</th>
                                            <th class="text-center" width="20%">Requestor</th>
                                            <th class="text-center" width="20%">Department</th>
                                            <th class="text-center" width="15%">Client</th>
                                            <th class="text-center" width="25%">Detail</th>
                                            <th class="text-center" width="10%">Status</th>
                                            <th class="text-center" width="9%">Action</th>
                                        </thead>

                                        <tbody>
                                            <?php if(!empty($job_request_list)) { ?> 
                                                <?php foreach($job_request_list as $key => $row) { ?>
                                                    <tr>
                                                        <td class="text-center"><?php echo $key+1; ?></td>
                                                        <td><b>Requested By : </b><br><?php echo $row['requester_name'].' ['.$row['requester_email'].']'; ?></td>
                                                        <td><?php echo $row['dept_name'].' ['.$row['branchName'].']'; ?></td>
                                                        <td><?php echo $row['client_name']; ?></td>
                                                        <td>
                                                            <?php 
                                                                echo '<b>Description </b> : '.$row['description']; 
                                                                echo '<br><b>Year End </b> : '.$row['yearEndDate'];
                                                                echo (strtotime($row['deadline']) > 0)?'<br><b>Deadline </b> : '.date('d-m-Y', strtotime($row['deadline'])):'';
                                                                echo ($row['remarks'])?'<br><b>Remarks </b> : '.$row['remarks']:'';
                                                            ?>
                                                        </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/job_request_form/'.$row['ID'].'/view') ?>" class="btn btn-outline-dark" data-trigger="hover" data-tooltip="tooltip" title="View Detail"><i class="far fa-eye"></i></a>

                                                                <?php if(($_SESSION['user']['id'] == $row['requester_id']) || ($_SESSION['user']['id'] == $row['createdBY'])){ ?>
                                                                    <button type="button" class="btn btn-outline-dark" data-trigger="hover" data-tooltip="tooltip" title="Clone" onclick="clone_job(<?php echo $row['ID']; ?>)"><i class="fas fa-clone"></i></button>
                                                                    <?php if($disabled == ''){ ?>
                                                                        <a href="<?php echo base_url('hr/serviceform/job_request_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" <?php echo $disabled; ?>><i class="far fa-edit"></i></button>
                                                                    <?php } ?>
                                                                <?php } ?>

                                                                <a href="<?php echo base_url('hr/serviceform_report/job_request_print/'.$row['ID']); ?>" class="btn btn-outline-dark" target="_blank" date-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['createdBY'])){ ?>
                                                                    <button id="deleteButton" type="button" class="btn btn-outline-dark" data-id="<?php echo $row['ID']; ?>" onclick="deleteJobRequest(this)" data-trigger="hover" data-tooltip="tooltip" title="Delete" <?php echo $disabled; ?>><i class="far fa-trash-alt"></i></button>
                                                                <?php } ?>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                <?php } ?>
                                            <?php } ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div> 
        </div>
    </div>
</div>

<script>
    $(document).ready(function()
    {
        $('#searchBtn').click(function(){
            getData();
        });

        <?php $this->session->unset_userdata('sv_job_request_filter_dept'); ?>
        <?php $this->session->unset_userdata('sv_job_request_filter_client_id'); ?>
        <?php $this->session->unset_userdata('sv_job_request_filter_year'); ?>
        <?php $this->session->unset_userdata('sv_job_request_filter_month'); ?>
        <?php $this->session->unset_userdata('sv_job_request_filter_status'); ?>
        <?php $this->session->unset_userdata('sv__job_request'); ?>
    });

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

        frmData.append('sv_job_request_filter_dept',$('#sv_job_request_filter_dept').val());
        frmData.append('sv_job_request_filter_client_id',$('#sv_job_request_filter_client_id').val());
        frmData.append('sv_job_request_filter_status',$('#sv_job_request_filter_status').val());
        frmData.append('sv_job_request_filter_year',$('#sv_job_request_filter_year').val());
        frmData.append('sv_job_request_filter_month',$('#sv_job_request_filter_month').val());

        $.ajax({
            url:"<?php echo base_url('/hr/api/serviceform/get_job_request_filter'); ?>",
            type:'post',
            dataType:'json',
            data:frmData,
            processData: false,
            contentType: false,
            success:function(data){

                iziToast.success({
                    position: 'bottomRight',
                    message: 'filtering data',
                });

                let job_request = data.table;

                if(job_request != null){
                    $.each(job_request,function(key,content)
                    {
                        var i = key + 1;
                        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;"';
                        }

                        if(disabled == '')
                        {
                            var btn_edit = '<a type="button" class="btn btn-outline-dark" href="<?php echo base_url();?>hr/serviceform/job_request_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_clone = '<button class="btn btn-outline-dark" data-trigger="hover" data-tooltip="tooltip" title="Clone"><i class="fas fa-clone" onclick="clone_job('+content.ID+')"></i></button>';

                        var btn_view = '<a href="<?php echo base_url();?>hr/serviceform/job_request_form/'+content.ID+'/view" class="btn btn-outline-dark" data-trigger="hover" data-tooltip="tooltip" title="View Detail"><i class="far fa-eye"></i></a>';

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

                        var btn_delete = '<button id="deleteButton" type="button" class="btn btn-outline-dark" data-id="'+content.ID+'" onclick="deleteJobRequest(this)" 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.createdBY))
                        {
                            var btn = btn_view+btn_clone+btn_edit+btn_print+btn_delete;
                        }else{
                            var btn = btn_view+btn_clone+btn_print;
                        }

                        var requestor_name  = '<b>Requested By : </b><br>'+content.requester_name+' ['+content.requester_email+']';
                        var department      = content.dept_name+' ['+content.branchName+']';
                        
                        if(moment(content.deadline) != null && content.deadline != '0000-00-00')
                        {
                            var deadline = '<br> <b>Deadline</b> : '+moment(content.deadline).format('DD-MM-YYYY');
                        }else{
                            var deadline = '';
                        } 

                        if(content.remarks != null && content.remarks != '')
                        {
                            var remarks = '<br> <b>Remarks</b> : '+content.remarks;
                        }else{
                            var remarks = '';
                        }

                        var details = '<b>Description</b> : '+content.description+'<br> <b>Year End</b> : '+content.yearEndDate+deadline+remarks;

                        // console.log(requestor_name);
                        table.row.add({
                            0   : '<div class="text-center">'+i+'</div>',
                            1   : requestor_name,
                            2   : department,
                            3   : content.client_name,
                            4   : details,
                            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();
                    });
                }
            },
            error:function(){
                iziToast.warning({
                    position: 'bottomRight',
                    message: '500 Internal Server Error.'
                });
            }
        });
    }

    function clone_job(job_request_id)
    {
        $.ajax({
            url:"<?php echo base_url('/hr/serviceform/job_request_clone'); ?>",
            type:'post',
            dataType:'json',
            data:{
                job_request_id : job_request_id,
            },
            success:function(data){

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

                location.reload();
            },
            error:function(){
                iziToast.warning({
                    position: 'bottomRight',
                    message: '500 Internal Server Error.'
                });
            }
        });
    }

    function deleteJobRequest(elem)
    {
        var job_request_id = $(elem).data('id');

        $.ajax({
            url:"<?php echo base_url('/hr/serviceform/job_request_delete'); ?>",
            type:'post',
            dataType:'json',
            data:{
                job_request_id : job_request_id,
            },
            success:function(data){

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

                location.reload();
            },
            error:function(){
                iziToast.warning({
                    position: 'bottomRight',
                    message: '500 Internal Server Error.'
                });
            }
        });
    }
</script>
