<div class="wrapper">
    <div class="container">
        <!-- Page-Title -->
        
        <div class="row">
            <div class="col-sm-12">
                <div class="pull-right m-t-15">     
                   
                </div>
                <h4 class="page-title">IMS UnPosted Invoices:</h4>
            </div>
        </div>
       
        <div class="row">
            <div class="col-sm-12">
                <div class="card-box table-responsive">

                     <div class="row m-b-20" id="filters">
                        <form method="Post" action="<?php echo base_url()."ims_unposted_invoices";?>">
                            <div class="row">   
                                <div class="col-md-6"></div>
                                     
                                <div class="col-md-6">
                                    <label for="reportrange" class="control-label">Date Range</label>
                                    <div class="form-group">
                                        <div id="reportrange" name="reportrange" class="form-control" style="display:inline">
                                            <i class="glyphicon glyphicon-calendar fa fa-calendar"></i>
                                            <span></span>
                                        </div>
                                        <input type="hidden" name="startdate" id="startdate" value="<?php echo $startdate;?>"><input type="hidden" name="enddate" id="enddate" value="<?php echo $enddate;?>">
                                        
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6"></div>
                                 <div class="col-md-4">
                                    <label for="invoice_type" class="control-label">Invoice Type</label>
                                    <div class="form-group">
                                        <select name="invoice_type" id="invoice_type" class="form-control">
                                            <option <?php if($invoice_type=='service'){echo "selected='selected'";} ?> value="service">Service</option>
                                            <option <?php if($invoice_type=='sale'){echo "selected='selected'";} ?> value="sale">Retail</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-2">
                                    <button type="submit" class="m-t-20 btn btn-sm btn-pink btn-bordred waves-effect w-md waves-light m-l-5">Run</button>   
                                </div>
                                
                            </div>
                        </form>
                    </div>
                    <hr>

                    <table id="tblreport" class="table table-striped table-bordered">
                        <thead>
                            <tr>
                               
                                <th>ID</th>
                                <th>Number</th>
                                <th>Date</th>
                                <th>Payable</th>  
                                <th>Tax Amount</th>  
                                <th>Cash</th>
                                <th>Card</th>
                                <th>Check</th>
                                <th>Voucher</th>
                                <th>Type</th>
                                <th>By</th>
                                <th>IMS Number</th>
                            </tr>
                        </thead>

                         <tbody>
                            <?php $return_value=0; $return_qty=0; foreach ($invoices as $rn){?>
                            <tr id="<?php echo $rn['id_invoice'];?>">
                                <td ><?php if($rn['reference_invoice_number'] !=''){ echo $rn['reference_invoice_number'];}else{echo '<a href="'.base_url().'existinginvoice/'.$rn['id_invoice'].'" target="_blank">'.$rn['id_invoice'].'</a>'  ;}?></td>
                                <td><?php  echo $rn['invoice_number'];?></td>
                                <td><?php echo $rn['invoice_date'];?></td>
                                <td><?php echo $rn['total_payable'];?></td>
                                <td><?php echo $rn['tax_total'];?></td>
                                
                                <td><?php echo $rn['paid_cash'];?></td>
                                <td><?php echo $rn['paid_card'];?></td> 
                                <td><?php echo $rn['paid_check'];?></td> 
                                <td><?php echo $rn['paid_voucher'];?></td>                                 
                                <td><?php if($rn['reference_invoice_number'] !=''){echo 'Recovery';}else{ echo $rn['invoice_type'];}?></td>
                                <td><?php echo $rn['created_by'];?></td>
                                <td class="imsnumber"><?php 
                                    if($rn['imsfiscal_invoice_number']=='' && $rn['reference_invoice_number'] ==''){ ?>
                                    <button id="btn_<?php echo $rn['id_invoice'];?>" onclick="updateimsfiscal(<?php echo $rn['id_invoice'];?>);" type="button" class="btn btn-warning">Post</button>
                                    <?php } else { ?>
                                    <?php echo $rn['imsfiscal_invoice_number'];?>
                                    <?php } ?>
                                </td>
                            </tr>
                            <?php } ?>
                        </tbody>
                        <tfoot>
                        
                    </table>
                </div>
            </div><!-- end col -->
        </div>
        <!-- end row -->
        
    </div>
    <script>
        $(document).ready(function() {
            <?php if(isset($startdate)){?>
               var startdate = '<?php echo date('F j, Y', strtotime($startdate)); ?>';
                var enddate = '<?php echo date('F j, Y', strtotime($enddate)); ?>';
                $('#reportrange span').html(startdate + ' - ' + enddate);

                $('#reportrange').daterangepicker({
                    format: 'MM/DD/YYYY',
                    startDate: moment().subtract(15, 'days'),
                    endDate: moment(),
                    minDate: '01/01/2012',
                    maxDate: '12/31/2090',
        //                    dateLimit: {
        //                        days: 60
        //                    },
                    showDropdowns: true,
                    showWeekNumbers: true,
                    timePicker: false,
                    timePickerIncrement: 1,
                    timePicker12Hour: true,
                    ranges: {
                        'Today': [moment()],
                        'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                        'Last 7 Days': [moment().subtract(6, 'days'), moment().add(1, 'days')],
                        'Last 30 Days': [moment().subtract(29, 'days'), moment().add(1, 'days')],
                        'This Month': [moment().startOf('month'), moment().endOf('month')],
                        'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
                    },
                    opens: 'left',
                    drops: 'down',
                    buttonClasses: ['btn', 'btn-sm'],
                    applyClass: 'btn-success',
                    cancelClass: 'btn-default',
                    separator: ' to ',
                    locale: {
                        applyLabel: 'Submit',
                        cancelLabel: 'Cancel',
                        fromLabel: 'From',
                        toLabel: 'To',
                        customRangeLabel: 'Custom',
                        daysOfWeek: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
                        monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
                        firstDay: 1
                    }
                }, function(start, end, label) {
                    //console.log(start.toISOString(), end.toISOString(), label);
                    startdate = start;
                    enddate = end;
                    $("#startdate").val(startdate.format('YYYY-MM-DD'));
                    $("#enddate").val(enddate.format('YYYY-MM-DD'));
                    $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
                });
            <?php } ?>
            $('#tblreport').DataTable({
                    dom: "Bfrtlip",
                    buttons: [{extend: "copy", className: "btn-sm btn-custom btn-trans"}, {extend: "csv", className: "btn-sm btn-pink btn-trans"},
                        {extend: "excel", className: "btn-sm btn-warning btn-trans"}, {extend: "pdf", className: "btn-sm btn-purple btn-trans"}],
                    responsive: !0
                });
                
                
                
        });
            
    function test(invoiceid){
        console.log($("#tblreport tr[id="+invoiceid+"] .imsnumber").html());
    }
        
        
    function updateimsfiscal(invoiceid){
        var check = "";
        check = '<?php if(isset($business[0]['imsfiscal'])){ if($business[0]['imsfiscal']=='Yes'){ echo "true";} else {echo false;}} else { echo 'false';}?>';
       //console.log(check);
        if(check==="true"){
            $.ajax({
                type: 'POST',
                url: '<?php echo base_url();?>getimsjson',
                data: {csrf_test_name: '', invoiceid:invoiceid, invoicetype:1},
                asyn: false,
                success: function(data) {
                    //console.log(data);
                    data = $.parseJSON(data);
                    var mJson = data.mJson;
                    var imsdetails = data.imsdetails;
                    
                    runimsfiscalupdate(mJson, invoiceid, imsdetails);
                }
            });
        } else {

            checksrbfiscal(invoiceid);
        }
               
    }
   
    function runimsfiscalupdate(data, invoiceid, imsdetails){
     
       
        var url = imsdetails.ims_url;
        var token = imsdetails.ims_token;
        var local = imsdetails.ims_local;
        var username = 'skedwise';
        var password = 'rest1234';
        
        var mData  = $.parseJSON(data);
        //console.log(mData);
         $.ajax({
            type: 'POST',
            //url: 'http://localhost:8524/api/IMSFiscal/GetInvoiceNumberByModel',
            url: url,
            contentType: "application/json",
            asyn: false,
            beforeSend: function (xhr) {
                xhr.setRequestHeader ("Authorization", "Bearer " + token);
            },            
            //data: {myJSON: data, url: url, token: token},
            data: data,
            success: function(response) {
                console.log(response);
               //response= $.parseJSON(response);
               
               toastr.success(response.Response, 'Fiscal');
                //update the log tables
                updateimslog(data, response.InvoiceNumber, invoiceid);
                
            }
        });
    }
    
    function updateimslog(data, invoicenumber, invoiceid){
       // console.log(data, invoicenumber, invoiceid);
     
        $.ajax({
            type: 'POST',
            url: 'imsfiscal_controller/imsfiscal_update_log',
            data: {data, invoicenumber: invoicenumber, invoiceid: invoiceid},
            asyn: false,
            success: function(response) {                
                toastr.success(response, 'FISCAL Log'); 
                
                var my_url = '<?php echo base_url(); ?>existinginvoice/' + invoiceid;
                window.open(my_url, "_blank");
                location.reload();
            }
        });
        
    }
    
    
    function checksrbfiscal(invoiceid){
        var check = "";
        check = '<?php if(isset($business[0]['srb_fiscal_service'])){ if($business[0]['srb_fiscal_service']=='Yes'){ echo "true";}}?>';
        console.log('srb' + check);
        if(check==="true"){
            $.ajax({
                type: 'POST',
                url: '<?php echo base_url();?>imsfiscal_controller/getsrbjson',
                data: {csrf_test_name: '', invoiceid:invoiceid, invoicetype:1},
                asyn: false,
                success: function(data) {
                    //console.log(data);
                    data = $.parseJSON(data);
                    var mJson = data.mJson;
                    var imsdetails = data.imsdetails;
                    
                    console.log(mJson);
                    runsrbfiscalupdate(mJson, invoiceid, imsdetails);
                }
            });
        } else {
            return false;
        }               
    }

    function runsrbfiscalupdate(data, invoiceid, imsdetails){
        var url = imsdetails.ims_url;
        var pos_user = imsdetails.pos_user;
        var pos_pass = imsdetails.pos_pass;
                
       // var mData  = $.parseJSON(data);
       
         $.ajax({
            type: 'POST',        
            url: url,
            contentType: "application/json",
            asyn: false,
            // beforeSend: function (xhr) {
            //     xhr.setRequestHeader ("Authorization", "Bearer " + token);
            // },            
            //data: {myJSON: data, url: url, token: token},
            data: data,
            success: function(response) {
                console.log(response);
               //var resp = $.parseJSON(response);
               
               toastr.success(response.msg, 'Fiscal');
                //update the log tables
                updatesrblog(data, response.srbInvoceId, invoiceid);
                
            }
        });
    }

    function updatesrblog(data, invoicenumber, invoiceid){
        console.log(data, invoicenumber, invoiceid);
     
        $.ajax({
            type: 'POST',
            url: 'imsfiscal_controller/srbfiscal_update_log',
            data: {data, invoicenumber: invoicenumber, invoiceid: invoiceid},
            asyn: false,
            success: function(response) {                
                toastr.success(response, 'FISCAL Log'); 
                
                var my_url = '<?php echo base_url(); ?>existinginvoice/' + invoiceid;
                window.open(my_url, "_blank");
                location.reload();
            }
        });


    }

</script>