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


 if (filter_has_var(INPUT_POST, "submit")) 
  try{  
        
        $startdate =         htmlspecialchars (strtoupper($_POST['startdate']));
         $date =         date("Y-m-d", strtotime($startdate));      
         $currency =           htmlspecialchars (strtoupper($_POST['currency']));
         $memo   =            htmlspecialchars ( $_POST['memo']);   
         $branch   =            htmlspecialchars ( $_POST['branch']);   
       
         $from   =             htmlspecialchars ( $_POST['from']);   
         //$warehouse   =         htmlspecialchars ( $_POST['warehouse']);   

         $transtype=4;
         $transaction=1;
         $transmode=  1;

         $amount   =         htmlspecialchars ( $_POST['g_total']);   
         $erate = getrate($conn,$currency) ;
         $alltotal   =   $amount *  $erate ; //      htmlspecialchars ( $_POST['warehouse']);   
         
         
         $item =                 $_POST['item'];
         $unit =                 $_POST['unit'];
         $price =                $_POST['price'];
         $total =                $_POST['payable'];
    
         $number = count($_POST["item"]); 

         $sql1 = 'INSERT INTO acctransactions(date,memo,transtype,transaction,transmode,transuid) VALUES (:date,:memo,:transtype,:transaction,:transmode,:transuid)';     
         $stmt = $conn->prepare($sql1)->execute(['date'=>$date,'memo'=>$memo,'transtype' =>$transtype,'transaction'=>$transaction,'transmode' =>$transmode,'transuid'=>$uid  ]); 
         $lastid = $conn->lastInsertId(); 

        if($number > 0)  
          {  
            for($i=0; $i<$number; $i++)  
            {    
              $sql = 'INSERT INTO acctransactionsdetails(transid,branch,warehouse,currency,erate,partner,coa,itemunit,itemunittotal,itemprice,itemtotal,total,transmove,transclass)
                                    VALUES (:transid,:branch,:warehouse,:currency,:erate,:partner,:coa,:itemunit,:itemunittotal,:itemprice,:itemtotal,:total,:tmove,:tclass)'; 
              $stmt = $conn->prepare($sql)->execute(['transid' =>$lastid,'branch'=>$branch,'warehouse'=>0,'currency'=>$currency,'erate'=>$erate,
                                                      'partner' =>$item[$i],'coa' =>3,'itemunit' =>0,'itemunittotal' =>0,
                                                      'itemprice'=>$price[$i],'itemtotal'=>$total[$i], 'total'=>$total[$i] * $erate,'tmove'=>1,'tclass'=>1   ]);
            }

                       
          } else{}
            
          $sql = 'INSERT INTO acctransactionsdetails(transid,branch,partner,currency,erate,coa,itemtotal,total,transmove,transclass ) 
          VALUES(:transid,:branch,:partner,:currency,:erate,:coa,:itemtotal,:total,:tmove,:tclass )';

  // subtotal,vat,total

         $conn->prepare($sql)->execute(['transid'=>$lastid,'branch'=>$branch,'partner'=>0,'currency'=>$currency,'erate'=>$erate,'coa'=>$from,'itemtotal'=>$amount,'total'=>$alltotal* $erate , 'tmove' =>5,'tclass'=>2  ]);


        // Audit trail 
        audittrail($conn,$lastid,$transtype,$transaction,$transmode,$uid);

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

<!DOCTYPE html>
<html>
<head>
<?php include_once('../inc/slink.php');   ?>  
</head>
<body <?php include_once('../inc/snav.php');  ?>
<div class="wrapper">

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

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

    <!-- Header Navbar -->
    <?php include_once('../inc/snavbar.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/smenu.php');   ?>
    <!-- /.sidebar -->
  </aside>

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

  <section class="content-header" style="padding-bottom:0px;">
    <div class="row">
      <div class="">
         <div class="col-md-4">
             <p class="listheader" > <i class="fa fa-plus-circle" ></i>OPENING PAYABLES  </p>     
         </div>
         <div class="col-md-4"> <span id="currency">  </span>  </div>
         <div class="col-md-4">
                     <a  href="openingbalance" class="listbtn btn-primary btn-sm pull-right  " > <i class="fa fa-bars"></i> VIEW ALL BALANCES  </a>
          
         </div>
      </div>
   
    </div>   
  </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="col-md-2 ">
                                                    <label > Date  </label>
                                                    <input type="text" class="form-control datepicker " autocomplete="off" name="startdate">    
                                                </div>                                                                                
                                                                                                
                                             
                                                <div class="col-sm-2">  
                                                        <label> Currency </label>  
                                                        <select class="form-control js-example-basic-single"   name="currency" style="width:100%" >
                                                            <?php $stmt = $conn->prepare("SELECT a.* FROM acccurrency a WHERE a.default=1 ");
                                                            $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-4  ">                                                      
                                                      <label> Credit Chart of Account  </label>
                                                      <select class="form-control js-example-basic-single"   name="from" required="" style="width:100%" >
                                                            <?php $stmt = $conn->prepare("SELECT * FROM coa where type=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-4">
                                                        <label> Total Opening balance </label>
                                                        <input type="text"    name="g_total"  id="quotepay"class="form-control totalsum"   readonly="true"  >
                                                      </div>
                                                      
                                                <div class="col-sm-3">  
                                                        <label> Branch </label>  
                                                        <select class="form-control js-example-basic-single"   name="branch" required="" style="width:100%" >
                                                            <?php $stmt = $conn->prepare("SELECT * FROM admbranch where type=1   ");
                                                            $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-sm-3">  
                                                        <label> Location stored </label>  
                                                        <select class="form-control js-example-basic-single"   name="location" style="width:100%" >
                                                            <?php $stmt = $conn->prepare("SELECT * FROM admbranch   ");
                                                            $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-9">
                                                       <label>  Memo Reference   </label>
                                                        <input type="text" class="form-control" name="memo" required='' autocomplete="off">
                                                </div> 
                                             
                                              <!---  QUOTE PRODUCTS AND DETAILS   --->
                                                  <!---  QUOTE HEADER  --->                               
                                                
                                                        <div class="col-xs-12" style="margin-top:2px;">
                                                            <table class="table table-bordered table-condesed table-stripped table-sm table-condensed bg-default  item_table " id="item_table" >
                                                                      <tr class="">
                                                                      <th style="width:20%;">   Supplier  </th>
                                                                      <!-- <th style="width:18%;">   Details   </th> -->
                                                                      <!-- <th style="width:10%;">   Uom  </th> -->
                                                                      <th style="width:20%;">   Unit  </th>
                                                                      <!-- <th style="width:12.5%;">   Buying Price  (<span id="bcode" style="color:white; font-size:16px; "></span> )  </th> -->
                                                                      <th style="width:15%;">  Amount    </th>
                                                                      <!-- <th style="width:12.5%;">   Tax obligation </th> -->
                                                                      <th style="width:20%;">  Total Amount </th>
                                                                      <th style="width:10%;" >      
                                                                          <button  type="button" class="btn btn-default btn-xs btn-block add" name="add">  <i class=" fa fa-plus-circle fa-sm"></i> Add </button>
                                                                      </th>
                                                                    </tr>
                                                              </table>
                                                        </div>
                                                    
                                                    <!---  QUOTE HEADER  --->                                                      
                                          </div> 

                                          <div class="col-sm-12  "  >   
                                                                                          
                                          </div>  
                                        
                                        
                                          <!-- submit button -->
                                        <div class="form-group " >
                                          <div class="col-sm-offset-4 col-xs-10" style="padding-top:10px;">                             
                                            <button type="submit"name="submit" class=" subbtn btn btn-primary col-xs-4">
                                                <i class="fa fa-plus-circle "></i> Add Opening Payables  </button>
                                                </div>
                                    </div>
                            
                        
                    </form>
                        
                    
                </div>
            </div>
      
   </section>
</div>
  <!-- /.content-wrapper -->
  
  <!-- Main Footer -->
  <footer class="main-footer">
    <?php  include_once('../inc/sfooter.php'); ?>
  </footer>
  
</div>
                         
<!-- ./wrapper -->

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

</body>
</html>

<!-- dynamic rows start here -->
<script>
    
$(document).ready(function(){

    var i=0; 
 
 $(document).on('click', '.add', function(){
    i++;  
  var html = '';
   html += '<tr id="row'+i+'">';
   html += '<td><select name="item[]" id="item_'+i+'" required="" class="form-control item js-example-basic-single "><option value="">Select </option><?php echo supplier($conn); ?></select><input type="hidden" name="coa[]" id="coa_'+i+'"  class="form-control coa " /></td>';
   //html += '<td><input type="text" name="name[]" id="name_'+i+'" class="form-control table-condesed item_name" autocomplete="off"  required="" /></td>';
  // html += '<td> <select name="uom[]"  id="uom_'+i+'" class="form-control item_uom js-example-basic-single  "><?php echo uom($conn); ?></select></td>';
   html += '<td><input type="text" name="unit[]" value="1"  id="unit_'+i+'" class="form-control table-condesed item_unit" autocomplete="off"  /></td>';
//    html += '<td><input type="" name="bp[]" id="bp_'+i+'" class="form-control item_bp" required="" /></td>';
   html += '<td><input type="" name="price[]" id="price_'+i+'" class="form-control item_price" required=""  autocomplete="off"/></td>';
//    html += '<td><select name="vat[]"   required="" id="vat_'+i+'" class="form-control item_vat js-example-basic-single "><option value="1"> ZERO RATED </option><?php echo vat($conn); ?></select></td>';  
     
   html += '<td><input type="hidden" name="vatamount[]" id="vatamount_'+i+'" value="0" class="form-control item_vatamount " /> <input type="hidden" name="total[]" id="total_'+i+'" value="0" class="form-control item_total " /><input type="text" name="payable[]" id="payable_'+i+'" readonly="true" class="form-control item_payable " /></td>';  
   html += '<td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn-xs btn-block remove"> <i class="fa fa-trash"></i> </button></td></tr>';
      
  $('#item_table').append(html);
                                      
     
  // DELETE A ROW 
          $(document).on('click', '.remove', function(){  
           var button_id = $(this).attr("id");   
         //  $('#row'+button_id+'').remove();  
         if( button_id > 1)
               {
                   $('#row'+button_id+'').remove(); 
                }else{}
         
           ///calculateTotal (); calculatePayable (); calculateVat ();  
              
      }); 
     
  //  INITIALIZE SELECT 2 ON DYNAMIC TABLE 
     
              $('.js-example-basic-single').select2({
                placeholder:'',
                width: 'resolve'        
            });

// SELECTED ITEM CHANGE 
        // $("#item_table").on('change', '.item', function()
        //     {
        //        var item =      $(this).closest('tr').find('.item').val();
        //        var stockcoa = function () { var stockcoa = 0 ;
        //                             $.ajax({
        //                                     async: false, 
        //                                     'type': "POST",                                          
        //                                     'url': "../zajax/aj.item.php",
        //                                     'data': { item:item  },
        //                                     'success': function (data) {  
        //                                                                   var ob=jQuery.parseJSON(data); 
        //                                                                   stockcoa = parseInt(ob.stockcoa) ;                                                                              
        //                                                                   // alert(stockcoa) ;                                                                            
        //                                                               }
        //                                     });  return  stockcoa;
        //                           }();
        //        $(this).parents("tr").find(".coa").val(stockcoa);   
                                                  
        //     });

     
// PRICE CHANGE 
            $("#item_table").on('change', '.item_price', function(){

                      var unit =      $(this).closest('tr').find('.item_unit').val();
                      var price =     $(this).closest('tr').find('.item_price').val();                      
                      var total =    unit * price ;                         
                      $(this).parents("tr").find(".item_total").val(total);  
                      $(this).parents("tr").find(".item_payable").val(total) ;
                      calculateTotal (); calculatePayable ();             
                     
                                                                 });
// UNIT CHNAGE 
$("#item_table").on('change', ".item_unit", function()
         {                     
                      var unit =      $(this).closest('tr').find('.item_unit').val();
                      var price =     $(this).closest('tr').find('.item_price').val();                    
                      var total = unit * price ;                          
                      $(this).parents("tr").find(".item_total").val(total);  
                      $(this).parents("tr").find(".item_payable").val(total) ;    
                      calculateTotal (); calculatePayable ();         
                                         
          }); 
// VAT CHANGE 



 

     
     
 });
       
                                    function calculateTotal () { $(".item_table").each(function () {  
                                                     var sum = 0; 
                                                      $("input[name='total[]']").each(function () {
                                                      if (!isNaN(this.value) && this.value.length != 0) 
                                                             { sum += parseFloat(this.value);  }
                                                                       $("input[name='g_subtotal']").val(sum);
                                                                                                    });  
                                                                                      });
                                                             }
          
                                   function calculatePayable () { $(".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_total']").val(sum);
                                                                       $("input[name='invamount']").val(sum);
                                                                                                    });  
                                                                                      });
                                                                 }
                                                                          
                                                  

                   });
</script>
<!-- DYANAMIC ROWS LISTING HERE --->

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