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

 $acledger = mysqli_query($conn,"SELECT tid,ac_name,acid,(COALESCE(CASE WHEN dr_acid = '$acid' THEN amount END,'')) debit,(COALESCE(CASE WHEN cr_acid = '$acid' THEN amount END,'')) credit,DATE_FORMAT(date, '%d/%m/%Y') date,details,ttype,invoice FROM transaction LEFT JOIN accounts ON (accounts.acid=(IF(dr_acid = '$acid', transaction.cr_acid, transaction.dr_acid))) WHERE transaction.coid = '$coid' AND transaction.active='1' AND (dr_acid = '$acid' || cr_acid = '$acid') AND date(date) BETWEEN '$fdate' AND '$edate' ORDER BY date(date),tid") 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.acid ='$acid' 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(219) .' '. language(212); ?></h3>
          <div class="card-tools">
            <button type="button" class="btn btn-tool" onclick="ExcelMe('#lgtable<?php echo $acid;?>')"  title="Download Excel">
              <i class="far fa-file-excel"></i>
            </button>
            <button type="button" onclick="BfpdfMe('#lgtable<?php echo $acid;?>');" class="btn btn-tool" title="Download Pdf"><i class="fas fa-download"></i></button>
            <button type="button" class="btn btn-tool" onclick="printMe('#acledger')" 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 cscroll" id="acledger" style="max-height: 450px;">
              <table id="lgtable<?php echo $acid;?>" class="ttable" cellpadding="0" cellspacing="0">
                 <thead>
                    <tr >
                       <th colspan="2" rowspan="3" class="text-center">
                        <?php if($co_logo != ""): ?>
                        <img id="img_data" class="profile-user-img img-fluid img-circle" style="width:80px;height:77px;" src="data:image/gif;base64,<?php echo $co_logo;?>" alt="User profile picture">
                        <?php else : ?>
                        <img id="img_data" class="profile-user-img img-fluid img-circle" style="width:80px;height:77px;" src="../../dist/img/no_img.jpg" alt="company profile">
                        <?php endif; ?>
                      </th>                    
                       <th colspan="3" rowspan="3">
                         <div style="padding-left:2px;">
                          <center>  <sss style="font-size:18px;font-weight: 600;"><?php echo $co_name;?></sss><br>
                           <sss><?php echo $co_address;?></sss>
                           <sss><?php echo $co_phone;?></sss> # 
                           <sss><?php echo $co_email;?></sss>
                            </center> <hr>
                           <sss> <?php echo language(244); ?>  :  <?php echo $inac['branch_name'];?></sss>
                           <sss> <?php echo $inac['branch_address'];?>  # <?php echo $inac['branch_number'];?>#<?php echo $inac['branch_code'];;?></sss> 
                         </div>
                       </th> 
                       <th colspan="4" class="text-center" style="font-size:13px;"><?php echo $ac_name;?></th>
                    </tr> 
                    <tr>                    
                       <th colspan="4" class="text-center" style="font-size:13px;"><?php echo language(294);?></th> 
                    </tr>
                    <tr>                    
                       <th colspan="4" class="text-center" style="font-size:13px;"><?php echo date('d/m/y', strtotime($fdate));?> <?php echo language(291);?> <?php echo date('d/m/y', strtotime($edate));?></th>
                    </tr>                                       
                    <tr class="sticky-top" style="background: hsl(0deg 0% 50% / 42%);">
                       <th class="text-center" style="width:3%;"> <?php echo language(15);?> </th>
                       <th class="text-center" style="width:9%;"><?php echo language(131);?> </th>
                       <th class="text-center" style="width:34%;"><?php echo language(295);?></th>
                       <th class="text-center" style="width:10%;"><?php echo language(207);?> </th>
                       <th class="text-center" style="width:21%;"><?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:8%;"><?php echo language(290);?></th>
                       <th class="text-center" style="width:8%;">#</th>
                    </tr>
                 </thead>
                 <tbody>
                    <tr>
                    <?php
                         $pr_dr='';
                         $pr_cr='';
                         $pr_arr = balance($acid,$edate,$fdate);
                         $pr_balance = ($pr_arr)?$pr_arr['pr_balance']:0;
                         if ($pr_balance >= 0) {
                           $pr_dr = $pr_balance;
                        } else {
                           $pr_cr = (- $pr_balance);
                        }
                    ?>
                       <td class="text-right" colspan="5" 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>
                       <td class="text-right" style="border-top:0;"></td>
                    </tr>
                 </tbody>
                 <tfoot> 
                    <tr class="sticky-bottom">
                       <td class="text-right" colspan="5"><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>
                       <td class="text-right"></td>
                    </tr>                                 
                    <tr class="sticky-bottom">
                       <th class="text-right" colspan="5"> <?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"colspan="2"></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 = '';
      $('#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);
      } else if(value.credit>0){
        balance -= Number(value.credit);
      }
              
            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>';

      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>' + value.details + ','+ ' By: '+ '<a href="#" onclick="vprofile('+value.acid+')">'+value.ac_name+'</a>'+'</td>';
      }
        data += '<td class="text-center btn-outline-dark" onclick="vprint(this)" type="'+value.ttype+'" tid="'+value.tid+'">' +
          vtype(value.ttype) + '</td>';
          
      <?php if(per('vou_delete')==1){ ?>
        data += '<td class="text-center" onclick="delinv(this)">' + value.invoice + '</td>';
      <?php } else { ?>
        data += '<td class="text-center">' + value.invoice + '</td>';
      <?php } ?>

        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>';
        
        if (value.ttype==='OPINS') {
            data += '<td class="text-center" data-toggle="dropdown" title="More Tools" aria-expanded="false"><i class="fa-solid fa-ellipsis-vertical"></i> <ul class="dropdown-menu" role="menu"><li><a class="dropdown-item" title="preview" preview="'+value.invoice+'"><i class="fa fa-check" aria-hidden="true"></i> Preview Vouchar</a></li><div class="dropdown-divider m-0"></div><li><a class="dropdown-item" title="Delete" delet="'+value.invoice+'"><i class="fas fa-trash"></i> Delete Vouchar</a></li></ul></td>';
        }else {
            data += '<td class="text-center text-danger" data-toggle="dropdown" title="More Tools" aria-expanded="false"><i class="fa-solid fa-ellipsis-vertical"></i> </td>';
        }

        data += '</tr>';
      });
      
      $('#lgtable<?php echo $acid;?> tbody').append(data);
      $('#lgtable<?php echo $acid;?> #sumdr').text(bden.format(sumdr));
      $('#lgtable<?php echo $acid;?> #sumcr').text(bden.format(sumcr));
      $('#lgtable<?php echo $acid;?> #balance').text(bden.format(balance));

        if (balance>0) {
          $('#lgtable<?php echo $acid;?> #drbalance').text(bden.format(balance));
          $('#lgtable<?php echo $acid;?> #crbalance').text('');
        } else if(balance<0){
          $('#lgtable<?php echo $acid;?> #crbalance').text(bden.format(- balance));
          $('#lgtable<?php echo $acid;?> #drbalance').text('');
        } else {
          $('#lgtable<?php echo $acid;?> #drbalance,#lgtable<?php echo $acid;?> #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?g_acid=<?php echo $acid?>'+'&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?g_acid=<?php echo $acid?>'+'&tid='+tid,'#mdview'); 
     } else if(ttp=='C') {
      $("#modal-lg").modal({backdrop: "static"});
      pagecall('../voucher/con_money_receipt.php?g_acid=<?php echo $acid?>'+'&tid='+tid,'#mdview');
     } else if(ttp=='OP') {
      $("#modal-lg").modal({backdrop: "static"});
      pagecall('../voucher/op_money_receipt.php?g_acid=<?php echo $acid?>'+'&tid='+tid,'#mdview');
     } else if(ttp=='EPUR'){
    <?php if ($printer_t=='P') { ?>
      $("#modal-sm").modal({backdrop: "static"});
      pagecall('../purchase/purchase_invoice_pos.php?g_acid=<?php echo $acid?>'+'&invoice='+invoice,'#smdview');
    <?php } elseif ($printer_t=='R') { ?>
      $("#modal-lg").modal({backdrop: "static"});
      pagecall('../purchase/purchase_invoice.php?g_acid=<?php echo $acid?>'+'&invoice='+invoice,'#mdview');
    <?php } ?>
     } else if(ttp=='ERSL'){
    <?php if ($printer_t=='P') { ?>
      $("#modal-sm").modal({backdrop: "static"});
      pagecall('../sales/sales_invoice_pos.php?g_acid=<?php echo $acid?>'+'&invoice='+invoice,'#smdview');
    <?php } elseif ($printer_t=='R') { ?>
      $("#modal-lg").modal({backdrop: "static"});
      pagecall('../sales/sales_invoice.php?g_acid=<?php echo $acid?>'+'&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?g_acid=<?php echo $acid?>'+'&invoice='+invoice,'#smdview');
    <?php } elseif ($printer_t=='R') { ?>
      $("#modal-lg").modal({backdrop: "static"});
      pagecall('../sales/c_sales_invoice.php?g_acid=<?php echo $acid?>'+'&invoice='+invoice,'#mdview');
    <?php } ?>
    } else if(ttp=='INSL'){
      $("#modal-lg").modal({backdrop: "static"});
      pagecall('../sales/ins_sales_invoice.php?g_acid=<?php echo $acid?>'+'&invoice='+invoice,'#mdview');   
     } else if(ttp=='EPRET'){
      $("#modal-lg").modal({backdrop: "static"});
      pagecall('../purchase_retrun/purchase_Ret_invoice.php?g_acid=<?php echo $acid?>'+'&invoice='+invoice,'#mdview');   
     }else if (ttp == 'ESRTN') {
      $("#modal-lg").modal({
        backdrop: "static"
      });
      pagecall('../sales_retrun/sales_return_invoice.php?g_acid=<?php echo $acid ?>' + '&invoice=' + invoice, '#mdview');
    }
  }
  

  function vprofile(acid){
    // $("#modal-xl").modal({backdrop: "static"});    
    pagecall('../accounts/ac_profile.php?acid='+acid,'#ac_view');   
  }    

   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')
     });
   }  

  function delinv(inv){   
      let invoice = $(inv).text();
      let ttp = $(inv).prev().attr('type');
      if (ttp=='EADJ' || ttp=='SOP' || ttp=='JUR' || ttp == 'INSR'){
        if (ttp=='EADJ' || ttp=='SOP' ){
            var path = "../itemadjust/invoice_delete.php";
          }
          
        if (ttp == 'INSR') {
           var path = "../voucher/vou_delete_db.php";
         }
        if (ttp=='JUR'){
            var path = "../voucher/vou_delete_db.php";
          }

      Swal.fire({
        title: 'Are you sure?',
        text: "You won't be able to revert this Invoice!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#3085d6',
        confirmButtonText: 'Yes, delete it!'
      }).then((result) => {
        if (result.isConfirmed) {
          Swal.fire({icon: 'success',title: 'Your Invoice is Successfully Delete',showConfirmButton: false,timer: 1500})
          $.post(path,{oinvoice:invoice},function(data){
             pagecall('../accounts/ac_profile.php?acid=<?php echo $acid;?>','#ac_view',0);
          });          
        }
      }) 
    }  
  }         
</script>



<script>
  $(document).ready(function() {

    $('[preview]').on('click', function(e){
      e.preventDefault();
      $("#modal-lg").modal({backdrop: "static"});
       pagecall('../print_setup/op_ins_preview.php?ins_invoice='+ $(this).attr("preview"),'#mdview');
    });

    $('[delet]').on('click', function(e){
    let opins_invoice = $(this).attr('delet');
    e.preventDefault(); 
      Swal.fire({
        title: 'Are you sure?',
        text: "You won't be able to revert this Invoice!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#3085d6',
        confirmButtonText: 'Yes, delete it!'
      }).then((result) => {
        if (result.isConfirmed) {
          Swal.fire({icon: 'success',title: 'Your Invoice is Successfully Delete',showConfirmButton: false,timer: 1500})
          $.post('../voucher/vou_delete_db.php',{opins_invoice:opins_invoice});   
          $(this).closest('tr').fadeOut('slow');         
        }
      })
    });
  })
</script>
