<?php
$this->load->view ( $left );
$this->load->view ( $header );
?>
<div class="row wrapper border-bottom white-bg page-heading">
    <div class="col-sm-12">
        <h2>Cusomer Payment/Balance Report</h2>
    </div>
    <!-- <div class="col-sm-8">
        <div class="title-action">
            <a href="<?php //echo site_url("bank/newbank");?>" class="btn btn-primary">
                <i class="fa fa-plus-square-o"></i>
                <span class="m-l-xs">Add Bank</span>
            </a>
        </div>
    </div> -->
</div>
<div class="wrapper wrapper-content">
<?php $state_array = array('-','Jammu & Kashmir','Himachal Pradesh','Punjab','Chandigarh','Uttarakhand','Haryana','Delhi','Rajasthan','Uttar Pradesh','Bihar','Sikkim','Arunachal Pradesh','Nagaland','Manipur','Mizoram','Tripura','Meghalaya','Assam','West Bengal','Jharkhand','Odisha','Chhattisgarh','Madhya Pradesh','Gujarat','Daman & Diu','Dadra & Nagar Haveli','Maharashtra','Karnataka','Goa','Lakshdweep','Kerala','Tamil Nadu','Pondicherry','Andaman & Nicobar Islands','Telengana','Andhra Pradesh','Other Territory');?>
    <div class="row text-center animated fadeInRightBig">
        <div class="row">
            <div class="col-lg-12">
                <div class="ibox float-e-margins">
                    <div class="ibox-content" style="padding: 15px 20px 15px 20px;">
                        <div class="row">
                            <table class="table myTable">
                                <thead>
                                    <tr>
                                        <th>Customer</th>
                                        <th>Invoice Due</th>
                                        <th>Credit Note</th>
                                        <th>Unused Payment</th>
                                        <th>Balance</th>
                                    </tr>
                                </thead>
                                <tbody id="data_report_invoice">
                                    <?php 
                                    if (count($customer_balance) > 0) { 
                                        $total_due_invoice = 0;
                                        $total_credit_note = 0;
                                        $total_unused_payment = 0;
                                        $total_outstanding_amount = 0;
                                        foreach ($customer_balance as $key => $value_balance) {?>
                                            <tr class="details_report" data-customar="<?php echo $key;?>">
                                               <td><?php echo !empty($value_balance['name']) ? $value_balance['name'] : '';?></td>
                                               <td><?php echo !empty($value_balance['nonpaid_invoice']) ? number_format((float)($value_balance['nonpaid_invoice']), 2, '.', '')  : '0.00';?></td>
                                               <td><?php echo !empty($value_balance['unused_credit_note']) ? '-'.number_format((float)($value_balance['unused_credit_note']), 2, '.', '') : '0.00';?></td>
                                               <td><?php echo !empty($value_balance['unused_payment']) ? number_format((float)abs($value_balance['unused_payment']), 2, '.', '') : '0.00';?></td>
                                               <td><?php echo number_format((float)($value_balance['nonpaid_invoice'] - $value_balance['unused_credit_note'] - abs($value_balance['unused_payment'])), 2, '.', '');?></td>
                                            </tr>
                                    <?php 
                                            $total_due_invoice += $value_balance['nonpaid_invoice'];
                                            $total_credit_note += $value_balance['unused_credit_note'];
                                            $total_unused_payment += $value_balance['unused_payment'];
                                            $total_outstanding_amount += ($value_balance['nonpaid_invoice'] - $value_balance['unused_credit_note'] - abs($value_balance['unused_payment']));
                                        }?>
                                            <tr style="font-weight: bold;">
                                                <td>Total</td>
                                                <td><?php echo number_format((float)$total_due_invoice, 2, '.', '');?></td>
                                                <td><?php echo number_format((float)$total_credit_note, 2, '.', '');?></td>
                                                <td><?php echo number_format((float)$total_unused_payment, 2, '.', '');?></td>
                                                <td><?php echo number_format((float)$total_outstanding_amount, 2, '.', '');?></td>
                                            </tr>
                                    <?php }?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<?php $this->load->view($footer); ?>
<script type="text/javascript">
	$(document).ready(function(){
        var state = <?php echo json_encode($state_array);?>;
       
        $('.date_calender .input-group.date').datepicker({
            todayBtn: "linked",
            keyboardNavigation: false,
            forceParse: false,
            calendarWeeks: true,
            language: 'en',
            autoclose: true
        });

        $('.details_report').on('click',function(){
            var customer = $(this).data('customar');
            window.open('<?php echo site_url("reports/customer_balance_details/'+customer+'");?>'); 
        });

        $('.generate_report').on('click',function(){ 
            var from = $('#start_date').val();
            var to = $('#end_date').val();
            var customer = $('#choose_customer').val();

            $.ajax({
                url: '<?php echo site_url('reports/customer_balance');?>',
                type: "POST",
                data:{
                    'from'          : from,
                    'to'            : to,
                    'customer'      : customer,
                    'data'          :'json'
                },
                success: function(response){ 
                    var data = JSON.parse(response);
                    var tr_invoice = '';
                    var tr_payment = '';
                    if (data.invoice_report.length > 0) {
                        data.invoice_report.map(function(value,index){
                            if (value.sale_invoice_id != value.paid_invoice) {
                                tr_invoice += '<tr>';
                                tr_invoice += '<td>'+value.invoice_date+'</td>';
                                tr_invoice += '<td>'+((value.invoice_no == null) ? '-' : value.invoice_no)+'</td>';
                                tr_invoice += '<td>'+value.sub_total+'</td>';
                                tr_invoice += '<td>'+(parseFloat(value.total) - parseFloat(value.sub_total))+'</td>';
                                tr_invoice += '</tr>';
                            }
                        });
                    }
                    if (data.payment_report.length > 0) {
                        data.payment_report.map(function(value,index){
                            tr_payment += '<tr>';
                            tr_payment += '<td>'+value.payment_date+'</td>';
                            tr_payment += '<td>'+value.account_name+'</td>';
                            tr_payment += '<td>'+value.amount+'</td>';
                            tr_payment += '<td>'+value.bank_charges+'</td>';
                            tr_payment += '<td>'+((value.payment_type == 1) ? 'Cash' : 'Cheque')+'</td>';
                            tr_payment += '<td>'+((value.reference == '') ? 'NA' : value.reference)+'</td>';
                            tr_payment += '<td>'+((value.note == '') ? '-' : value.note)+'</td>';
                            tr_payment += '</tr>';
                        });
                    }
                    $('#data_report_invoice').html('');
                    $('#data_report_invoice').html(tr_invoice);

                    $('#data_report_payment').html('');
                    $('#data_report_payment').html(tr_payment);
                }
            });
        });

        $('.generate_excel').on('click',function(){
            var from = $('#start_date').val();
            var to = $('#end_date').val();
            $.ajax({
                    url: '<?php echo site_url('reports/customer_balance');?>',
                    type: "POST",
                    data:{
                        'from'  : from,
                        'to'    : to,
                        'data' :'json',
                        'excel' :'1'
                    },
                    success: function(response){ 
                        var data = JSON.parse(response);
                        JSONToCSVConvertor(data, "B2B Report", true);
                    }
                });
        });

        function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) {
            //If JSONData is not an object then JSON.parse will parse the JSON string in an Object
            var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
            var CSV = '';    
            //Set Report title in first row or line
            //CSV += ReportTitle + '\r\n\n';
            //This condition will generate the Label/Header
            if (ShowLabel) {
                var row = "";
                //This loop will extract the label from 1st index of on array
                for (var index in arrData[0]) {
                    //Now convert each value to string and comma-seprated
                    row += index + ',';
                }
                row = row.slice(0, -1);
                //append Label row with line break
                CSV += row + '\r\n';
            }
            //1st loop is to extract each row
            for (var i = 0; i < arrData.length; i++) {
                var row = "";   
                //2nd loop will extract each column and convert it in string comma-seprated
                for (var index in arrData[i]) {
                    row += '"' + arrData[i][index] + '",';
                }
                row.slice(0, row.length - 1);
                //add a line break after each row
                CSV += row + '\r\n';
            }
            if (CSV == '') {        
                alert("Invalid data");
                return;
            }   
            //Generate a file name
            var fileName = "";
            //this will remove the blank-spaces from the title and replace it with an underscore
            fileName += ReportTitle.replace(/ /g,"_");   
            //Initialize file format you want csv or xls
            var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);
            // Now the little tricky part.
            // you can use either>> window.open(uri);
            // but this will not work in some browsers
            // or you will not get the correct file extension    
            
            //this trick will generate a temp <a /> tag
            var link = document.createElement("a");    
            link.href = uri;
            
            //set the visibility hidden so it will not effect on your web-layout
            link.style = "visibility:hidden";
            link.download = fileName + ".csv";
            
            //this part will append the anchor tag and remove it after automatic click
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
	});
</script>
<script type="text/javascript" language="javascript" src="//code.jquery.com/jquery-1.12.4.js"></script>
    <script src="//cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
    <script src="//cdn.datatables.net/buttons/1.5.1/js/dataTables.buttons.min.js"></script> 	
	<script src="//cdn.datatables.net/buttons/1.5.1/js/buttons.flash.min.js"></script> 
	<script src="//cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script> 
	<script src="//cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/pdfmake.min.js"></script> 
	<script src="//cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/vfs_fonts.js"></script>
	<script src="//cdn.datatables.net/buttons/1.5.1/js/buttons.html5.min.js"></script> 
    <script src="//cdn.datatables.net/buttons/1.5.1/js/buttons.print.min.js"></script>

<script type="text/javascript">
	var jq = jQuery.noConflict();

	jq(document).ready(function() {
	jq('.myTable').DataTable( {
			dom: 'Bfrtip',
			buttons: [
				'copy', 'csv', 'excel', 'pdf', 'print'
			]
		} );
	} );

</script>	