<?php 
$user_id = $this->session->userdata('user_id');
if(!$user_id){ redirect('user/login_view', 'refresh'); }
$bankname = $this->db->query("select * from bank_name where status=1 and buisness_id='$b_type' limit 1");
foreach ($bankname->result() as $name){ $bname = $name->id;  }
?>
<!DOCTYPE html>
<html lang="en">
<?php $this->load->view('head.php'); ?>
<body class="dashboard">
<div id="wrapper">

<div class="admin-title"><div class="row"><?php $this->load->view('header.php'); ?></div></div>

<div class="content-area"><div class="row">
<div class="admin-menu"><?php $this->load->view('sidebar.php'); ?></div>

<div class="content-menu">
  <div class="panel-heading"><h2 class="transac">All Transaction</h2></div>
</div>

<div class="main-content">
<div class="btn-controls">
<div class="content-menu-dash">
  <ul class="nav nav-tabs nav-stacked">
    <?php
      $firstbankid=0;
    $type = $this->db->query("select * from bank_name where status=1 and buisness_id='$b_type'");
    foreach ($type->result() as $row){
        if($row->id && !$firstbankid){
            $firstbankid=$row->id;
        }
        $activ = ($row->id==$tabid || (!$tabid && $row->id==$bname))?'active':'';
        $background = ($markbank[$row->id] < 0)?'background:#c61d23!important;color:#fff;':'background:green;';
        echo '<li class="page-header '.$activ.'"><a style="'.$background.'" data-toggle="tab" onclick="pagination('.$row->id.')" href="#'.$row->id.'" class="tabtitle'.$row->id.'">'.ucfirst($row->type).'</a></li>';
    }
    ?>
  </ul>
</div>

<div class="tab-content dash-tab">
<?php 
$bank=$this->db->query("select * from bank_name where status=1 and buisness_id='$b_type'");
foreach ($bank->result() as $bankrow){
  $data_id=$bankrow->id;
  $actv = ($data_id==$tabid || (!$tabid && $data_id==$bname))?'in active':'';
  $banktotal=$this->db->query("select * from sale_purchases where status=1 and buisness_id='$b_type' and bank_id='$data_id'");
  $totaltabcradit=0;$totaltabdebit=0;
  foreach ($banktotal->result() as $banktab){ $totaltabcradit+=$banktab->amount; $totaltabdebit+=$banktab->pur_amount; }
  $totalamounttab=$totaltabcradit-$totaltabdebit;
?>
<div id="<?php echo $data_id; ?>" class="tab-pane fade <?php echo $actv; ?>">
  <h3><?php echo ucfirst($bankrow->type);?></h3>

  <div class="action_btn">
    <form method="post" action="<?php echo site_url('Excel_export/dashboard');?>" style="display:inline;">
     <!-- <button type="submit" title="Export" data-toggle="tooltip"><span class="glyphicon glyphicon-ice-lolly-tasted"></span></button>-->
      <input type="hidden" name="tab" value="<?php echo $data_id; ?>">
      <input type="hidden" name="from" class="datefrom<?php echo $data_id; ?>">
      <input type="hidden" name="to" class="dateto<?php echo $data_id; ?>">
    </form>
    <input type="hidden" id="bname" value="<?php echo $bname; ?>">
    <input type="hidden" id="pagitab" value="<?php echo $data_id; ?>">
    <!--<button class="p-btn" title="Print" onclick="printDiv('printableArea<?php echo $data_id;?>')"><span class="glyphicon glyphicon-print"></span></button>-->
   <!-- <button class="p-btn search" title="Search"><span class="glyphicon glyphicon-search"></span></button>-->
  </div>

  <div class="filtertab home">
    <input type="hidden" id="tabbank" value="<?php echo $data_id;?>">
    <select class="tabfilterprofit">
        <option value="Total">Total</option>
        <option value="This Month">This Month</option>
        <option value="Last Month">Last Month</option>
        <option value="This Year">This Year</option>
        <option value="Last Year">Last Year</option>
    </select>
    <div class="top-row color-profit-filter">
        <p><strong class="totalprofit"><?php echo number_format($totalamounttab,2);?> €</strong> <span class="tabfiltervalue">Total</span> <?php echo ucfirst($bankrow->type);?></p>
        <p><strong class="totaldebit"><?php echo number_format($totaltabdebit,2);?> €</strong> Debit</p>
        <p style="background:#79c501;"><strong class="totalcradit"><?php echo number_format($totaltabcradit,2);?> €</strong> Credit</p>
    </div>
  </div>

  <div id="printableArea<?php echo $data_id; ?>" class="dashboardtable">
    <div class="date_filter">
        <div class="date_filter_data"><input style="width:150px;" class="form-control" id="min<?php echo $data_id; ?>" type="text" placeholder="From"></div>
        <div class="date_filter_data"><input style="width:150px;" class="form-control" id="max<?php echo $data_id; ?>" type="text" placeholder="To"></div>
        <div class="date_filter_data" style="width:100px;">
   <button type="button" style="width:100px;" class="btn btn-default" onclick="resetDateFilter(<?php echo $data_id; ?>)">Reset</button>
</div>
    </div>
    <table class="table table-striped table-bordered table-hover mytable dash-table" id="example<?php echo $data_id; ?>">
      <thead><tr><th>Date</th><th>Type</th><th>Debit</th><th>Credit</th><th>Balance</th></tr></thead>
      <tbody></tbody>
      <tfoot><tr class="total-value">
        <th></th><th>Total:</th>
        <th id="debitttl<?php echo $data_id;?>"></th>
        <th id="craditttl<?php echo $data_id;?>"></th>
        <th id="balance<?php echo $data_id;?>"></th>
      </tr></tfoot>
    </table>
  </div>
</div>
    
<?php } ?>
</div></div></div></div></div>

 <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
  <script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
  <script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker.css" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
//extra
    <link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.dataTables.min.css"/>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.print.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
    //extra
    
<?php $this->load->view('footer.php'); ?>
    
<script>

    
<?php foreach ($bank->result() as $bankrow){ ?>
    $('#min<?php echo $bankrow->id; ?>, #max<?php echo $bankrow->id; ?>').datepicker({
        format:"dd/mm/yyyy",
        autoclose:true
    }).on('changeDate', function(){ applyDateFilter(<?php echo $bankrow->id;?>); });
   <?php } ?>
    function resetDateFilter(tabid){
    $('#min'+tabid).val('');
    $('#max'+tabid).val('');
    $('.datefrom'+tabid).val('');
    $('.dateto'+tabid).val('');
    $('#example'+tabid).DataTable().ajax.reload(); // reload full data
}
     function exportdate(min,max){
            $("#datefrom").val(min);
             $("#dateto").val(max);
            
        }       
var st = $('.tabfilterprofit');

st.change(function(){
 var text=($(this).val());
   
   $(".tabfiltervalue").text(text);
   tabprofit(text);
});
      
</script>
     <script>
        function tabprofit(value){
        
          var id = $('#tabbank').val();
          // alert(id);
           $.ajax({
              url: "<?php echo base_url()?>user/dashtabfilter",
            type: "POST",
            data    : {'text':value,'tabid':id,},
                 dataType: 'json',
            success: function(data){
                
                $(".totalprofit").text((data.totalprofit).toLocaleString(undefined, {minimumFractionDigits: 2}) +' €');
                $(".totaldebit").text((data.totaldebit).toLocaleString(undefined, {minimumFractionDigits: 2}) +' €');
                $(".totalcradit").text((data.totalcradit).toLocaleString(undefined, {minimumFractionDigits: 2}) +' €');
            }
        });
            
        }
        $('.p-btn.search').on('click', function(){
  $('.dash-tab .dataTables_filter').slideToggle('fast');
});
    </script>
<script>
     
initTable('<?php echo  $firstbankid;?>');
    function applyDateFilter(tabid){
    $('.datefrom'+tabid).val($('#min'+tabid).val());
    $('.dateto'+tabid).val($('#max'+tabid).val());
    $('#example'+tabid).DataTable().ajax.reload();
}
function exportWithAllData(dt, buttonName) {
    // Store current length
    var oldLength = dt.page.len();

    // Show all rows
    dt.page.len(-1).draw();

    // Delay to ensure table redraw finished
    setTimeout(function() {
        dt.button(buttonName).trigger(); // Run original export
        // Restore old length
        dt.page.len(oldLength).draw();
    }, 500);
}
function exportAllExcel(e, dt, button, config) {
    var self = this;
    var api = new $.fn.dataTable.Api(dt);
    var oldStart = api.page.info().start;

    // Clone original Excel action
    var excelAction = $.fn.dataTable.ext.buttons.excelHtml5.action;

    api.one('preXhr', function (e, s, data) {
        data.start = 0;
        data.length = 2147483647;

        api.one('preDraw', function (e, settings) {
            // Call original Excel action with proper context
            excelAction.call(self, e, api, button, config);

            // Restore
            settings._iDisplayStart = oldStart;
            api.one('preXhr', function (e, s, data) {
                data.start = oldStart;
            });
            setTimeout(api.ajax.reload, 0);
            return false;
        });
    });
    api.ajax.reload();
}

function exportAllPrint(e, dt, button, config) {
    var self = this;
    var api = new $.fn.dataTable.Api(dt);
    var oldStart = api.page.info().start;

    var printAction = $.fn.dataTable.ext.buttons.print.action;

    api.one('preXhr', function (e, s, data) {
        data.start = 0;
        data.length = 2147483647;

        api.one('preDraw', function (e, settings) {
            printAction.call(self, e, api, button, config);

            settings._iDisplayStart = oldStart;
            api.one('preXhr', function (e, s, data) {
                data.start = oldStart;
            });
            setTimeout(api.ajax.reload, 0);
            return false;
        });
    });
    api.ajax.reload();
}



function initTable(tabid){
   // alert(tabid)
    var heading=$('.tabtitle'+tabid).text();
    console.log(heading);
    $('#example'+tabid).DataTable({
        processing:true, serverSide:true,
        ajax:{ url:"<?php echo site_url('user/ajax_sale_purchases');?>", type:"POST", data:function(d){ d.bank_id = tabid;  d.from = $('#min'+tabid).val();
                d.to   = $('#max'+tabid).val();}},
   
        dom: 'Bfrtip',   // <== Add this
        lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
       pageLength: 100,
       buttons: [
        { extend: 'excelHtml5', text: '<span class="glyphicon glyphicon-ice-lolly-tasted"></span>', title: 'Transactions '+heading ,  action: exportAllExcel},
       
        { extend: 'print', text: '<span class="glyphicon glyphicon-print"></span>' , action: exportAllPrint}
    ],
        footerCallback:function(row,data,start,end,display){
            var api=this.api(), intVal=function(i){return typeof i==='string'?i.replace(/[\€\,]/g,'')*1:typeof i==='number'?i:0;};
            var debit=api.column(2,{page:'current'}).data().reduce((a,b)=>intVal(a)+intVal(b),0);
            var credit=api.column(3,{page:'current'}).data().reduce((a,b)=>intVal(a)+intVal(b),0);
            $('#debitttl'+tabid).html(debit.toFixed(2)+' €');
            $('#craditttl'+tabid).html(credit.toFixed(2)+' €');
            $('#balance'+tabid).html((credit-debit).toFixed(2)+' €');
        }
    });
}
   


function pagination(tabid){
    $('#tabbank').val(tabid);
    tabprofit('Total');
    if(!$.fn.DataTable.isDataTable('#example'+tabid)){
        initTable(tabid);
    }else{
        $('#example'+tabid).DataTable().ajax.reload();
    }
}
$('.tabfilterprofit').change(function(){
    $(".tabfiltervalue").text($(this).val());
    tabprofit($(this).val());
});
$('.p-btn.search').on('click', function(){
    $('.dash-tab .dataTables_filter').slideToggle('fast');
});
    
     function printDiv(divName) {
    var printButton = document.getElementById("printpagebutton");
//Set the print button visibility to 'hidden' 
printButton.style.visibility = 'hidden';
//Print the page content

var printContents = document.getElementById(divName).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
</script>
<style>
.table{width:61%;}
.dataTables_filter{width:20%;margin-left:-106px;}
.dashboardtable .col-sm-6{width:auto;}
</style>
</body></html>
