<style>
     tr.strikethrough > td {text-decoration:line-through !important; color:red;} 
</style>
<div class="wrapper">
            <div class="container">
                <!-- Page-Title -->
                <div class="row">
                    <div class="col-sm-12">                        
                        <h4 class="page-title">Invoices</h4>
                    </div>
                </div>
                
                 <div class="row">
                    <div class="col-sm-12">
                        <div class="card-box table-responsive">                            
                            <?php if($this->session->userdata('role')=='Super User'){?>
                            <form method="POST" action="<?php echo base_url();?>invoice_controller/todayinvoices">
                                <div class="row">
                                    <div class="col-md-4">
                                        <input class="form-control mdate" id="mDate" name="mDate" value="<?php echo $today;?>">
                                    </div>
                                    <div class="col-md-2">
                                        <button class="btn btn-default" type="submit">Run</button>
                                    </div>
                                    <div class="col-md-6"></div>
                                </div>
                            </form>    
                            <?php } ?>
                            <h4 class="header-title m-t-0 m-b-30">&nbsp;</h4>

                            <table id="tblinvoice" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%">
                                <thead>
                                    <tr>
                                        <th>Day Seq.</th>
                                        <!--<th>Invoice ID</th>-->
                                        <th>Invoice #</th>
                                        <th>Invoice Date</th>
                                        <th>VisitDate</th>
                                        <th>Customer</th>                                        
                                        <th>Customer Cell</th>
                                        <th>Status</th>
                                        <th>Type</th>
                                        <th>Recovery</th>
                                        <th>Balance</th>
                                        <th>Paid Amount</th>
                                        <th>Advance</th>
                                        <th>Sub Total</th>
                                        <th>Other Charges</th>
                                        <th>Discount</th>
                                        <th>Gross Amount</th>
                                        <th>Taxes</th>
                                        <th>Net Amount</th>
                                        <th>Payment Mode</th>
                                        <th>Instrument</th>                                        
                                        <th>Discount Remarks</th>
                                        <th>IMS</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php 
                                        $balance = 0;
                                        $netamount = 0;
                                        $grossamount = 0;
                                        $subtotal = 0;
                                        $discount = 0;
                                        $taxes = 0;
                                        $paidamount = 0;
                                    ?>
                                    <?php foreach ($invoices as $invoice){?>
                                    
                                    <tr class="<?php if($invoice['invoice_status']!=='valid'){echo 'strikethrough';}?>">
                                        <td><?php echo $invoice['invoice_seq']; ?></td>
                                        <!--<td><?php echo $invoice['id_invoice']; ?></td>-->
                                        <td><?php echo $invoice['invoice_number']; ?></td>
                                        <td><?php echo $invoice['invoice_date']; ?></td>
                                        <td><?php echo $invoice['visit_time']; ?></td>
                                        <td class="text-custom"><?php echo $invoice['customer_name']; ?> <?php echo $invoice['invoice_extra']; ?></td>
                                        <td>
                                            
                                            <?php 
                                                if( $this->session->userdata('hide_cell') && $this->session->userdata('hide_cell') == "No"){
                                                    echo $invoice['customer_cell']; 
                                                } 
                                            ?>
                                        
                                        
                                        </td>
                                        <td><?php echo $invoice['invoice_status']; ?></td>
                                        <td><?php echo $invoice['invoice_type']; ?></td>
                                        <td><?php echo $invoice['reference_invoice_number'] !== "" ? "<label class='label label-info'>Recovery</label>" : ""; ?></td>
                                        <td class="text-danger"><?php echo $invoice['balance']; if($invoice['invoice_status']=='valid'){$balance+=$invoice['balance'];}?></td>
                                        <td><?php echo $invoice['paid_amount']; if($invoice['invoice_status']=='valid'){$paidamount += $invoice['paid_amount'];}?></td>
                                        <td><?php echo $invoice['advance_amount']; ?></td>
                                        <td><?php echo $invoice['sub_total']; if($invoice['invoice_status']=='valid'){$subtotal += $invoice['sub_total'];}?></td>
                                        <td><?php echo $invoice['other_charges']; ?></td>
                                        <td><?php echo $invoice['discount']; if($invoice['invoice_status']=='valid'){$discount += $invoice['discount'];}?></td>
                                        <td><?php echo $invoice['gross_amount']; if($invoice['invoice_status']=='valid'){$grossamount += $invoice['gross_amount'];}?></td>
                                        <td><?php echo $invoice['tax_total']; if($invoice['invoice_status']=='valid'){$taxes += $invoice['tax_total'];}?></td>
                                        <td><?php echo $invoice['net_amount']; if($invoice['invoice_status']=='valid'){$netamount+=$invoice['net_amount'];}?></td>
                                        <td><?php echo $invoice['payment_mode']; ?></td>
                                        <td><?php echo $invoice['instrument_number']; ?></td>
                                        
                                        <td><?php echo $invoice['discount_remarks']; ?></td>
                                        <td><?php echo $invoice['imsfiscal_invoice_number']; ?></td>
                                        <td>
                                            <a target="_blank" href="<?php if($invoice['invoice_type']=="service"){echo base_url().'existinginvoice/'.$invoice['id_invoice']; } elseif($invoice['invoice_type']=="sale") {echo base_url().'existingorderinvoice/'.$invoice['id_invoice']; } ?>" class="btn btn-warning waves-effect waves-light m-b-5"> <i class="fa fa-rocket m-r-5"></i> <span>Open</span> </a>
                                            <?php
                                            $visit_order_id = $invoice['visit_id'];
                                            $flag = '';
                                            if($invoice['invoice_type'] === "service"){
                                                $flag = 'service';
                                            } else{
                                                $flag = 'retail';
                                            }
                                            ?>
                                            <?php if(isset($business[0]['allow_invoice_cancel'])){
                                                if($business[0]['allow_invoice_cancel'] == 'Yes') {?>
                                                    <button onclick="cancelinvoice(<?php echo $invoice['id_invoice']; ?>, <?php echo $visit_order_id; ?>, '<?php echo $flag; ?>');" class="btn btn-icon waves-effect waves-light btn-danger m-b-5"> <i class="fa fa-remove"></i> </button>
                                                <?php } else if($this->session->userdata('role')=='Super User' || $this->session->userdata('role')=='Admin' || $this->session->userdata('role')=='Accountant'){?>
                                                    <button onclick="cancelinvoice(<?php echo $invoice['id_invoice']; ?>, <?php echo $visit_order_id; ?>, '<?php echo $flag; ?>');" class="btn btn-icon waves-effect waves-light btn-danger m-b-5"> <i class="fa fa-remove"></i> </button>
                                                <?php } 
                                                
                                                } else { ?>
                                                <button onclick="cancelinvoice(<?php echo $invoice['id_invoice']; ?>, <?php echo $visit_order_id; ?>, '<?php echo $flag; ?>');" class="btn btn-icon waves-effect waves-light btn-danger m-b-5"> <i class="fa fa-remove"></i> </button>
                                            <?php } ?>
                                        
                                            <?php if($invoice['receipt_url'] != '' && $this->session->userdata('role')=='Super User'){?>
                                                <a target="receipt" href="<?php echo $invoice['receipt_url'];?>" class="btn btn-icon waves-effect waves-light btn-success m-b-5"> <i class="fa fa-dollar"></i> </a>
                                            <?php } ?>
                                        </td>
                                    </tr>
                                    
                                    <?php } ?>
                                </tbody>
                                
                        <tfoot>
                            <tr>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                 <td></td> 
                                  <td></td>
                                <td></td>
                                <td><?php //echo $subtotal ? $subtotal : 0; ?></td>
                                <td><?php //echo $discount ? $discount : 0; ?></td>
                                <td class="text-right"><strong>Total:</strong></td>
                                <td><?php echo $paidamount ? $paidamount : 0; ?></td>
                                <td><?php //echo $balance ? $balance : 0; ?></td>
                                
                                
                                <td ><?php //echo $grossamount ? $grossamount : 0; ?></td>
                                <td><?php //echo $taxes ? $taxes : 0; ?></td>
                                <td><?php //echo $netamount ? $netamount : 0; ?></td>
                               
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                            </tr>
                        </tfoot>
                            </table>
                        </div>
                    </div><!-- end col -->
                </div>
                <!-- end row -->
                
                
                
    <script type="text/javascript">
        $(document).ready(function() {
            
            
            $('.mdate').datepicker({
                default: today,
                autoclose: true,
                todayHighlight: true,
                format: 'yyyy-mm-dd'
            });
            
            
            $('#tblinvoice').DataTable({
                lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                stateSave: true,
                fixedHeader: {header: true},
                
                <?php if(DOWNLOAD == true || $this->session->userdata('role') == 'Admin' || $this->session->userdata('role')=='Super User'){ ?>
                    dom: "Bfrtlip",
                    buttons: [{extend: "copy", className: "btn-sm btn-custom btn-trans"}, {extend: "csv", className: "btn-sm btn-pink btn-trans", footer: true}, {
                            extend: "excel",
                            className: "btn-sm btn-warning btn-trans"
                        }, {extend: "pdf", className: "btn-sm btn-purple btn-trans", footer: true}
                    , {extend: "print", className: "btn-sm btn-primary btn-trans", footer: true}],
                <?php } else { ?>
                    dom: "frtlip",
                <?php } ?>
                    responsive: !0,
                    //"scrollX": true,
            });

        } );
        //TableManageButtons.init();
        
        function cancelinvoice(invoiceid, visit_order_id, flag){
            //Warning Message

            swal({
                title: "Are you sure?",
                text: "Give Reason For Cancelling This Invoice:",
                type: "input",
                showCancelButton: true,
                closeOnConfirm: false,
                inputPlaceholder: "reason for cancelling"
              }, function (inputValue) {
                if (inputValue === false) return false;
                if (inputValue === "") {
                  swal.showInputError("You need to write something!");
                  return false
                }
                
                if(flag=='service'){
                    var check = "";
                    check = '<?php if(isset($business[0]['srb_fiscal_service'])){ if($business[0]['srb_fiscal_service']=='Yes'){ echo "true";} else { echo "false";}}?>';
                    
                    if(check=="false"){

                        check = '<?php if(isset($business[0]['imsfiscal'])){ if($business[0]['imsfiscal']=='Yes'){ echo "true";} else { echo "false";}}?>';

                    }

                    console.log('srb' + check);
                    if(check==="true"){
                        swal.showInputError("Connected with Taxation systems. You Cannot Cancel Invoices!");
                        return false
                    }else {
                        updateimsfiscal(invoiceid, visit_order_id, 3, flag, inputValue);
                    }
                } else {
                    var check = "";
                    check = '<?php if(isset($business[0]['srb_fiscal_sale'])){ if($business[0]['srb_fiscal_sale']=='Yes'){ echo "true";} else { echo "false";}}?>';
                    
                    if(check=="false"){

                        check = '<?php if(isset($business[0]['imsfiscal_r'])){ if($business[0]['imsfiscal_r']=='Yes'){ echo "true";} else { echo "false";}}?>';

                    }

                    console.log('pra ' + check);
                    if(check==="true"){
                        swal.showInputError("Connected with Taxation systems. You Cannot Cancel Invoices!");
                        return false
                    }else {
                        updateimsfiscal(invoiceid, visit_order_id, 3, flag, inputValue);
                    }
                }
            });
            
        }

        function openinvoice(invoiceid){
            $.ajax({
                    type: 'POST',
                    url: '<?php echo base_url();?>invoice_controller/openinvoice',
                    data: {invoiceid: invoiceid},
                    success: function(data) {
                        
                    }
                });
        }
        
        
        
    function updateimsfiscal(invoiceid, visit_order_id, invoicetype, flag, inputValue){
        console.log(flag);
        //return false;
        var check = "";
        if(flag="service"){
            check = '<?php if(isset($business[0]['imsfiscal'])){ if($business[0]['imsfiscal']=='Yes'){ echo "true";}}?>';
            check = '<?php if(isset($business[0]['srb_fiscal_service'])){ if($business[0]['srb_fiscal_service']=='Yes'){ echo "true";}}?>';
        }else{
            check = '<?php if(isset($business[0]['imsfiscal_r'])){ if($business[0]['imsfiscal']=='Yes'){ echo "true";}}?>';
            check = '<?php if(isset($business[0]['srb_fiscal_sale'])){ if($business[0]['srb_fiscal_service']=='Yes'){ echo "true";}}?>';
        }
       
        if(check==="true"){
            
            var url = '<?php echo base_url();?>imsfiscal_controller/getimsjson_r';
            if(flag=='service'){ url = '<?php echo base_url();?>imsfiscal_controller/getimsjson';}
            
            $.ajax({
                type: 'POST',
                url: url,
                data: {invoiceid:invoiceid, invoicetype:invoicetype},
                asyn: false,
                success: function(data) {
                   data = $.parseJSON(data);
                    var mJson = data.mJson;
                    var imsdetails = data.imsdetails;
                    var x;
                    x = runimsfiscalupdate(mJson, invoiceid, visit_order_id, imsdetails, inputValue, flag);
                    
                }
            });
        } else {
            sked_invoice_cancel(invoiceid, visit_order_id, flag, inputValue);
        }
               
    }
    
    function runimsfiscalupdate(data, invoiceid, visit_order_id, imsdetails, inputValue, flag){
        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) {
               toastr.success(response.Response, 'Fiscal');
               console.log(response.Response);
               var r=response.Response;
                //update the log tables
                updateimslog(data, response.InvoiceNumber, invoiceid);
                
                if(r  === 'Invoice received successfully'){
                   sked_invoice_cancel(invoiceid, visit_order_id, flag, inputValue);
                } else {
                    swal("Info!", "Invoice was not removed!.".r, "error");
                }
                
                
            }
        });
    }
    
    function updateimslog(data, invoicenumber, invoiceid){
       // console.log(data, invoicenumber, invoiceid);
        $.ajax({
            type: 'POST',
            url: '<?php echo base_url();?>imsfiscal_controller/imsfiscal_update_log',
            data: {data, invoicenumber: invoicenumber, invoiceid: invoiceid},
            asyn: false,
            success: function(response) {                
                toastr.success(response, 'FISCAL Log');    
                
            }
        });
        
    }
    
    function sked_invoice_cancel(invoiceid, visit_order_id, flag, inputValue){
        $.ajax({
            type: 'POST',
            url: '<?php echo base_url();?>invoice_controller/cancelinvoice',
            data: {
                invoiceid : invoiceid,
                visit_order_id : visit_order_id,
                flag : flag,
                reason : inputValue
            },
            success: function(data) {
                var result = data.split("|");
                if (result[0] === "success") {
                    swal("Deleted!", "Your invoice has been removed.", "success");
                    location.reload();
                } else {
                    swal("Info!", "Invoice was not removed!. "+result[1] , "error");
                }
            } 
        });
    }


    function getreceiptjson(invoiceid, flag){
        
        var url = '<?php echo base_url();?>ReceiptsAPI/receiptsjson_retail';
        if(flag=='service'){ url = '<?php echo base_url();?>ReceiptsAPI/receiptsjson_service';}

        $.ajax({
            type: 'POST',
            url: url,
            data: {invoiceid:invoiceid},
            
            asyn: false,
            success: function(data) {
                console.log(data);
               // data = $.parseJSON(data);
                // var mJson = data.mJson;
                sendreceiptdata(invoiceid, data);
                
                
            }
        });

            
    }



    function callreceiptapi(data, invoiceid){
        //login to api
        var url = 'https://receipt.mexyon.com/login_user';        
        var username = 'mexyon123.com';
        var password = 'password123';
        var token = '';
        $.ajax({
            type: 'POST',           
            url: url,
            contentType: "application/json",
            asyn: false,
            // beforeSend: function (xhr) {
            //     xhr.setRequestHeader ("Authorization", "Bearer " + token);
            // },                        
            data: {email: "mexyon123.com", password: "password123"},            
            success: function(response) {
                var res= parseJSON(response);

                if(res.msg == 'Login successful'){
                    console.log("receipt api success logged in");
                    token = res.token;
                    sendreceiptdata(invoiceid, data, token);
                } else {
                    console.log("receipt api failed logged in");
                }
                

            }
        });
    }

    function sendreceiptdata(invoiceid, data, token){
        var url = 'https://receipt.mexyon.com/insert-receipt';  
        var mData  = $.parseJSON(data);

        var token = "bWV4eW9ucmVjZWlwdEBnbWFpbC5jb206YWRtaW4xMjM=";
        //var token = "cGVuZ3JlY2VpcHRAZ21haWwuY29tOnBlbmcxMjM=";

         $.ajax({
            url: "https://receipt.mexyon.com/insert-receipt",
            method: "POST",
            data: data,
            type: "json",
            contentType: "application/json",
             beforeSend: function (xhr) {
                xhr.setRequestHeader ("Authorization", "Basic " + token);
                // xhr.setRequestHeader ("email", useremail);
                // xhr.setRequestHeader ("password", userpassword);
            },         
            success: function(response) {               
               console.log(response.message);
               var r=response.message;
               var code = response.receipt_code;
               var url = response.receipt_url;                
                
                if(r  === 'Data inserted successfully'){
                    console.log('receitpapi success ' + url);
                    updateslipcode(url, code);
                    window.open(url);
                } else {
                    console.log('receitpapi fail: ' + response);
                }                
            },
            error: function(err){
                console.log(err);
            }
        });

    }


    function updateslipcode(url, code, invoiceid){

        $.ajax({
            type: 'POST',
            url: '<?php echo base_url();?>invoice_controller/updateslipcode',
            data: {
                invoiceid : invoiceid,
                receipt_code : code,
                receipt_url : url
            },
            success: function(data) {
                var result = data.split("|");
                if (result[0] === "success") {
                    swal("Success", "Rceipt Code updated", "success");
                    
                } else {
                    swal("Error", "Receipt Code not sent", "error");
                }
            } 
        });

    }



    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'); 
                
                window.location.href = '<?php echo base_url(); ?>existinginvoice/' + invoiceid;
            }
        });


    }

    </script>
