<?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));
    $csdata = [];
    $bkdata = [];
  while($ldg= mysqli_fetch_assoc($acledger)){
    if ($ldg['g_type']=='mcash') {
      $csdata[]=$ldg;
    } else {
      $bkdata[]=$ldg;
    }  
  }


 $prbalq = mysqli_query($conn,"SELECT g.g_type,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' GROUP BY g.g_type HAVING balance <> 0") or die(mysqli_error($conn));
   $pr_balance = 0;
   while($prbal= mysqli_fetch_assoc($prbalq)){

    if ($prbal['g_type']=='mcash') {
      $cspr_balance  = $prbal['balance'];
    } else {
      $bkpr_balance  = $prbal['balance'];
    }
    $pr_balance += $prbal['balance'];
  } 

   $drpr_balance='';
   $crpr_balance='';
   $cspr_dr='';
   $cspr_cr='';
   $bkpr_dr='';
   $bkpr_cr='';

    if ($pr_balance >= 0) {
       $drpr_balance = $pr_balance;
    } else {
       $crpr_balance = (- $pr_balance);
    }

    if ($cspr_balance >= 0) {
       $cspr_dr = $cspr_balance;
    } else {
       $cspr_cr = (- $cspr_balance);
    }

    if ($bkpr_balance >= 0) {
       $bkpr_dr = $bkpr_balance;
    } else {
       $bkpr_cr = (- $bkpr_balance);
    }
  
$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 id="cstbody">
                    <tr style="background:#ffdec3;">
                       <td class="text-right" colspan="8"><dt>(Cash + Bank) <?php echo language(129);?> </dt></td>
                       <td class="text-right"><dt><?php if ($drpr_balance>0) {echo money($drpr_balance,true);}?></dt></td>
                       <td class="text-right"><dt><?php if ($crpr_balance>0) {echo money($crpr_balance,true);}?></dt></td>
                       <td class="text-right"><dt></dt></td>
                    </tr>
                    <tr style="background:#d9ebff;">
                      <td class="text-left" colspan="11"><dt> Cash </dt></td>
                    </tr>
                    <tr>
                       <td class="text-right" colspan="8"><dt> <?php echo language(129);?> </dt></td>
                       <td class="text-right"><dt><?php if ($cspr_dr>0) {echo money($cspr_dr,true);}?></dt></td>
                       <td class="text-right"><dt><?php if ($cspr_cr>0) {echo money($cspr_cr,true);}?></dt></td>
                       <td class="text-right"><dt><?php echo money($cspr_balance,true);?></dt></td>
                    </tr>
                 </tbody>
                 <tbody id="bktbody">
                    <tr style="background:#d9ebff;">
                      <td class="text-left" colspan="11"><dt> Bank </dt></td>
                    </tr>
                    <tr>
                       <td class="text-right" colspan="8"><dt> <?php echo language(129);?> </dt></td>
                       <td class="text-right"><dt><?php if ($bkpr_dr>0) {echo money($bkpr_dr,true);}?></dt></td>
                       <td class="text-right"><dt><?php if ($bkpr_cr>0) {echo money($bkpr_cr,true);}?></dt></td>
                       <td class="text-right"><dt><?php echo money($bkpr_balance,true);?></dt></td>
                    </tr>
                 </tbody>                 
                 <tfoot>                                 
                    <tr style="background:#ffdec3;">
                       <th class="text-right" colspan="8">(Cash + Bank) <?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 balance = '';
      var csdata = '';
      var csi = 1;
      var csbalance = Number(<?php echo $cspr_balance;?>);
      var cssumdr = 0;
      var cssumcr = 0;
      var cstype = '';
      var csmethod = '';
      var csacname = '';

      $.each(<?php echo json_encode($csdata)?>, function (key, value) {

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

        csbalance += Number(value.debit);

        csdebitor = value.ac_name;
        cscreditor = value.bacname;

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

        csdebitor = value.bacname;
        cscreditor = value.ac_name;   

      }

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

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

        csdata += '<tr>';
        csdata += '<td class="text-center">' + csi++ + '</td>';

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

      if (value.ac_name===null) {
        csdata += '<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 {
        csdata += '<td>'+csdebitor+'</a>'+'</td>';
        csdata += '<td>'+cscreditor+'</a>'+'</td>';
        csdata += '<td>'+ value.details +'</td>';
      }
        csdata += '<td class="text-center btn-outline-dark" onclick="vprint(this)" type="'+value.ttype+'" tid="'+value.tid+'">' + vtype(value.ttype) + '</td>';

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

        csdata += '<td class="text-right">' + csdebitt + '</td>';

        csdata += '<td class="text-right">' + cscreditt + '</td>';

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

        csdata += '</tr>';

      });
     var cstdata = ''; 
         cstdata += '<tr>';
         cstdata += '<td class="text-right" colspan="8"><dt><?php echo language(292);?></dt></td>';
         cstdata += '<td class="text-right"><dt>'+ bden.format(cssumdr) +'</dt></td>';
         cstdata += '<td class="text-right"><dt>'+ bden.format(cssumcr) +'</dt></td>';
         cstdata += '<td class="text-right"><dt>'+ bden.format(csbalance) +'</dt></td>';
         cstdata += '</tr>';


      $('#dbtable #cstbody').append(csdata);
      $('#dbtable #cstbody').append(cstdata);

      var bkdata = '';
      var bki = 1;
      var bkbalance = Number(<?php echo $bkpr_balance;?>);
      var bksumdr = 0;
      var bksumcr = 0;
      var bktype = '';
      var bkmethod = '';
      var bkacname = '';

      $.each(<?php echo json_encode($bkdata)?>, function (key, value) {

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

        bkbalance += Number(value.debit);

        bkdebitor = value.ac_name;
        bkcreditor = value.bacname;

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

        bkdebitor = value.bacname;
        bkcreditor = value.ac_name;   

      }

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

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

        bkdata += '<tr>';
        bkdata += '<td class="text-center">' + bki++ + '</td>';

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

      if (value.ac_name===null) {
        bkdata += '<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 {
        bkdata += '<td>'+bkdebitor+'</a>'+'</td>';
        bkdata += '<td>'+bkcreditor+'</a>'+'</td>';
        bkdata += '<td>'+ value.details +'</td>';
      }
        bkdata += '<td class="text-center btn-outline-dark" onclick="vprint(this)" type="'+value.ttype+'" tid="'+value.tid+'">' + vtype(value.ttype) + '</td>';

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

        bkdata += '<td class="text-right">' + bkdebitt + '</td>';

        bkdata += '<td class="text-right">' + bkcreditt + '</td>';

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

        bkdata += '</tr>';

      });
     var bktdata = ''; 
         bktdata += '<tr>';
         bktdata += '<td class="text-right" colspan="8"><dt><?php echo language(292);?></dt></td>';
         bktdata += '<td class="text-right"><dt>'+ bden.format(bksumdr) +'</dt></td>';
         bktdata += '<td class="text-right"><dt>'+ bden.format(bksumcr) +'</dt></td>';
         bktdata += '<td class="text-right"><dt>'+ bden.format(bkbalance) +'</dt></td>';
         bktdata += '</tr>';


      $('#dbtable #bktbody').append(bkdata);
      $('#dbtable #bktbody').append(bktdata);

        balance = Number(csbalance+bkbalance);

        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>
