<?php    include_once('config/db.php');  include_once('config/check.php');  include_once('functions/acc_depreciation.php');


$partner =            htmlspecialchars (strtoupper($_POST['paybtn']));
//echo"$partner";
    // $startdate =            date("Y-m-d", strtotime($startdate));
    // $memo =       $_POST['memo']; 
    // $description  = $_POST['description']; 


  // if($startdate == '')  
  //   {   header("location:acc_rec");  }
  //     else  
      
  //   {     
    
               $stmt = $conn->prepare(" SELECT a.*,b.code FROM bppartner a JOIN acccurrency b ON a.currency=b.id  WHERE a.id=?");
                 $stmt->execute([$partner]);  $details = $stmt->fetch(); 

              
               $items = $conn->query(" 
               select * from ( 
                                SELECT a.bpartner,invoiceid, a.currency,a.memo,a.startdate,a.description, SUM(a.invamount) totalamount, SUM(a.amountpaid) totalpaid ,
                              SUM(a.invamount) - SUM(a.amountpaid) AS totalbalance ,
                                        
                              SUM(a.glamount) glamount, SUM(a.amountpaidgl) amountpaidgl ,
                              SUM(a.glamount) - SUM(a.amountpaidgl) AS totalbalancegl ,
                                          b.name bname ,b.id bid ,b.type,c.code ccode ,d.name dname
                              FROM
                              ( 
                                 
                              
                                SELECT a.id tableid,'REC_INV' as doctype , a.id invoiceid  ,a.date startdate ,a.enddate enddate ,a.bpartner bpartner ,a.currency currency, a.erate erate ,a.memo memo ,a.amount amount, a.glamount glamount ,a.amount invamount ,'' amountpaid,'' amountpaidgl, a.description description ,a.uid uid ,a.type type  FROM acctransaction a WHERE a.type= 10 or type=26
                                 UNION
                                 SELECT b.id tableid,'REC_PAYMENT' AS doctype , b.invoiceid invoiceid ,b.date startdate ,b.enddate enddate ,b.bpartner bpartner ,b.currency currency ,b.erate erate ,b.memo memo ,'' amount  ,'' glamount,'' invamount,b.amount amountpaid, b.glamount amountpaidgl, b.description description ,b.uid uid ,b.type type  FROM acctransaction b WHERE b.type= 11
                                UNION 
                                
                                SELECT a.id tableid,'REC_PAYMENT' AS DOCTYPE,b_invoiceid invoiceid,b.date startdate,b.enddate enddate,
                                b.bpartner bpartner,b.currency currency,b.erate erate,b.memo memo,'' amount,'' glamount,'' invamount,
                                a.total amountpaid,a.glamount amountpaidgl,b.description description,b.uid uid,b.type TYPE FROM 
                                acctransaction_item a
                                JOIN acctransaction b ON a.transactionid=b.id WHERE split=2 AND type=5
                           

                              )  a   JOIN bppartner b ON a.bpartner = b.id  
                                    JOIN bppartnertype d ON b.type=d.id
                                    JOIN acccurrency c ON a.currency=c.id 
                                    where bpartner='$partner'
                                    group by a.invoiceid 
                                    order by invoiceid asc
                     )z  where totalbalance >= 1
               
               ")->fetchAll();
                                                                                                  
    // }
 
  
 if (filter_has_var(INPUT_POST, "submitD")) 
      try{

         
        $billtype =      5 ;
        $startdate =         htmlspecialchars (strtoupper($_POST['startdate']));
         $startdate = date("Y-m-d", strtotime($startdate));
             

        $coa = 68 ;                             
        $paidto=                htmlspecialchars ( strtoupper($_POST['paidto']));
        $partner =         htmlspecialchars (strtoupper($_POST['partner']));   
        $memo   =            htmlspecialchars ($_POST['memo']);              
        $paymode   =            htmlspecialchars ($_POST['paymode']);              
        $description =       htmlspecialchars (strtoupper($_POST['description']));     
        $split =  2 ;      
        $currency =    $_POST['currency'] ;
        $erate =         getrate($conn,$currency);   ;
        $amount =         $_POST['g_subtotal']  ; 
        $glamount =  $amount * $erate ;

      
         $rid =              $_POST['rid'];
         $payable =              $_POST['payable'];
         $memos =              $_POST['memos'];
         $unit =             1 ;
        
  
       
   
        $number = count($_POST["rid"]); 
        if($number > 0)  
          {      
              $sql = 'INSERT INTO acctransaction(date,enddate,bpartner,split,memo,currency,erate,amount,glamount,dr,description,type,paymode,uid) VALUES (:startdate,:enddate,:partner,:split,:memo,:currency,:erate,:amount,:glamount,:dr,:description,:type,:paymode,:uid)';     
              $stmt = $conn->prepare($sql)->execute(['startdate'=>$startdate,'enddate'=>$startdate,'partner' =>$partner,'split'=>$split,
                                                    'memo' =>$memo,'currency' => $currency,'erate' => $erate ,'amount' => $amount,'glamount' =>$glamount ,'dr' =>$paidto,'description' => $description,'type'=>$billtype,'paymode'=>$paymode ,'uid'=>$uid  ]); 
              $lastid = $conn->lastInsertId(); 
          
              for($i=0; $i<$number; $i++)  
                {  
                  // debiting 
                  $sql = 'INSERT INTO acctransaction_item (transactionid,b_invoiceid,coa,name,unit,price,gross,total,glamount)
                  VALUES(:tid,:bid,:coa,:name,:unit,:price,:gross,:total,:glamount )'; 

                 $stmt = $conn->prepare($sql)->execute(['tid' => $lastid,'bid' => $rid[$i],'coa' =>$coa,'name' => $memos[$i],'unit' =>$unit,
                                  'price' => $payable[$i] ,'gross' => $payable[$i], 
                                   'total' => $payable[$i],'glamount' => $payable[$i] * $erate  ]);

                }                  
              
          } else{}
        
             
         header("location:acc_rec.php"); 
        } catch(Exception $e) { echo 'Message: ' .$e->getMessage();}


       
       



?>

<!DOCTYPE html>
<html>
<head>
<?php include_once('inc/link.php');   ?>  
<style>

  .highlight {
    
    border-color:red;
  }
  </style>

</head>
<body <?php include_once('inc/nav.php');  ?>>
<div class="wrapper">

  <!-- Main Header -->
    <header class="main-header">

    <!-- Logo -->
       <?php include_once('inc/brand.php');   ?>

    <!-- Header Navbar -->
    <?php include_once('inc/navbar.php');   ?>

  </header>
 
  <!-- Left side column. contains the logo and sidebar -->
    <aside class="main-sidebar">

    <!-- sidebar: style can be found in sidebar.less -->
     <?php include_once('inc/menu.php');   ?>
    <!-- /.sidebar -->
  </aside>

  <!-- Content Wrapper. Contains page content -->
  <div class="content-wrapper">

  <section class="content-header" style="padding-bottom:0px;">
    <p style="color:green; font-size:20px; font-weight:bold; " > <i class="fa fa-calculator" ></i> Receive bulk payments   </p>
         
        <ol class="breadcrumb">
          <li><a href="#"><i class="fa fa-dashboard"></i> </a></li>
          <li><a href="#"> </a></li>
         
        </ol>
      </section>


  <!-- Main content -->
  <section class="content container-fluid" style="padding-top:0px;">
    
      <div class="box box-default box-xs"   >
              <div class="box-body">
                  <div class="row">
             
                    <form class="form-horizontal "  action="" method="post"  >
                        <div class="row"> 
                                        <div class="col-md-12 "  > 
                                            <div class="" >  
                                                                                                                                                                                     
                                                <div class="col-md-2">
                                                      <label >   Payment Date   </label>
                                                      <input type="hidden" class="form-control " name="partner" autocomplete="off"    value="<?php  echo $details["id"]?>" required=""> 
                                                      <input type="text" class="form-control datepicker" name="startdate" autocomplete="off"    value="<?php  echo $startdate; ?>" required=""> 
                                                </div>
                                                     
                                                <div class="col-md-3">
                                                   <label>  Paid to  </label>
                                                      <select class="form-control js-example-basic-single"  required="" name="paidto" style="" >
                                                      <?php $stmt = $conn->prepare("SELECT * FROM coa where TYPE=2 AND cgroup =4      ");
                                                          $stmt->execute(); foreach ($stmt as $row) {?>
                                                              <option> </option>
                                                              <option value="<?php echo $row['id']; ?>"><?php
                                                                  echo $row['name']; ?></option> <?php } ?>
                                                  </select>                                   
                                                </div>
                                                
                                                <div class="col-md-3">
                                                   <label>  Amount paid   </label>
                                                   <input type="text" class="form-control" name="amountpaid" required=''   style="background-color:default;" value="<?php  echo "$memo" ?>"  autocomplete="off">
                                                </div>  
                                                <div class="col-md-2">
                                                   <label>  Assigned   </label>
                                                   <input type="text" class="form-control" name="assigned" required='' readonly=""  style="background-color:default;"   autocomplete="off">
                                                </div> 
                                                <div class="col-md-2">
                                                   <label>  Difference   </label>
                                                   <input type="text" class="form-control" name="diff" required='' readonly=""  style="background-color:default;" value="<?php  echo "$memo" ?>"  autocomplete="off">
                                                </div>   
                                                <div class="col-md-4">
                                                   <label>  Name   </label>
                                                   <input type="text" class="form-control" name="customer" required=''  readonly=""  style="background-color:default;"  value="<?php  echo $details["name"]?>"  autocomplete="off">
                                                </div>                                          
                                                <div class="col-md-1">
                                                   <label>  currency   </label>
                                                   <input type="hidden" class="form-control" name="currency" required=''  readonly=""  style="background-color:default;"  value="<?php  echo $details["currency"]?>"  autocomplete="off">
                                                   <input type="text" class="form-control" name="code" required=''  readonly=""  style="background-color:default;"  value="<?php  echo $details["code"]?>"  autocomplete="off">
                                                </div>                                          
                                                <div class="col-md-2">
                                                   <label>  Memo  </label>
                                                   <input type="text" class="form-control" name="memo" required=''   style="background-color:default;"   autocomplete="off">
                                                </div>                                          
                                        
                                                <div class="col-md-3">
                                                      <label >  Description   </label>
                                                      <input type="text" class="form-control  " autocomplete="off" name="description"   style="background-color:white;"   required=""> 
                                                </div>

                                                <div class="col-md-2">
                                                 <label>  Payments Mode   </label>                                       
                                                  <select class="form-control js-example-basic-single  "  required="" name="paymode" style="" >
                                                  <?php $stmt = $conn->prepare("SELECT * FROM acctranspaymode   ");
                                                      $stmt->execute(); foreach ($stmt as $row) {?>
                                                          <option> </option>
                                                          <option value="<?php echo $row['id']; ?>"><?php
                                                              echo $row['name']; ?></option> <?php } ?>
                                                  </select>      
                                                </div>
                                                
                                
                                        </div>                                
                                        <!---  QUOTE HEADER  --->                               
                                        <div class="col-xs-12">
                                            <div class="" style="margin-top:5px;">
                                                <table class="table  table-condesed table-bordered table-sm table-condensed item_table " id="item_table" >
                                                        <tr class="bg-primary" >
                                                            <th style="width:7%;">    Date </th>
                                                            <th style="width:15%;">   Memo </th>
                                                            <th style="width:14%;">   Description  </th>                                                    
                                                            <th style="width:7%;">   Rate </th>
                                                            <th style="width:12%;">   Invoice_amount    </th>
                                                            <th style="width:12%;">   Paid </th>
                                                            <th style="width:12%;">   Balance  </th>
                                                            <th style="width:12%;">   Assign  </th>
                                                            
                                                    
                                                        </tr>
                                                           <?php   $i = 0; foreach($items as $item )
                                                                 { extract($item); 
                                                                    $item= $item;
                                                                                                                               
                                                                   $i++;                                
                                                            ?>	
                                                                                       
                                                                <tr id="row'+i+'">                                                                  
                                                                  <td style="border:none;" ><input type="hidden" name="rid[]" readonly="true"   value="<?php echo $invoiceid; ?>" id="rid_'+i+'" class="form-control table-condesed rid" /> <input type="date" name="" readonly="true"   value="<?php echo $startdate; ?>" id="no_'+i+'" class="form-control table-condesed no" /></td>
                                                                  <td style="border:none;" ><input type="" name="memos[]" readonly="true"   value="<?php echo $memo; ?>" id="memo_'+i+'" class="form-control table-condesed memo" /> </td>
                                                                  <td style="border:none;" ><input type="" name="description[]" readonly="true"   value="<?php echo $description; ?>" id="desc_'+i+'" class="form-control table-condesed desc" /> </td>
                                                                  <td style="border:none;" > <input type="text" name="[]" readonly="true"   value="<?php echo  $ccode ; ?>" id="_'+i+'" class="form-control table-condesed " /> </td>
                                                                  <td style="border:none;" > <input type="text" name="[]" readonly="true"   value="<?php echo  number_format($totalamount, 2) ; ?>" id="_'+i+'" class="form-control table-condesed " /> <input type="hidden" name="facost[]" readonly="true"   value="<?php echo  $totalamount ; ?>" id="facost_'+i+'" class="form-control table-condesed facost" /></td>
                                                                  <td style="border:none;" > <input type="text" name="[]" readonly="true"   value="<?php echo  number_format($totalpaid, 2) ; ?>" id="_'+i+'" class="form-control table-condesed " /> <input type="hidden" name="facost[]" readonly="true"   value="<?php echo  $totalpaid ; ?>" id="facost_'+i+'" class="form-control table-condesed facost" /></td>
                                                                  <td style="border:none;" > <input type="text" name="[]" readonly="true"   value="<?php echo  number_format($totalbalance, 2) ; ?>" id="_'+i+'" class="form-control table-condesed " /> <input type="hidden" name="[]" readonly="true"   value="<?php echo  $totalbalance ; ?>" id="facost_'+i+'" class="form-control table-condesed  balance" /></td>
                                                                  <td style="border:none;" > <input type="text" name="payable[]" required="" autocomplete="off"  value="0" id="payable_'+i+'" class="form-control payable " /> </td>
                                                                  
                                                                      
                                                                </tr>
                                                            
                                                            <?php } ?>
                                                  </table>
                                                         
                                            </div>
                                        </div>
                                        <!---  QUOTE HEADER  ---> 
                                                                                             
                                                  
                                                  <div class="col-md-4">
                                                 
                                                  </div>
                                                  <div class="col-md-2">
                                                  </div>

                                                  <div class="col-md-6">
                                                                                                          
                                                     
                                                      <div class="col-md-6"> </div> 
                                                       <div class="col-md-6"> 
                                                        <input type="text"  value="" readonly="true" name="g_subtotal" class="form-control"  > 
                                                       </div>
                                                  </div>
                                                 
                                        <!-- </div>   -->
                                        
                                        
                                          <!-- submit button -->
                                        <div class="form-group " >
                                          <div class="col-sm-offset-4 col-xs-10 disabled" style="padding-top:2px;">                             
                                          <button type="submit" name="submitD" class="btn btn-success col-xs-4 postgl">
                                                <i class="fa fa-calculator "></i>  Receive payment  </button>
                                                </div>
                                    </div>
                            
                        </div>
                    </form>
                        
                    </div>
                </div>
            </div>
     
   </section>
</div>
  <!-- /.content-wrapper -->
  
  <!-- Main Footer -->
  <footer class="main-footer">
    <?php  include_once('inc/footer.php'); ?>
  </footer>
  
</div>
                         
<!-- ./wrapper -->

<!-- REQUIRED JS SCRIPTS -->
<?php include_once('inc/linkjs.php') ?>

</body>
</html>

<!-- dynamic rows start here -->
<script>
    
$(document).ready(function(){
   // var i=0; 

    $("#item_table").on('change', ".payable", function()
         {        
               calculateTotal ();
               var amount = $("input[name='amountpaid']").val();  
               var assigned = $("input[name='assigned']").val();

               var diff = amount - assigned ;
                 $("input[name='diff']").val(diff); 

            var paid =      $(this).closest('tr').find('.payable').val();            
          
            var balance =      $(this).closest('tr').find('.balance').val();

            var paid = (Math.round((paid * 1000)/10)/100).toFixed(2) ;
            var balance = (Math.round((balance * 1000)/10)/100).toFixed(2) ;
                   
         
            
            var overpayment = paid - balance;
            // alert(overpayment);
            

            if( overpayment > 0  ){         
                                $('.postgl').hide();
                                $(this).closest('tr').find('.payable').addClass('highlight');
              }
            else  if(diff!=0 ) 
                 {
                      $(this).closest('tr').find('.payable').removeClass('highlight');
                      $('.postgl').hide();               
                 }
             else{          
                         $(this).closest('tr').find('.payable').removeClass('highlight');                 
                          $('.postgl').show(); 
                  }

          }); 

  // on amount paid change 
          // $("input[name='amountpaid']") .change(function(){        
          //           calculateTotal ();
          //             var amount = $("input[name='amountpaid']").val();  
          //             var assigned = $("input[name='assigned']").val();

          //             var diff = amount - assigned ;
          //               $("input[name='diff']").val(diff); 


                    
          //           if(diff!=0 ) 
          //               {
                             
          //                     $('.postgl').hide();               
          //               }
          //           else{          
                                          
          //                         $('.postgl').show(); 
          //                 }
                              
                         
          //            });
// on amount paid change 
    
                                      
                        
                                    function calculateTotal () { $(".item_table").each(function () {  
                                                     var sum = 0; 
                                                      $("input[name='payable[]']").each(function () {
                                                      if (!isNaN(this.value) && this.value.length != 0) 
                                                             { sum += parseFloat(this.value);  }
                                                                       $("input[name='g_subtotal']").val(sum);
                                                                       $("input[name='assigned']").val(sum);
                                                                                                    });  
                                                                                      });
                                                             }
        
                   });
</script>
<!-- DYANAMIC ROWS LISTING HERE --->

<!-- DYNAMIC ROWS ENDS HERE --->