<?php
$this->load->view("common/header");
?>

<!-- end: HEAD -->

<?php
$tmp_id = 0;
?>

<!-- start: CSS REQUIRED FOR THIS PAGE ONLY -->
<style type="text/css">
label {
	font-weight: 700;
}
.form-horizontal .form-group {
	margin-left: 0;
	margin-right: 0;
}
td {
	vertical-align: text-top;
}
</style>

<!-- end: CSS REQUIRED FOR THIS PAGE ONLY -->

<!-- end: HEAD -->

<!-- start: BODY -->

<body>

<!-- start: HEADER -->

<div class="navbar navbar-inverse navbar-fixed-top"> 
  
  <!-- start: TOP NAVIGATION CONTAINER -->
  
  <div class="container">
    <div class="navbar-header"> 
      
      <!-- start: RESPONSIVE MENU TOGGLER -->
      
      <button data-target=".navbar-collapse" data-toggle="collapse" class="navbar-toggle" type="button"> <span class="clip-list-2"></span> </button>
      
      <!-- end: RESPONSIVE MENU TOGGLER --> 
      
      <!-- start: LOGO -->
      
      <?php
$this->load->view("common/logo");
?>
      
      <!-- end: LOGO --> 
      
    </div>
    <div class="navbar-tools"> 
      
      <!-- start: TOP NAVIGATION MENU -->
      
      <?php
$this->load->view("common/notifications.php");
?>
      
      <!-- end: TOP NAVIGATION MENU --> 
      
    </div>
  </div>
  
  <!-- end: TOP NAVIGATION CONTAINER --> 
  
</div>

<!-- end: HEADER --> 

<!-- start: MAIN CONTAINER -->

<div class="main-container">
  <div class="navbar-content"> 
    
    <!-- start: SIDEBAR -->
    
    <?php
$this->load->view("common/navigation");
?>
    
    <!-- end: SIDEBAR --> 
    
  </div>
  
  <!-- start: PAGE -->
  
  <div class="main-content"> 
    
    <!-- end: SPANEL CONFIGURATION MODAL FORM -->
    
    <div class="container"> 
      
      <!-- start: PAGE HEADER -->
      
      <div class="row">
        <div class="col-sm-12"> 
          
          <!-- start: PAGE TITLE & BREADCRUMB -->
          
          <ol class="breadcrumb">
            <li> <a href="#"> Dashboard </a> </li>
            <li> <a href="<?php
echo base_url('sales2?s=' . rand());
?>"> Invoice </a> </li>
            <li class="active"> Customer Payment </li>
            <li class="search-box">
              <form class="sidebar-search">
                <div class="form-group">
                  <input type="text" placeholder="Start Searching...">
                  <button class="submit"> <i class="clip-search-3"></i> </button>
                </div>
              </form>
            </li>
          </ol>
          <div class="page-header">
            <h1> Cheque return</h1>
          </div>
          <p>Please fill in the information below. The field labels marked with * are required input fields.</p>
        </div>
      </div>
      
      <!-- end: PAGE HEADER --> 
      
      <!-- start: PAGE CONTENT 

                    <!-- start grid -->
      
      <div class="row">
        <div class="col-md-12"> 
          
          <!-- start: DYNAMIC TABLE PANEL -->
          
          <div class="panel panel-default">
            <div class="panel-heading"> <i class="fa fa-plus"></i> Cheque return settlment </div>
            <div class="panel-body">
              <div class="alert alert-danger" style="display:none;">
                <button class="close" data-dismiss="alert"> × </button>
                <i class="fa fa-times-circle"></i> <strong></strong> <span class="errortxt"></span> </div>
              <div class="alert alert-success" style="display:none;">
                <button class="close" data-dismiss="alert"> × </button>
                <i class="fa fa-check-circle"></i> <strong></strong><span class="succetxt"></span> </div>
              <form role="form" class="form-horizontal" id="create_collection_form" action="#" method="post">
                <div class="col-md-12"></div>
                <!--col-md-12--> 
                <!-- start payments-->
                
                <div class="col-md-12">
                  <div class="well well-sm">
                    <div class="row">               
                     
                     
                     
                      <div class="col-md-2">
                        <div class="form-group">
                          <label>Date Return *</label>
                          <input id="sale_pymnt_date_time" name="sale_pymnt_date_time" type='text' class="form-control date-time" value="<?php
echo date("Y-m-d H:i:s");
?>" data-bv-field="date" />
                        </div>
                      </div>                    
                     

                      <div class="col-sm-3">
                        <div class="payment">
                          <div class="form-group">
                            <label for="amount_1">Responsible *</label>
                            <select class="form-control paid_by" id="collector_id" name="collector_id" data-bv-field="paid_by" tabindex="-1" title="Collect by *" >
                              <option value=""> --Select Collector--</option> 
                              <?php  foreach ($user_list as $row){?>
					<option value="<?php echo $row['user_id']; ?>"><?php echo  $row['user_first_name'] ?> </option><?php }?>                            
                            </select>
                          </div>
                        </div>
                      </div>

                      <div class="col-sm-3">
                        <div class="payment">
                          <div class="form-group">
                            <label for="amount_1">Return Reason *</label>
                            <select class="form-control paid_by" id="return_reason" name="return_reason" data-bv-field="paid_by" tabindex="-1" title="REASON by *" >
                              <option value=""> --Select --</option> 
                              <?php  foreach ($ch_return_reason_list as $row){?>
					<option value="<?php echo $row['rt_reason_id']; ?>">(<?php echo  $row['reason_code'] ?> ) <?php echo  $row['return_reason'] ?> </option><?php }?>                            
                            </select>
                          </div>
                        </div>
                      </div>

                      <div class="col-sm-3">
                        <div class="payment">
                          <div class="form-group">
                            <label for="amount_1">REF No </label>
                            <input type="text" class="pa form-control kb-pad amount" id="ref_no" name="ref_no" value="" />
                          </div>
                        </div>
                      </div>

                      

                      <!----------------------------->
                     
                      
                   
                      
                      <div class="clearfix"></div>
                      
                      <!-- end payment optiones -->
                      <div id="note_grid" class="form-group">
                        <div class="col-sm-12">
                          <label class="control-label"> Note </label>
                          <textarea id="sale_note"  class="ckeditor form-control" cols="10" rows="2" name="sale_note"></textarea>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                
                <!-- end payments-->
                
                
                <!--col-md-8--> 
                
                <!-- item add box-->
                
                <div id="sticker" class="col-md-12">
                  <div class="well well-sm">
                    <div class="form-group"> 
                      
                      <!-- auto complete start -->
                      
                      <div class="input-group wide-tip" style="display:none">
                        <div style="padding-left: 10px; padding-right: 10px;" class="input-group-addon"> <i class="fa fa-2x fa-barcode addIcon"></i> </div>
                        <input type="text" placeholder="Please add products to order list" id="add_item" class="form-control input-lg" value="" name="add_item" style="border-radius: 6px;font-size: 18px;height: 46px;line-height: 1.33;padding: 10px 16px;">
                        
                        <!--<div style="padding-left: 10px; padding-right: 10px;" class="input-group-addon">

                                                            <i id="addIcon" class="fa fa-2x fa-plus-circle addIcon"></i>

                                                        </div>--> 
                        
                      </div>
                      
                      <!-- end auto complete end --> 
                      
                    </div>
                    <div class="clearfix"></div>
                    <div class="control-group table-group">
                      <p id="loader" align="center" style="display:none">Loading...<i class="fa fa-spin fa-spinner"></i></p>
                      <div class="controls table-controls">
                       
                      </div>
                    </div>
                  </div>
                </div>
                <div class="col-md-12">
                  <div class="modal-footer" style="margin-bottom:10px;">
                    <input type="submit" class="btn btn-primary" value="Add Cheque Return" name="add_payments" id="add_payments" onClick="insertPaymentsData();">
                    <button id="reset" class="btn btn-danger" type="button">Reset</button>
                  </div>
                </div>
               
                <input name="base_url" type="hidden" id="base_url" value="<?php
echo base_url();
?>">
                <input name="smp_id" type="hidden" id="smp_id" value="<?php echo $smp_id; ?>">
              </form>
              <input name="" type="hidden" id="tmpVal">
              
              <!-- end: DYNAMIC TABLE PANEL --> 
              
              <!-- footer amount details -->
              
            
              
              <!-- end footer amount details --> 
              
            </div>
          </div>
          
          <!-- end grid --> 
          
        </div>
        
        <!-- end: PAGE --> 
        
      </div>
    </div>
  </div>
</div>
<!-- end: MAIN CONTAINER --> 

<!-- start: FOOTER -->

<div class="footer clearfix">
  <div class="footer-items"> <span class="go-top"><i class="clip-chevron-up"></i></span> </div>
</div>

<!-- end: FOOTER --> 

<!-- start: RIGHT SIDEBAR --> 

<!-- end: RIGHT SIDEBAR -->

<div id="event-management" class="modal fade" tabindex="-1" data-width="760" style="display: none;">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> &times; </button>
        <h4 class="modal-title">Event Management</h4>
      </div>
      <div class="modal-body"></div>
      <div class="modal-footer">
        <button type="button" data-dismiss="modal" class="btn btn-light-grey"> Close </button>
        <button type="button" class="btn btn-danger remove-event no-display"> <i class='fa fa-trash-o'></i> Delete Event </button>
        <button type='submit' class='btn btn-success save-event'> <i class='fa fa-check'></i> Save </button>
      </div>
    </div>
  </div>
</div>
<input name="tmpVal" type="hidden" id="tmpVal" value="0">
<input name="" id="type_sale" type="hidden" value="22">

<!-- start ajax model -->

<div id="ajax-modal" class="modal fade" data-backdrop="static" data-keyboard="false" tabindex="-1" style="display: none;"></div>

<!-- end ajax model --> 

<a id="modal_ajax_serial_no" data-toggle="modal" href="#"></a> <a id="modal_ajax_serial_no_view" data-toggle="modal" href="#"></a>
<input name="" type="hidden" id="curr_row_no" value="0">

<!-- start: MAIN JAVASCRIPTS -->

<?php
$this->load->view("common/footer");
?>
<script type="text/javascript" src="<?php
echo asset_url();
?>js/accounting.js"></script> 
<script type="text/javascript" src="<?php
echo asset_url();
?>js/accounting.min.js"></script> 

<!-- end: MAIN JAVASCRIPTS --> 

<!-- start: JAVASCRIPTS REQUIRED FOR THIS PAGE ONLY VALIDATION--> 

<!--<script src="<?php
echo asset_url();
?>js/collect_cash.js"></script>--> 

<!-- end: JAVASCRIPTS REQUIRED FOR THIS PAGE ONLY  VALIDATION--> 

<script>$("#checkAll").click(function() {
    $('input:checkbox').not(this).prop('checked', this.checked);
});
$( ".search-select" ).select2();
$('.checkbox').bind('change', function(e) {
    if (!e.target.checked) {
        var id_num;
        var str = e.target.name;
        if (str) {
            str = str.replace('row_c[', '');
            str = str.replace('][collection][]', '');
            id_num = str;
        }
        $('#amount_' + id_num).val('0');
        calculateTotalAmount();
    } else {
        var pay_amount = $('#sale_pymnt_amount').val();
        var arr = $('.added_amount'),
            sum = 0;
        $.each(arr, function() {
            sum += parseFloat($('#' + this.id).val()) || 0;
        });
        var id_num;
        var str = e.target.name;
        if (str) {
            str = str.replace('row_c[', '');
            str = str.replace('][collection][]', '');
            id_num = str;
        }
        var has_to_pay = $('#balance_amount_' + id_num).val();
        var balance_to_continue = pay_amount - sum;
        if (balance_to_continue >= has_to_pay) {
            $('#amount_' + id_num).val(has_to_pay);
        } else if (balance_to_continue > 0) {
            $('#amount_' + id_num).val(balance_to_continue);
        } else {
            $('#' + e.target.id).prop('checked', false);
        }
        calculateTotalAmount();
    }
    if (false == $(this).prop("checked")) {
        $("#select_all").prop('checked', false);
    }
    if ($('.checkbox:checked').length == $('.checkbox').length) {
        $("#select_all").prop('checked', true);
    }
});
$('input:text').click(function() {
    this.select();
});
$("#select_all").change(function(e) {
    if (e.target.checked) {
        var pay_amount = $('#sale_pymnt_amount').val();
        $(".checkbox").prop('checked', function(index) {
            var arr = $('.added_amount'),
                sum = 0;
            $.each(arr, function() {
                sum += parseFloat(this.value) || 0;
            });
            var id_num;
            var str = $(".checkbox")[index].name;
            if (str) {
                str = str.replace('row_c[', '');
                str = str.replace('][collection][]', '');
                id_num = str;
            }
            var has_to_pay = $('#balance_amount_' + id_num).val();
            var balance_to_continue = pay_amount - sum;
            if (balance_to_continue >= has_to_pay) {
                $('#amount_' + id_num).val(has_to_pay);
                $('#' + $(".checkbox")[index].id).attr('checked', '');
            } else if (balance_to_continue > 0) {
                $('#amount_' + id_num).val(balance_to_continue);
                $('#' + $(".checkbox")[index].id).attr('checked', '');
            }
            calculateTotalAmount();
        });
    } else {
        var pay_amount = $('#sale_pymnt_amount').val();
        $(".checkbox").prop('checked', function(index) {
            var id_num;
            var str = $(".checkbox")[index].name;
            if (str) {
                str = str.replace('row_c[', '');
                str = str.replace('][collection][]', '');
                id_num = str;
            }
            $('#amount_' + id_num).val(0);
            $('#' + $(".checkbox")[index].id).removeAttr('checked');
            calculateTotalAmount();
        });
    }
});

function calculateTotalAmount() {
    var tot_amount = 0;
    var tot_visiting_charge = 0;
    $('input[name^="card_row"]').each(function() {
        var id = $(this).val();
        var amount_fld = "#amount_" + id;
        tot_amount = tot_amount + parseFloat($(amount_fld).val());
        var visiting_charge_fld = "#visiting_charge_" + id;
        tot_visiting_charge = tot_visiting_charge + parseFloat($(visiting_charge_fld).val());
    });
    $("#tot_amount_div").text(convertToAmount(tot_amount));
    $("#total_amount-txt").text(convertToAmount(tot_amount));
    $("#avl_amount-txt").text(convertToAmount($('#sale_pymnt_amount').val() - tot_amount));

    $("#smp_amount").val((tot_amount));
    $("#tot_vist_charge_div").text(convertToAmount(tot_visiting_charge));
    $("#tot_amount_all").text(convertToAmount(tot_amount + tot_visiting_charge));
}

function convertToAmount(val) {
    var disval = val;
    return accounting.formatMoney(disval, "", 2, ",", ".");
}

function convertToAmount2Des(val) {
    var disval = val;
    return accounting.formatMoney(disval, "", 2, "", ".");
}

function changeAmount(row) {
    var collection_fld = "#collection_c_" + row;
    var amount_fld = "#amount_" + row;
    var amount_val = parseFloat($(amount_fld).val());
    if (amount_val) {
        var pay_amount = $('#sale_pymnt_amount').val();
        var arr = $('.added_amount'),
            sum = 0;
        $.each(arr, function() {
            sum += parseFloat(this.value) || 0;
        });
        sum -= amount_val;
        var has_to_pay = amount_val;
        var balance_to_continue = pay_amount - sum;
        if (balance_to_continue >= has_to_pay) {
            $(collection_fld).prop("checked", true);
        } else {
            $(collection_fld).prop("checked", false);
            $(amount_fld).val('0');
        }
    } else {
        $(collection_fld).prop("checked", false);
    }
    calculateTotalAmount();
}
$("form").submit(function(e) {
    return false;
});

function insertPaymentsData() {
    $("#add_payments").val('Please wait...');
    $("#add_payments").prop("disabled", true);
    calculateTotalAmount();
    setTimeout(function() {
        var fields = $("#create_collection_form").serialize();
        var rowCount = $('#rowCount').val();
        var customer_id = $('#customer_id').val();
        var smp_amount = $('#smp_amount').val();
       
            $.post("<?php
echo base_url();
?>payment_process/save_cheque_return", fields).done(function(data) {
                var obj = jQuery.parseJSON(data);
                if (obj.error == 1) {
                    $('.alert-success').hide();
                    $('.alert-danger').show();
                    $(".errortxt").text(obj.disMsg);
                    $("#add_payments").prop("disabled", false);
                    $("#add_payments").val('Add Payments');
                    window.scrollTo(500, 0);
                }
                if (obj.error == 0) {
                    window.scrollTo(500, 0);
                    $("#cash_collect > tbody").empty();
                    displayNotice('page', 'Payment successfully added!');
                    setTimeout(function() {
                        
                        sendUrl = 'payment_process';
    location.href = "<?php
echo base_url();
?>" + sendUrl;
                    }, 1000);
                }
            });
            return false;
      
    }, 1000);
}

function change_customer(val) {
    $('body').modalmanager('loading');
    sendUrl = 'payment_process/manage/' + val;
    location.href = "<?php
echo base_url();
?>" + sendUrl;
}
<!--start:add items-->
<!--end:add items-->

function deleteCollectCashItem(row_id) {
    var val = '#row_c_' + row_id;
    $(val).remove();
}
$(document).ajaxStart(function() {
    $('#loader').show('fast');
});
$(document).ajaxStop(function() {
    $('#loader').hide('fast');
});

function setTmpVal(val) {
    $('#tmpVal').val(val);
}

function changePayingby(val) {
    $('.paying_by_details').hide();
    if (val == 'Credit Card') {
        $('#credit_card').show();
    }
    if (val == 'Cheque') {
        $('#cheque_dtls').show();
    }
}


function load_customer_balance() {
    var customer_id = $("#customer_id").val();
    if (customer_id != 1) {

        /* var tot_amount = gross_total; */

        var warehouse_id = $('#warehouse_id').val();
        /*get customer crdit limit*/
        var base_url = $("#base_url").val();
                
                /*SART*/
                
                var srh_customer_id = $('#customer_id').val();
                var warehouse_id = $('#warehouse_id').val();
                var srh_from_date = '';
                var srh_to_date = $('#sale_pymnt_date_time').val();

/*

                var today = new Date(srh_to_date);
    
                var dd = today.getDate();
                var mm = today.getMonth() + 1; 
                var yyyy = today.getFullYear();

                if (dd < 10) {
                    dd = '0' + dd
                }

                if (mm < 10) {
                    mm = '0' + mm
                }

                srh_to_date = mm + '/' + dd + '/' + yyyy;*/
            console.log(srh_to_date);
                var cus_id = customer_id;
                var total_sales = 0;
                var total_return = 0;
                var return_cash = 0;
                var total_paid = 0;
                var unrealized_chq = 0;
                /*-------------
                    get sales
                ---------------*/
                $.get(base_url+"sales/get_all_sum_sales_for_summery_report?srh_customer_id=" + customer_id + "&warehouse_id=" + warehouse_id + "&srh_from_date=" + srh_from_date + "&srh_to_date=" + srh_to_date)
                    .done(function(data) {
                        var sales_obj = jQuery.parseJSON(data);
                        
                        total_sales = sales_obj[0].sale_total;
                        if (total_sales)
                            /*-------------
                                get returns
                            ---------------*/
                            
                            $.get(base_url+"sales/get_sum_sales_return?srh_customer_id=" + cus_id + "&warehouse_id=" + warehouse_id + "&srh_from_date=" + srh_from_date + "&srh_to_date=" + srh_to_date)
                            .done(function(data) {
                                var sales_return_obj = jQuery.parseJSON(data);
                                
                                /*-------------
                                get return cash
                                ---------------*/
                                
                                $.get(base_url+"sales/getSumPaymentsForBalanceRep?srh_customer_id=" + cus_id + "&warehouse_id=" + warehouse_id + "&srh_from_date=" + srh_from_date + "&srh_to_date=" + srh_to_date + "&srh_type=sale&srh_payment_term=Return_Cash&return_name=Return_Cash")
                                    .done(function(data) {
                                        var return_cash_obj = jQuery.parseJSON(data);
                                        
                                        /*-------------
                                                get Total Paid
                                                ---------------*/
                                        $.get(base_url+"sales/getSumPaymentsForBalanceRep?srh_customer_id=" + cus_id + "&warehouse_id=" + warehouse_id + "&srh_from_date=" + srh_from_date + "&srh_to_date=" + srh_to_date + "&srh_type=sale&srh_payment_term=&return_name=tot_sp")
                                            .done(function(data) {
                                                var total_paid_obj = jQuery.parseJSON(data);
                                                

                                                total_sales = sales_obj[0].sale_total; 
                                                total_return = sales_return_obj.sale_return_total; 
                                                return_cash = return_cash_obj[0].Return_Cash; 
                                                total_paid = total_paid_obj[0].tot_sp;
                                                unrealized_chq = $('#unrealized_check_amount').val(); 

                                                $('#cheque_txt').text(accounting.formatMoney(unrealized_chq, "", 2, ",", "."));

                                                var fin = total_sales - total_return - (total_paid - return_cash);

                                                if (fin) {
                                                    $('#customer_balance').text(convertToAmount(fin));
                                                }else
												$('#customer_balance').text(convertToAmount(0));
                                               
                                                /************/
                                                /*-------------
                                                    END UnRealized Chq
                                                ---------------*/
                                            });
                                        /*-------------
                                            END Total Paid
                                        ---------------*/
                                    });
                                /*-------------
                                    END return cash
                                ---------------*/
                            });
                        /*-------------
                            END get returns
                        ---------------*/
                    });
                /*-------------
                    END get sales
                ---------------*/
                /* end each*/
    }
}
                </script>
</body>

<!-- end: BODY -->

</html>