<?php require_once('../auth/auth.php');require_once('../auth/acid_balance.php');require_once('../auth/function.php');?>
<?php
 $gbid   = $_GET['bid'];
 $gbrid  = $_GET['brid'];
 $fdate  = $_GET['fdate'];
 $edate  = $_GET['edate'];
 $acid =1;

 $acledger = mysqli_query($conn,"SELECT t.tid,a.ac_name,bc.ac_name bacname,a.acid,g.g_type,(COALESCE(CASE WHEN t.dr_acid = a.acid THEN amount END,'')) debit,(COALESCE(CASE WHEN t.cr_acid = a.acid THEN amount END,'')) credit,DATE_FORMAT(t.date, '%d/%m/%Y') date,t.details,t.ttype,t.invoice FROM transaction t LEFT JOIN accounts a ON (t.dr_acid = a.acid || t.cr_acid = a.acid) LEFT JOIN accounts bc ON (bc.acid = IF(t.dr_acid = a.acid,t.cr_acid,t.dr_acid)) LEFT JOIN ac_sub_g_category g ON (a.gcatid = g.ac_g_catid ) WHERE t.coid = '$coid' AND t.active='1' AND (g.g_type = 'mcash' || g.g_type = 'bank') AND date(date) BETWEEN '$fdate' AND '$edate' ORDER BY date(date),t.tid,g.ac_g_catid") or die(mysqli_error($conn));
    $data = [];
  while($ldg= mysqli_fetch_assoc($acledger)){
    $data[]=$ldg;
  }
$inacc= mysqli_query($conn,"SELECT co_name,owner_name,co_phone,co_email,co_address,co_logo,a.ac_name,br.branch_name,br.branch_address,br.branch_code,br.branch_number FROM accounts a 
  LEFT JOIN company c ON(a.coid=c.coid)
  LEFT JOIN branch br ON(br.brid=a.brid) 
  WHERE a.coid='$coid' AND a.bid ='$gbid' AND a.brid ='$gbrid' LIMIT 1") or die(mysqli_error($conn));
$inac= mysqli_fetch_assoc($inacc);

$ac_name        = $inac['ac_name'];

$co_name        = $inac['co_name'];
$owner_name     = $inac['owner_name'];
$co_address     = $inac['co_address'];
$co_phone       = $inac['co_phone'];
$co_email       = $inac['co_email'];
$co_logo        = $inac['co_logo']; 
?>

<section class="content">
 <div class="container-fluid">
  <div class="row">
    <div class="col-md-12">
      <div class="card card-primary card-outline direct-chat direct-chat-primary shadow-none" style="border-left:1px solid #969c9d;border-right:1px solid #969c9d;border-bottom:1px solid #969c9d;">
        <div class="card-header" style="padding: 3px 8px;">
          <h3 class="card-title">  <?php echo language(27); ?></h3>
          <div class="card-tools">
            <button type="button" class="btn btn-tool" onclick="ExcelMe('#dbtable')"  title="Download Excel">
              <i class="far fa-file-excel"></i>
            </button>
            <button type="button" onclick="BfpdfMe('#dbtable');" class="btn btn-tool" title="Download Pdf"><i class="fas fa-download"></i></button>
            <button type="button" class="btn btn-tool" onclick="printMe('#dbledger')" title="Print Now"><i class="fas fa-print"></i></button>
            <button type="button" class="btn btn-tool" data-card-widget="remove" data-dismiss="modal">
              <i class="fas fa-times"></i>
            </button>
          </div>
        </div>      
            <div class="card-body p-1 table-responsive" id="dbledger">
              <table id="dbtable" class="ttable" cellpadding="0" cellspacing="0">
                 <thead>

                    <tr>                    
                       <th rowspan="3" colspan="8">
                        <div style="width:12%;float:left;">
                            <?php if($co_logo != ""): ?>
                                <img class="profile-user-img img-fluid img-circle" src="data:image/gif;base64,<?php echo $co_logo;?>" style="width:80px;height:77px;">
                            <?php else : ?>
                                <img class="profile-user-img img-fluid img-circle  " src="../../dist/img/a.png" style="width:80px;height:77px;">
                        </div>
                            <?php endif; ?>
                         <div style="padding-left:2px;float:left;">
                           <sss style="font-size:18px;font-weight: 600;"><?php echo $co_name;?></sss><br>
                           <sss><?php echo $owner_name;?></sss><br>
                           <sss><?php echo $co_address;?></sss><br>
                           <sss><?php echo $co_phone;?></sss> # 
                           <sss><?php echo $co_email;?></sss>
                         </div>
                       </th> 
                       <th colspan="3" class="text-center" style="font-size:13px;">All Branch</th>
                    </tr> 
                    <tr>                    
                       <th colspan="3" class="text-center" style="font-size:13px;">Day Book</th> 
                    </tr>
                    <tr>                    
                       <th colspan="3" class="text-center" style="font-size:13px;"><?php echo date('d/m/y', strtotime($fdate));?> To <?php echo date('d/m/y', strtotime($edate));?> 
                       </th>
                    </tr>                                       
                    <tr style="background: hsl(0deg 0% 50% / 42%);">
                       <th class="text-center" style="width:2%;"> <?php echo language(15);?> </th>
                       <th class="text-center" style="width:7%;"><?php echo language(131);?> </th>
                       <th class="text-center" style="width:5%;">Method</th>
                       <th class="text-center" style="width:15%;">Debitor</th>
                       <th class="text-center" style="width:15%;">Creditor</th>
                       <th class="text-center" style="width:13%;"><?php echo language(295);?></th>
                       <th class="text-center" style="width:5%;"><?php echo language(207);?> </th>
                       <th class="text-center" style="width:12%;"><?php echo language(289);?></th>
                       <th class="text-center" style="width:8%;"><?php echo language(217);?></th>
                       <th class="text-center" style="width:8%;"><?php echo language(218);?></th>
                       <th class="text-center" style="width:10%;"><?php echo language(290);?></th>
                    </tr>
                 </thead>
                 <tbody>
                    <tr>
                    <?php

                         $prbalq = mysqli_query($conn,"SELECT SUM(COALESCE(CASE WHEN t.dr_gcatid = g.ac_g_catid THEN amount END,0))-SUM(COALESCE(CASE WHEN t.cr_gcatid = g.ac_g_catid THEN amount END,0)) balance FROM transaction t LEFT JOIN ac_sub_g_category g ON (t.dr_gcatid=g.ac_g_catid || t.cr_gcatid=g.ac_g_catid) WHERE t.coid='$coid' AND t.bid='$gbid' AND t.brid='$gbrid' AND t.active=1 AND (g.g_type = 'mcash' || g.g_type = 'bank') AND date(date) < '$fdate' HAVING balance <> 0") or die(mysqli_error($conn));
                         $prbal= mysqli_fetch_assoc($prbalq);
                         $pr_balance  = $prbal['balance'];
                         $pr_dr='';
                         $pr_cr='';
                         if ($pr_balance >= 0) {
                           $pr_dr = $pr_balance;
                        } else {
                           $pr_cr = (- $pr_balance);
                        }
                    ?>
                       <td class="text-right" colspan="8" style="border-top:0;"><dt> <?php echo language(129);?> </dt></td>
                       <td class="text-right" style="border-top:0;"><dt><?php if ($pr_dr>0) {echo money($pr_dr,true);}?></dt></td>
                       <td class="text-right" style="border-top:0;"><dt><?php if ($pr_cr>0) {echo money($pr_cr,true);}?></dt></td>
                       <td class="text-right" style="border-top:0;"><dt><?php echo money($pr_balance,true);?></dt></td>
                    </tr>
                 </tbody>
                 <tfoot> 
                    <tr>
                       <td class="text-right" colspan="8"><dt><?php echo language(292);?></dt></td>
                       <td class="text-right"><dt id="sumdr"></dt></td>
                       <td class="text-right"><dt id="sumcr"></dt></td>
                       <td class="text-right"><dt id="balance"></dt></td>
                    </tr>                                 
                    <tr>
                       <th class="text-right" colspan="8"> <?php echo language(293);?></th>
                       <th class="text-right"><dt id="drbalance"></dt></th>
                       <th class="text-right"><dt id="crbalance"></dt></th>
                       <th class="text-right"></th>
                    </tr>
                 </tfoot>
              </table>
            </div>
           </div>
        </div>

   </div>
  </div>
</section>
<script id="pscript">
  $(document).ready(function () {
      var data = '';
      var i = 1;
      var balance = Number(<?php echo $pr_balance; ?>);
      var sumdr = 0;
      var sumcr = 0;
      var type = '';
      var method = '';
      var acname = '';
      $('#sumdr').text(bden.format(sumdr));
      $('#sumcr').text(bden.format(sumcr));
        if (balance>0) {
            $('#drbalance').text(bden.format(balance));
          } else if(balance<0){
            $('#crbalance').text(bden.format(- balance));
          }

            // console.log(Object.keys(<?php echo json_encode($data)?>).length === 0);
      $.each(<?php echo json_encode($data)?>, function (key, value) {

      if (Number(value.debit)>0) {

        balance += Number(value.debit);

        debitor = value.ac_name;
        creditor = value.bacname;

      } else if(value.credit>0){
     
        balance -= Number(value.credit);

        debitor = value.bacname;
        creditor = value.ac_name;   

      }

      if (value.g_type=='mcash') {
        method = 'Cash';
      } else if(value.g_type=='bank'){
        method = 'Bank';
      }
              
            sumdr += (Number(value.debit)>0)?Number(value.debit):0;
            sumcr += (Number(value.credit)>0)?Number(value.credit):0;

      var debitt = (value.debit==''|| value.debit==0)?'':bden.format(Number(value.debit));
      var creditt = (value.credit==''|| value.credit==0)?'':bden.format(Number(value.credit));       

        data += '<tr>';
        data += '<td class="text-center">' + i++ + '</td>';

        data += '<td class="text-center">' + value.date + '</td>';
        data += '<td class="text-center">' + method + '</td>';

      if (value.ac_name===null) {
        data += '<td><div class="btn-outline-dark" onclick="dtls(this)" data-toggle="collapse" href="#id'+value.invoice+'" invoice="'+value.invoice+'">' + value.details + ','+ ' Multiple accounts '+'<i class="fas fa-caret-left float-right"></i></div><div id="id'+value.invoice+'" class="collapse px-2"></div></td>';          
      } else {
        data += '<td>'+debitor+'</a>'+'</td>';
        data += '<td>'+creditor+'</a>'+'</td>';
        data += '<td>'+ value.details +'</td>';
      }
        data += '<td class="text-center btn-outline-dark" onclick="vprint(this)" type="'+value.ttype+'" tid="'+value.tid+'">' + vtype(value.ttype) + '</td>';

        data += '<td class="text-center">' + value.invoice + '</td>';

        data += '<td class="text-right">' + debitt + '</td>';

        data += '<td class="text-right">' + creditt + '</td>';

        data += '<td class="text-right"><b>' + bden.format(balance) + '</b></td>';

        data += '</tr>';
      });
      
      $('#dbtable tbody').append(data);
      $('#dbtable #sumdr').text(bden.format(sumdr));
      $('#dbtable #sumcr').text(bden.format(sumcr));
      $('#dbtable #balance').text(bden.format(balance));

        if (balance>0) {
          $('#dbtable #drbalance').text(bden.format(balance));
          $('#dbtable #crbalance').text('');
        } else if(balance<0){
          $('#dbtable #crbalance').text(bden.format(- balance));
          $('#dbtable #drbalance').text('');
        } else {
          $('#dbtable #drbalance,#dbtable #crbalance').text('');
        }

      $('#pscript').remove();
        toastr.success(Showing, yourdata);
  });
</script>

<script>
  function vprint(tdd){
     let ttp = $(tdd).attr("type");
     let tid = $(tdd).attr("tid");
     let invoice = $(tdd).next().text();
     if (ttp=='R') {
      $("#modal-lg").modal({backdrop: "static"});
      // pagecall('../print_setup/normal_recevied_preview.php?n_re_invoice='+invoice,'#mdview');  
      pagecall('../voucher/re_money_receipt.php?tid='+tid,'#mdview');
     } else if(ttp=='INSR') {
      $("#modal-lg").modal({backdrop: "static"});
      pagecall('../print_setup/ri_ins_preview.php?tid='+tid,'#mdview');
     }else if(ttp=='P') {
      $("#modal-lg").modal({backdrop: "static"});
      pagecall('../voucher/pay_money_receipt.php?tid='+tid,'#mdview'); 
     } else if(ttp=='C') {
      $("#modal-lg").modal({backdrop: "static"});
      pagecall('../voucher/con_money_receipt.php?tid='+tid,'#mdview');
     } else if(ttp=='OP') {
      $("#modal-lg").modal({backdrop: "static"});
      pagecall('../voucher/op_money_receipt.php?tid='+tid,'#mdview');
     } else if(ttp=='EPUR'){
    <?php if ($printer_t=='P') { ?>
      $("#modal-sm").modal({backdrop: "static"});
      pagecall('../purchase/purchase_invoice_pos.php?invoice='+invoice,'#smdview');
    <?php } elseif ($printer_t=='R') { ?>
      $("#modal-lg").modal({backdrop: "static"});
      pagecall('../purchase/purchase_invoice.php?invoice='+invoice,'#mdview');
    <?php } ?>
     } else if(ttp=='ERSL'){
    <?php if ($printer_t=='P') { ?>
      $("#modal-sm").modal({backdrop: "static"});
      pagecall('../sales/sales_invoice_pos.php?invoice='+invoice,'#smdview');
    <?php } elseif ($printer_t=='R') { ?>
      $("#modal-lg").modal({backdrop: "static"});
      pagecall('../sales/sales_invoice.php?invoice='+invoice,'#mdview');
    <?php } ?>
     } else if(ttp=='ECSL'){
    <?php if ($printer_t=='P') { ?>
      $("#modal-sm").modal({backdrop: "static"});
      pagecall('../sales/c_sales_invoice_pos.php?invoice='+invoice,'#smdview');
    <?php } elseif ($printer_t=='R') { ?>
      $("#modal-lg").modal({backdrop: "static"});
      pagecall('../sales/c_sales_invoice.php?invoice='+invoice,'#mdview');
    <?php } ?>
    } else if(ttp=='INSL'){
      $("#modal-lg").modal({backdrop: "static"});
      pagecall('../sales/ins_sales_invoice.php?invoice='+invoice,'#mdview');   
     } else if(ttp=='EPRET'){
      $("#modal-lg").modal({backdrop: "static"});
      pagecall('../purchase_retrun/purchase_Ret_invoice.php?invoice='+invoice,'#mdview');   
     }else if (ttp == 'ESRTN') {
      $("#modal-lg").modal({
        backdrop: "static"
      });
      pagecall('../sales_retrun/sales_return_invoice.php?invoice=' + invoice, '#mdview');
    }
  }
  


   function dtls(sid) {
    let invoice = $(sid).attr('invoice');
       $(".preloader").css('display','flex');
       $('#id'+invoice).load("../accounts/jur_view.php",
       ({
          invoice: invoice,
          acid:'<?php echo $acid;?>'
      }),
      function() {
       $('.preloader').hide(); 
       $(sid).removeAttr("onclick");
       // $('#id'+gcatid).collapse('toggle')
     });
   }  
        
</script>
