<div class="container-fluid" style="padding-bottom: 2rem;">
    <div class="card bg-light-transparent">  
        <div class="card-header bg-white">
            <div class="float-left">
                <h4>Credit Note Request List</h4>

                <a href="#" data-target="#modal_credit_note_entity" class="btn btn-outline-dark btn-sm" data-toggle="modal"><i class="fa fa-plus"></i> Add New Credit Note Request</a>

                <a href="<?php echo base_url('hr/Serviceform_report/credit_note_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">
                                <input type="hidden" name="user_id" id="user_id" value="<?php echo $_SESSION['user']['id']; ?>">
                                <div class="form-group row">
                                    <label for="sv_credit_note_filter_dept" class="col-lg-1">
                                        Department
                                    </label>                           
                                    <div class="col-lg-5">
                                        <select class="custom-select" name="sv_credit_note_filter_dept" id="sv_credit_note_filter_dept" <?php echo ($finance_staff || $_SESSION['user']['division_id'] == 10)?'':'disabled'; ?>>
                                         <option value="-1">[All]</option>
                                         <?php if($department) foreach($department as $row){ ?>
                                            <option value="<?php echo $row['id']; ?>" <?php echo ($finance_staff || $_SESSION['user']['division_id'] == 10)?'':($_SESSION['user']['department_id'] == $row['id'])?'selected':''; ?>><?php echo $row['name'].' ['.$row['branch_name'].']'; ?></option> 
                                        <?php } ?>
                                        </select>
                                    </div>

                                    <label for="sv_credit_note_filter_entity" class="col-lg-1">
                                        Entity
                                    </label>
                                    <div class="col-lg-5">
                                        <select class="custom-select" name="sv_credit_note_filter_entity" id="sv_credit_note_filter_entity">
                                         <option value="-1">[All]</option>
                                         <?php if($business_entity) foreach($business_entity 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_credit_note_filter_branch" class="col-lg-1">
                                        Branch
                                    </label>                           
                                    <div class="col-lg-5">
                                        <select class="custom-select" name="sv_credit_note_filter_branch" id="sv_credit_note_filter_branch">
                                         <option value="-1">[All]</option>
                                         <?php if($branch) foreach($branch as $row){ ?>
                                            <option value="<?php echo $row['id']; ?>"><?php echo $row['name']; ?></option> 
                                        <?php } ?>
                                        </select>
                                    </div>

                                    <label for="sv_credit_note_filter_status" class="col-lg-1">
                                        Status
                                    </label>                           
                                    <div class="col-lg-5">
                                        <select class="custom-select" id="sv_credit_note_filter_status" name="sv_credit_note_filter_status">
                                            <option value="-1">[All]</option>
                                            <option value="Pending">Pending</option>
                                            <option value="Approved">Approved</option>
                                            <option value="Rejected">Rejected</option>
                                            <option value="Completed">Completed</option>
                                            <option value="Duplicate">Duplicate</option>
                                        </select>
                                    </div>
                                </div>

                                <div class="form-group row">
                                    <label for="sv_credit_note_filter_requester" class="col-lg-1">
                                        Requester
                                    </label>                           
                                    <div class="col-lg-5">
                                        <select class="custom-select" id="sv_credit_note_filter_requester" name="sv_credit_note_filter_requester">
                                            <option value="-1">[All]</option>
                                            <?php if($requester) foreach($requester as $row){ ?>
                                                <option value="<?php echo $row['id'] ?>"><?php echo $row['name']; ?></option>
                                            <?php } ?>
                                        </select>
                                    </div>

                                    <label for="sv_credit_note_filter_approver" class="col-lg-1">
                                        Approver
                                    </label>                           
                                    <div class="col-lg-5">
                                        <select class="custom-select" id="sv_credit_note_filter_approver" name="sv_credit_note_filter_approver">
                                            <option value="-1">[All]</option>
                                            <?php if($approver) foreach($approver 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_credit_note_filter_preparer" class="col-lg-1">
                                        Prepare
                                    </label>                           
                                    <div class="col-lg-5">
                                        <select class="custom-select" id="sv_credit_note_filter_preparer" name="sv_credit_note_filter_preparer">
                                            <option value="-1">[All]</option>
                                            <?php if($preparer) foreach($preparer as $row){ ?>
                                                <option value="<?php echo $row['id'] ?>"><?php echo $row['name']; ?></option>
                                            <?php } ?>
                                        </select>
                                    </div>

                                    <label for="sv_credit_note_filter_year" class="col-lg-1">
                                        Year
                                    </label>                           
                                    <div class="col-lg-5">
                                      <input type="text" name="sv_credit_note_filter_year" id="sv_credit_note_filter_year" class="form-control datepicker-yyyy">
                                    </div>
                                </div>
                                <div class="form-group row">
                                    <label for="sv_credit_note_filter_month" class="col-lg-1">
                                      Month
                                    </label>                           
                                    <div class="col-lg-5">
                                        <input type="text" name="sv_credit_note_filter_month" id="sv_credit_note_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_credit_note" class="table table-bordered p-0 m-0" width="100%">
                                    <thead> 
                                        <th class="text-center" width="1%">#</th>
                                        <th class="text-center" width="12%">Credit Note No</th>
                                        <th class="text-center" width="12%">MGS Job ID</th>
                                        <th class="text-center" width="12%">Entity</th>
                                        <th class="text-center" width="12%">Branch</th>
                                        <th class="text-center" width="12%">Department </th>
                                        <th class="text-center" width="12%">Requester</th>
                                        <th class="text-center" width="12%">Status</th>
                                        <th class="text-center" width="10%">Amount (RM)</th>
                                        <th class="text-center" width="5%">Action</th>
                                    </thead>
                                    <tbody>
                                        <?php if(!empty($credit_note_list)) { ?> 
                                            <?php foreach($credit_note_list as $key => $row) {
                                                ?>
                                                <tr>
                                                    <td class="text-center"><?php echo $key+1; ?></td>
                                                    <td class="text-center"><?php echo $row['cn_form_no']; ?></td>
                                                    <td>
                                                        <?php echo ($row['job_id'])?'<b>Job ID : </b>'.str_pad($row['job_id'],5,0,STR_PAD_LEFT).'<br><br>':''; ?>
                                                        
                                                        <?php echo '<b>Client : </b>'.$row['customerName']; ?>
                                                    </td>
                                                    <td><?php echo $row['entity_name']; ?></td>
                                                    <td><?php echo ($row['inv_branch'])?$row['inv_branch']:'N/A'; ?></td>
                                                    <td><?php echo $row['dept_name'].' / '.$row['branchName']; ?></td>
                                                    <td><?php echo $row['requester_name'];//.' ['.$row['requester_email'].']'; ?></td>
                                                    <td>
                                                        <?php if($row['approval_status'] == 0){ ?>
                                                            <b>Approval Status : </b><br>Pending <i class="fa fa-exclamation-circle" style="color: #FFC107;"></i>
                                                            <?php $disabled = ''; ?>
                                                        <?php } else { $disabled = 'disabled style="cursor: not-allowed;"'; ?>
                                                            <b>Approval Status : </b><br>
                                                            <?php if($row['approval_status'] == 1)
                                                            {
                                                                echo 
                                                                'Approved <i class="fa fa-check-circle" style="color: green;"></i>
                                                                <br>
                                                                <b>Approved By : </b>'.$row['approved_by_name'];
                                                            }else{
                                                                echo 
                                                                'Rejected <i class="fa fa-times-circle" style="color: red;"></i>
                                                                <br>
                                                                <b>Rejected By : </b>'.$row['approved_by_name'];
                                                            }
                                                            ?>
                                                            <br><br>
                                                            <b>Finance Status : </b><br>
                                                            <?php if($row['prepared_status'] == 0)
                                                            {
                                                                echo 'Pending <i class="fa fa-exclamation-circle" style="color: #FFC107;"></i>';
                                                            }
                                                            elseif($row['prepared_status'] == 1)
                                                            {
                                                                echo 
                                                                'Completed <i class="fa fa-check-circle" style="color: green;"></i>
                                                                <br>
                                                                <b>Prepared By : </b>'.$row['prepared_by_name']; 
                                                            }else{
                                                                echo 
                                                                'Duplicate <i class="fa fa-exclamation-triangle" style="color: #FFC107;"></i><br>
                                                                <b>Prepared By : </b>'.$row['prepared_by_name'];
                                                            }
                                                            ?>
                                                        <?php } ?>
                                                    </td>
                                                    <td class="text-center"><?php echo number_format($row['total'],2); ?></td>
                                                    <td class="text-center">
                                                        <div class="btn-group btn-group-sm" role="group">
                                                            <a type="button" class="btn btn-outline-dark" data-trigger="hover" data-tooltip="tooltip" 
                                                            title="View Detail" href="<?php echo base_url('hr/serviceform/credit_note_form/'.$row['business_entity_id'].'/'.$row['ID'].'/view'); ?>" target="_blank"><i class="far fa-eye"></i></a>

                                                            <?php if(($_SESSION['user']['id'] == $row['requester_id']) || ($_SESSION['user']['id'] == $row['createdBY'])){ ?>
                                                                <?php if($disabled == ''){ ?>
                                                                    <a type="button" class="btn btn-outline-dark" data-trigger="hover" data-tooltip="tooltip" title="Edit" href="<?php echo base_url('hr/serviceform/credit_note_form/'.$row['business_entity_id'].'/'.$row['ID']); ?>" target="_blank"><i class="far fa-edit"></i></a>
                                                                <?php }else{ ?>
                                                                    <button type="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 type="button" class="btn btn-outline-dark" href="<?php echo base_url('hr/serviceform_report/credit_note_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['createdBY'])){ ?>
                                                            <button id="deleteButtonCreditNote" type="button" class="btn btn-outline-dark" onclick="deleteCreditNote(<?php echo $row['ID']; ?>);" data-trigger="hover" data-tooltip="tooltip" title="Delete" <?php echo ($disabled == '')?'':$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 class="modal fade" id="modal_credit_note_entity" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLongTitle"></h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>

            <div class="modal-body">
                <!-- <form class="form" id="crmcompany" method="post" action="<?php //echo base_url('hr/serviceform/credit_note_form') ?>"> -->
                    <div class="row p-3">
                        <div class="col-12">
                            <label>Business Entity</label>
                            <select class="form-control" id="entity_id" name="entity_id" required>
                                <option value="-1"><?php echo "-- Select Company --"; ?></option>
                                <?php if(!empty($business_entity)): foreach($business_entity as $row): //debug($row); ?>
                                    <option value="<?php echo $row['id']; ?>"><?php echo $row['name']; ?></option>
                                <?php endforeach; endif;?>
                            </select>
                        </div>
                    </div>

                    <div class="float-right">
                        <button type="button" class="btn btn-light" data-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary" onclick="to_credit_note_form()">Go</button>
                    </div> 
                <!-- </form> -->
            </div>
        </div>
    </div>
</div>

<script>
    $(document).ready(function()
    {
        <?php $this->session->unset_userdata('sv_credit_note_filter_dept'); ?>
        <?php $this->session->unset_userdata('sv_credit_note_filter_entity'); ?>
        <?php $this->session->unset_userdata('sv_credit_note_filter_branch'); ?>
        <?php $this->session->unset_userdata('sv_credit_note_filter_status'); ?>
        <?php $this->session->unset_userdata('sv_credit_note_filter_requester'); ?>
        <?php $this->session->unset_userdata('sv_credit_note_filter_approver'); ?>
        <?php $this->session->unset_userdata('sv_credit_note_filter_preparer'); ?>
        <?php $this->session->unset_userdata('sv_credit_note_filter_year'); ?>
        <?php $this->session->unset_userdata('sv_credit_note_filter_month'); ?>
        <?php $this->session->unset_userdata('sv__credit_note'); ?>
        
        $('#searchBtn').click(function(){
            getData();
        });
    });

    function to_credit_note_form()
    {
        var entity_id = $('#entity_id').val();

        if(entity_id > 0)
        {
            window.location.href = '<?php echo base_url('hr/serviceform/credit_note_form/'); ?>'+entity_id;
        }
    }

    function deleteCreditNote(ID) 
    {
        validateForm("#deleteButtonCreditNote", "Delete this from list?", function() {
            $.ajax({
                url:'<?php echo base_url('hr/serviceform/deleteCreditNoteList') ?>',
                data: {
                    creditNoteID : 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_credit_note').DataTable();
        table.clear().draw();
        var frmData = new FormData();

        frmData.append('sv_credit_note_filter_dept',$('#sv_credit_note_filter_dept').val());
        frmData.append('sv_credit_note_filter_entity',$('#sv_credit_note_filter_entity').val());
        frmData.append('sv_credit_note_filter_branch',$('#sv_credit_note_filter_branch').val());
        frmData.append('sv_credit_note_filter_status',$('#sv_credit_note_filter_status').val());
        frmData.append('sv_credit_note_filter_requester',$('#sv_credit_note_filter_requester').val());
        frmData.append('sv_credit_note_filter_approver',$('#sv_credit_note_filter_approver').val());
        frmData.append('sv_credit_note_filter_preparer',$('#sv_credit_note_filter_preparer').val());
        frmData.append('sv_credit_note_filter_year',$('#sv_credit_note_filter_year').val());
        frmData.append('sv_credit_note_filter_month',$('#sv_credit_note_filter_month').val());
        // frmData.append('user_id',$('#user_id').val());

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

                let credit_note = data.table;

                if(credit_note != null){
                    $.each(credit_note,function(key,content)
                    {
                        var i = key + 1;
                        
                        if(content.approval_status == 0)
                        {
                            var approval_status = '<b>Approval Status : </b><br>'; 
                            var status = 'Pending <i class="fa fa-exclamation-circle" style="color: #FFC107;"></i>';
                            var disabled = '';

                            var cn_status = approval_status+status;
                        } else 
                        {
                            var disabled = 'disabled style="cursor: not-allowed;"';

                            var approval_status = '<b>Approval Status : </b><br>';
                            if(content.approval_status == 1)
                            {
                                var status = 'Approved <i class="fa fa-check-circle" style="color: green;"></i><br><b>Approved By : </b>'+content.approved_by_name;
                            }else{
                                var status = 'Rejected <i class="fa fa-times-circle" style="color: red;"></i><br><b>Rejected By : </b>'+content.approved_by_name; 
                            }
                            
                            var finance_status = '<b>Finance Status : </b><br>';
                            if(content.prepared_status == 0)
                            {
                                var f_status = 'Pending <i class="fa fa-exclamation-circle" style="color: #FFC107;"></i>';
                            }
                            else if(content.prepared_status == 1)
                            {
                                var f_status = 'Completed <i class="fa fa-check-circle" style="color: green;"></i><br><b>Prepared By : </b>'+content.prepared_by_name; 
                            }else{
                                var f_status = 'Duplicate <i class="fa fa-exclamation-triangle" style="color: #FFC107;"></i><br><b>Prepared By : </b>'+content.prepared_by_name;
                            }

                            var cn_status = approval_status+status+'<br><br>'+finance_status+f_status;
                        }


                        var btn_view = '<a type="button" class="btn btn-outline-dark" data-trigger="hover" data-tooltip="tooltip" title="View Detail" href="<?php echo base_url();?>hr/serviceform/credit_note_form/'+content.business_entity_id+'/'+content.ID+'/view" target="_blank"><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/credit_note_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/credit_note_form/'+content.business_entity_id+'/'+content.ID+'" target="_blank" data-trigger="hover" data-tooltip="tooltip" title="Edit" '+disabled+'><i class="far fa-edit"></i></a>';
                        }else{
                            var btn_edit = '<button type="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="delete_equipment('+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.createdBY))
                        {
                            var btn = btn_view+btn_edit+btn_print+btn_delete;
                        }else{
                            var btn = btn_view+btn_print;
                        }

                        if(content.job_id != '' && content.job_id != null && content.job_id > 0)
                        {
                            var job_id = '<b>Job ID : </b>'+(content.job_id).padStart(5, '0')+'<br><br><b>Client : </b>'+content.customerName;
                        }else{
                            var job_id = '<b>Client : </b>'+content.customerName;
                        }

                        table.row.add({
                            0   : '<div class="text-center">'+i+'</div>',
                            1   : '<div class="text-center">'+content.cn_form_no+'</div>',
                            2   : job_id,
                            3   : content.entity_name,
                            4   : content.inv_branch,
                            5   : content.dept_name+' / '+content.branchName,
                            6   : content.requester_name,
                            7   : cn_status,
                            8   : '<div class="text-center">'+content.total+'</div>',
                            9	: '<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>