@extends('layouts.master')

@push('css')
@endpush

@section('content')
<?php //echo "<pre>"; print_r($po_data); exit(); ?>
<style type="text/css">
    .tborder {border: 1px solid black !important;}
    table.customtble tbody tr td{
        padding: 0px 5px 0px 5px;
        /*border:1px solid #000;*/
        font-size: 13px;
        color: gray;

    }
    table.customtble thead tr th{
        padding: 0px 5px 0px 5px;
        /*border:1px solid #000;*/
        font-size: 14px;
        font-weight: bold;
    }
    @media print{
        table.customtble thead tr th{
            font-size: 11px;
        }
        table.customtble tbody tr td{
            font-size: 10px;
        }
        body * { visibility: hidden; margin-top: 0px !important;}
        .printableArea, .printableArea *{ visibility: visible !important; }
        table{ border-collapse: collapse;}
        @page {size: landscape}
    }
</style>
<div class="container-fluid">
    <div class="printableArea" id="printableArea">  
        <form id="FormId" class="form-horizontal" method="POST" action="{{ route('itemLedger') }}">   
            {{ csrf_field() }}
            <div class="form-horizontal form-body hidden-print">
                <div class="row">
                    <div class="col-md-12">
                        <div class="panel panel-default">

                            <div class="panel-body">
                                <div class="row">
                                    <div class="col-md-5">
                                        <div class="form-group">
                                            <label for="product_id" class="col-sm-3 control-label">Product Name</label>
                                            <div class="col-sm-8">
                                                <select id="product_id" name="product_id" class="form-control" >
                                                    <option value=""></option>
                                                </select>
                                            </div>
                                        </div> 
                                    </div>
                                    <div class="col-md-3">
                                        <div class="form-group">
                                            <label for="fromdate" class="col-sm-4 control-label">From Date</label>
                                            <div class="col-sm-7">
                                                <input type="text" name="fromdate" id="fromdate" class="form-control" autocomplete="false" placeholder="dd/mm/yyyy" value="<?php echo date('d-m-Y', strtotime($fromdate)); ?>" />
                                            </div>

                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="form-group">
                                            <label for="fromdate" class="col-sm-4 control-label">To Date</label>
                                            <div class="col-sm-7">
                                                <input type="text" name="todate" id="todate" class="form-control" autocomplete="false" placeholder="dd/mm/yyyy" value="<?php echo date('d-m-Y', strtotime($todate)); ?>" />
                                            </div>

                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-11 col-lg-11 col-sm-11 col-xs-12 text-right">
                                        <span class="spin-loader"></span>
                                    </div>
                                    <div class="col-md-1  text-right">
                                        <button id="submitbutton" type="button" class="btn btn-primary"><i class="fa fa-search"></i> Run</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </form>
        <div class="row">
            <div class="col-md-12">
                <div class="panel panel-default">

                    <div class="panel-body">
                        <div class="clearfix">
                            <div class="pull-left ">
                                <!-- <h3 class="logo invoice-logo"><img src='{{asset('plugins/images/'.$business->business_logo)}}' width="200" alt='logo here' /></h3> -->
                            </div>
                        </div>
                        <hr class="hidden">
                        <div class="row">
                            <div class="col-md-12"><h3 class="text-center">Item Ledger</h3></div>
                        </div>
                        <div class="row hidden">
                            <div class="col-md-12">
                                <table style=" width: 100%;" cellspacing="0" id="podetailstbl" class="customtble">
                                    <tr>
                                        <td style="width: 50% ">
                                            <p><strong>From </strong>: <span id="fromdateshow"><?php echo date('d-M-Y', strtotime($fromdate)); ?></span>
                                                <br>
                                                <strong>To </strong>: <span id="todateshow"><?php echo date('d-M-Y', strtotime($todate)); ?></span>
                                                <br>
                                                <strong></strong> <span id="mode">&nbsp;</span>
                                            </p>

                                        </td>
                                        <td style="width: 0.5%; border-bottom: none !important; border-top: none !important;"></td>
                                        <td style="width: 50%">
                                            <p><strong>Statement Date: </strong> <?php echo date('d-M-Y'); ?>
                                                <br>
                                                <strong></strong> <span id="mode">&nbsp;</span>
                                                <br>
                                                <strong></strong> <span id="mode">&nbsp;</span>
                                            </p>

                                        </td>
                                    </tr>
                                </table>

                            </div><!-- end col -->
                        </div>
                        <!-- end row -->

                        <div class="m-h-50">&nbsp;</div>
                        <div class="row hidden">
                            <div class="col-md-12">
                                <div class="btn-group m-r-10">
                                    <button data-toggle="dropdown" class="btn btn-default btn-outline dropdown-toggle waves-effect waves-light" type="button">
                                        Show/Hide Columns <span class="caret"></span>
                                    </button>
                                    <ul role="menu" id="shCol" class="dropdown-menu animated lightSpeedIn icheck-list">
                                        
                                        <li>
                                            <div class="ckbox ckbox-primary">
                                                <input class="check" data-checkbox="icheckbox_square-red" type="checkbox" checked="checked" id="checkserial" value="0" >
                                                <label for="checkserial">#</label>
                                            </div>
                                        </li>

                                        <li>
                                            <div class="ckbox ckbox-primary">
                                                <input class="check" data-checkbox="icheckbox_square-red" type="checkbox" checked="checked" id="checktrans" value="1">
                                                <label for="checktrans">Trans#</label>
                                            </div>
                                        </li>
                                        
                                        <li>
                                            <div class="ckbox ckbox-primary">
                                                <input class="check" data-checkbox="icheckbox_square-red" type="checkbox" checked="checked" id="checkdate" value="2">
                                                <label for="checkdate">Date</label>
                                            </div>
                                        </li>

                                         <li>
                                            <div class="ckbox ckbox-primary">
                                                <input class="check" data-checkbox="icheckbox_square-red" type="checkbox" checked="checked" id="checkparticular" value="3">
                                                <label for="checkparticular">Particular</label>
                                            </div>
                                        </li>

                                        <li>
                                            <div class="ckbox ckbox-primary">
                                                <input class="check" data-checkbox="icheckbox_square-red" type="checkbox" checked="checked" id="checktype" value="4">
                                                <label for="checktype">Type</label>
                                            </div>
                                        </li>
                                        
                                        <li>
                                            <div class="ckbox ckbox-primary">
                                                <input class="check" data-checkbox="icheckbox_square-red" type="checkbox" checked="checked" id="checkqtyreceipt" value="5">
                                                <label for="checkqtyreceipt">Qty Receipt</label>
                                            </div>
                                        </li>
                                        
                                        <li>
                                            <div class="ckbox ckbox-primary">
                                                <input class="check" data-checkbox="icheckbox_square-red" type="checkbox" checked="checked" id="checkqtyissue" value="6">
                                                <label for="checkqtyissue">Qty Issue</label>
                                            </div>
                                        </li>
                                        
                                        <li>
                                            <div class="ckbox ckbox-primary">
                                                <input class="check" data-checkbox="icheckbox_square-red" type="checkbox" checked="checked" id="checkbatch" value="7">
                                                <label for="checkbatch">Batch#</label>
                                            </div>
                                        </li>
                                        
                                        <li>
                                            <div class="ckbox ckbox-primary">
                                                <input class="check" data-checkbox="icheckbox_square-red" type="checkbox" checked="checked" id="checkrate" value="8">
                                                <label for="checkrate">Rate</label>
                                            </div>
                                        </li>
                                        
                                        <li>
                                            <div class="ckbox ckbox-primary">
                                                <input class="check" data-checkbox="icheckbox_square-red" type="checkbox" checked="checked" id="checkamount" value="9">
                                                <label for="checkamount">Amount</label>
                                            </div>
                                        </li>
                                        
                                        <li>
                                            <div class="ckbox ckbox-primary">
                                                <input class="check" data-checkbox="icheckbox_square-red" type="checkbox" checked="checked" id="checkbalance" value="10">
                                                <label for="checkbalance">Balance</label>
                                            </div>
                                        </li>
                                        
                                    </ul>
                                </div>
                            </div>
                        </div>
                        <div class="m-h-50">&nbsp;</div>
                        <div class="row">
                            <div class="col-md-12">
                                <div class="table-responsive">
                                    <!-- <table class="table table-bordered m-t-30" id="tblproducts"> -->
                                    <table id="tblreport" class="display nowrap table-bordered " style="width: 100%;">
                                        <thead>
                                            <tr>
                                                <th>#</th>
                                                <th class="text-center">Sale Order#</th>
                                                <th class="text-center">Date</th>
                                                <th class="text-center">Customer</th>
                                                <th class="text-center">Type</th>
                                                <th class="text-center">Qty Receipt</th>
                                                <th class="text-center">Qty Issue</th>
                                                <th class="text-center">Batch</th>
                                                <th class="text-center">Rate</th>
                                                <th class="text-center">Amount</th>
                                                <th class="text-center">Balance</th>
                                            </tr>
                                        </thead>
                                        <tbody><tr><td>Data not found</td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tbody>
                                    </table>
                                </div>
                            </div>
                        </div>

                        <hr>
                        <div class="hidden-print">
                            <div class="pull-right">
                                <a id="printbutton" href="#" class="btn btn-inverse waves-effect waves-light hidden" onclick='window.print();'  ><i class="fa fa-print"></i></a>

                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>    
    <!-- end row -->
</div>
<script>
    $(document).ready(function(){
        $('#fromdate').datepicker({
                autoclose: true,
                todayHighlight: true,
                format: "dd-mm-yyyy",
//                viewMode: "months", 
//                minViewMode: "months"
        });

        $('#todate').datepicker({
            autoclose: true,
            todayHighlight: true,
            format: "dd-mm-yyyy",
        });
        
        var shTable;
        $('#submitbutton').click(function(){
            if($('#product_id option:selected').val() === ""){
                swal({
                    title: "Product & Date Should not be empty!",
                    type: "info",
                    confirmButtonText: 'OK!'
                });
                return;
            }
            $('.spin-loader').addClass('fa fa-spin fa-spinner');
            $('#fromdateshow').html('').html($('#fromdate').val());
            $('#todateshow').html('').html($('#todate').val());
            var product_name = $('#product_id option:selected').text();
                product_name = product_name.split('|');
            $.ajax({
                type: 'POST',
                url: $('#FormId').attr('action'),
                data: {fromdate: $('#fromdate').val(), todate: $('#todate').val(), product_id: $('#product_id option:selected').val()},
                dataType: 'json',
                headers: {
                    'X-CSRF-TOKEN': '<?php echo csrf_token(); ?>'
                },
                success: function(response){
                    var data = response;var d = 0, r = 0, dd = 0;
                    var body = '', total_return = 0.00, total_delivered = 0.00, total_amount = 0.00, total_unit_price = 0.00, total_balance = 0.00;
                    var hhtml = '<tr><th>#</th><th class="text-center">Sale Order#</th><th class="text-center">Date</th><th class="text-center">Customer</th><th class="text-center">Type</th><th class="text-center">Qty Receipt</th><th class="text-center">Qty Issue</th><th class="text-center">Batch</th><th class="text-center">Rate</th><th class="text-center">Amount</th><th class="text-center">Balance</th></tr>';
                    for(var i = 0; i < data.length; i++){
                        total_return += parseFloat(data[i]['return_qty']); total_delivered += parseFloat(data[i]['gdn_qty_delivered']);
                        total_amount += parseFloat(data[i]['amount']); total_unit_price += parseFloat(data[i]['gdn_unit_price']);
                        if(data[i]['type'] == 'Sale' && i != 0){
                          d += parseInt(data[i]['gdn_qty_delivered']);
                        }
                        if(data[i]['type'] == 'Return'){
                          r += parseInt(data[i]['return_qty']);
                        }
                        body += '<tr>';
                        body += '<td>'+(i+1)+'</td>';
                        body += '<td>'+data[i]['sale_order_number']+'</td>';
                        body += '<td class="text-center">'+data[i]['sale_date']+'</td>';
                        body += '<td>'+data[i]['customer_name']+'</td>';
                        body += '<td class="text-center">'+data[i]['type']+'</td>';
                        body += '<td class="text-right">'+addCommas(data[i]['return_qty'])+'</td>';
                        body += '<td class="text-right">'+addCommas(data[i]['gdn_qty_delivered'])+'</td>';
                        body += '<td class="text-center">'+data[i]['gdn_batch_number']+'</td>';
                        body += '<td class="text-right">'+addCommas(parseFloat(data[i]['gdn_unit_price']))+'</td>';
                        body += '<td class="text-right">'+addCommas(parseFloat(data[i]['amount']))+'</td>';
                        if(data[i]['type'] != 'Return'){
                            dd += data[i]['gdn_qty_delivered'];
                            body += '<td class="text-right">'+(data[i]['batch_qty']-data[i]['gdn_qty_delivered']-d)+'</td>';
                        }else if(data[i]['type'] != 'Sale'){
                            body += '<td class="text-right">'+(((data[i]['batch_qty'] - dd) + data[i]['return_qty'])-r)+'</td>';
                        }
                        body += '</tr>';
                    }
                    
                    if(data.length > 0){
                        $('.spin-loader').removeClass('fa fa-spin fa-spinner');
                        var heading = '<tr><td></td><td><strong>Item Ledger</strong></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>';
                        var date = '<tr><td></td><td><strong>From: </strong>'+$('#fromdate').val()+'<strong> To: </strong>'+$('#todate').val()+'</td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>';
                        var total_row = '<tr><td></td><td></td><td></td><td></td><td class="text-right"><strong>Total:</strong></td><td class="text-right">'+addCommas(total_return)+'</td><td class="text-right">'+addCommas(total_delivered)+'</td><td></td><td class="text-right">'+addCommas(total_unit_price.toFixed(2))+'</td><td class="text-right">'+addCommas(total_amount.toFixed(2))+'</td><td></td></tr>';
                        var tbody = heading+date+body+total_row;
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append(tbody);
                        
                        shTable = $('#tblreport').DataTable({
                            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
//                            stateSave: true, 
                            fixedHeader: {header: true},
                            "bSort" : false,
                            dom: "Bfrtlip",
                            buttons: [
                                {extend: "excel", title: '<?php echo $business->business_name; ?>\n Item Ledger \n'+product_name[1], filename: 'itemLedger', exportOptions: { columns: ':visible' }}, 
                                {extend: "pdf", title: '<?php echo $business->business_name; ?>\n Item Ledger \n'+product_name[1], filename: 'itemLedger', orientation: 'landscape', exportOptions: { columns: ':visible' }, pageSize: 'A4',}
                            ],
                            //responsive: !0
                        });
                    }else{
                        $('.spin-loader').removeClass('fa fa-spin fa-spinner');
                        $("#tblreport").dataTable().fnDestroy();
                        $("#tblreport thead").html('');
                        $("#tblreport tbody").html('');
                        $("#tblreport thead").append(hhtml);
                        $("#tblreport tbody").append('<tr><td>Data not found</td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>');
                        $('#printbutton').addClass('hidden');
                    }
                }
            });
        });
        
        jQuery('#shCol input').on('click', function() {
            // Get the column API object
            var column = shTable.column($(this).val());
            // Toggle the visibility
            if ($(this).is(':checked')){
                column.visible(true);
            }else{
                column.visible(false);
            }
        });
        
        $("#product_id").select2({

        maximumSelectionSize: 6,
        width: 300,
        placeholder: "Search product...",
        minimumInputLength: 2,
        ajax: { 
            url: "{{url('sale/getProduct')}}",
            type: "post",
            dataType: 'json',
            delay: 250,
            beforeSend: function(xhr){
                xhr.setRequestHeader('X-CSRF-Token', "{{csrf_token()}}");
            },
            data: function (params) {
                return {
              searchTerm: params.term, // search term
              //brand_id : $("#brand option:selected").val()
              
          };
      },
      processResults: function (response) {
       return {
        results: response
    };
},
cache: true
}
});
    });
    function addCommas(nStr)
{
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}
</script>
@endsection

