<?php 
if(!isset($_SESSION)) { 
  session_start(); 
  include('../includes/dbcon.php');
}
if(empty($_SESSION['rm_id'])):
header('Location:../index.php');
endif;


  $inv_no=0;

if (isset($_GET['inv_no'])) { 
  $inv_no= trim($_GET['inv_no']);
}  //// if is set


if (isset($_POST['inv_no'])) { 
$inv_no= trim($_POST['inv_no']);

}

///////////////////VAT
$sqlvat="select * from company_master ";
$sqlitemvat=mysqli_query($con,$sqlvat)or die(mysqli_error($con));
          while($rowvat=mysqli_fetch_array($sqlitemvat)){     
                
                 $vatp=$rowvat['vat'];
             }  

/////////////////////////////////////

///echo $inv_no;
if ($inv_no<>0){

$pp="SELECT einv_temp_header.*,customer_master.cus_name,stock_locations.loc_name
FROM einv_temp_header
LEFT JOIN stock_locations ON einv_temp_header.loc_id=stock_locations.loc_id
LEFT JOIN customer_master ON customer_master.cus_id=einv_temp_header.cus_id where invd_id=$inv_no " ;


  $sqlsp=mysqli_query($con,"SELECT einv_temp_header.*,customer_master.cus_name,stock_locations.loc_name
FROM einv_temp_header
LEFT JOIN stock_locations ON einv_temp_header.loc_id=stock_locations.loc_id
LEFT JOIN customer_master ON customer_master.cus_id=einv_temp_header.cus_id where invd_id=$inv_no ")or die(mysqli_error($con));
            $count=mysqli_num_rows($sqlsp); 
            if ($count>0) {
              ///echo "fff";
              while($rowsp=mysqli_fetch_array($sqlsp)){     
                 $loc_name=$rowsp['loc_name']; 
                 $invd_id=$rowsp['invd_id']; 
                 $invd_date=$rowsp['invd_date']; 
                 $loc_id=$rowsp['loc_id'];  
                 $cus_name=$rowsp['cus_name']; 
                 $vat_inv=$rowsp['vat_inv'];
             }  

          
            }// if ($count>0) {

}  ////if ($grnd_no<>0){

if($vat_inv>0){
    $vname="VAT";
}
else {$vname=" "; }

?>
<!DOCTYPE html>
<html lang="en">


<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title> Sales Management </title>
  <!-- plugins:css -->
  <?php include('../includes/commonheader.php');?>
  
  
  
</head>

<body class="horizontal-menu">
 <?php include('../includes/header.php');?>
<div class="main-panel">         
<div class="content-wrapper">  
     
          <div class="row">
            <div class="col-md-8 grid-margin stretch-card">
              <div class="card">
                <div class="card-body">
                   <form class="forms-sample" >
                  <div class="table-responsive">
                   
                    <table  class="table no-border" >
                      <thead>
                        <tr>
                          <th>Barcode</th>
                          <th>Item</th>
                          <th>Qty</th>
                           <th></th>
                        </tr>
                      </thead>
                      <tbody>
                        <tr>
                             <input type="hidden" class="form-control" id="loc_id" name="loc_id"value=<?php echo $loc_id; ?> >
                             <input type="hidden" class="form-control" id="invref" name="invref" value="<?php echo   $invd_id;  ?>" >
                               <input type="hidden" class="form-control" id="vatp" name="vatp" value="<?php echo    $vatp;  ?>" >
                            
                            
                          <td> <input type="text" class="form-control input-box" id="barcode" name="barcode">
                          </td>
                          <td class="font-weight-bold">
                          <div style="display: flex; width: 100%; gap: 5px;">
                              <select class="form-control select2" style="width: 200px !important;" name="item_id" id="item_id" autofocus>

                         
                          <option value="0">~~~Select Item ~~~~</option>  
                            <?php 
                            $querydoc=mysqli_query($con,"SELECT view_item_master.item_id ,view_item_master.item_name
                            FROM view_item_master
                            LEFT JOIN item_stocks ON view_item_master.item_id=item_stocks.item_id AND item_stocks.loc_id=$loc_id
                            WHERE sales_price<>0  and item_stocks.loc_id=$loc_id AND IFNULL(item_stocks.loc_qoh ,0)<>0  ")or die(mysqli_error());          
                            while($rowd=mysqli_fetch_array($querydoc)){
                            ?>
                            <option value="<?php echo $rowd['item_id'];?>"><?php echo $rowd['item_name'];?></option>        
                            <?php }?>
                            </select> 
                            </div>
                          </td>
                          <td class="text-muted">
                              
                             <input type="number" class="form-control input-box" id="qty" name="qty">
                             <input type="hidden" class="form-control input-box" id="costprice" name="costprice"placeholder=" Price" readonly>  
                          </td>
                          <td>                   
                  
                            <button type="button" class="btn btn-primary mr-2">Add Item</button>
                         
                        </tr>
                        
                      
                      </tbody>
                    </table>
              </form>
    <div class="col-md-12 grid-margin d-flex align-items-center gap-3">
    <div class="result"></div>
    <div class="resultsp"></div>
    <div class="result-unit text-primary" style="font-size:10px;"></div>
    <div class="result-cc text-primary" style="font-size:10px;"></div>
    <div class="result-qoh text-primary" style="font-size:10px;"></div>
    <input type="hidden" class="form-control" id="lqty" name="lqty" placeholder="Qty">
    </div>
</div>

<form class="needs-validation" novalidate method="post" action="einv_new_final_add.php" enctype="multipart/form-data" > 
                    <div class="form-group row">
                      <div class="table-responsive">
                       <input type="hidden" class="form-control" id="inv_no" name="inv_no" value="<?php  echo $inv_no;  ?>">
                        <input type="hidden" class="form-control" id="loc_id" name="loc_id" value="<?php  echo $loc_id;  ?>">


       <div style="overflow-y: auto; max-height: 300px; border: 1px solid #ddd;">
                     <table id="order-listing" class="table table-striped table-bordered table-sm" cellspacing="0"
  width="100%"> 
                       <tr>
              
                        <th class="bg-primary text-white" width=30%>Item </th>                         
                        <th width=15%>Qty</th>  
                        <th width=20%>Price</th>
                        <th width=15%>Discount</th>
                        <th width=20%>Tot</th>  
                        <th>Action</th>
                      
                        </tr>  
                      </table>
                      </div>          
        

        
               </div>  </div>   </div>  </div>          
         <div class="col-md-6 grid-margin stretch-card">
              <div class="card">
                <div class="card-body">
                  <h4 class="card-title">
                    <i class="fas fa-calendar-alt"></i>
                    Payments
                  </h4>
                  <form>
                  <div class="table-responsive">
                      <table >
                      <thead>
                        <tr>
                          <th>
                           
                          </th>
                          <th>
                           
                          </th>
                         
                        </tr>
                      </thead>
                      <tbody>
                        <tr>
                          <td class="py-1">
                           Sub Total
                          </td>                        
                           <td class="py-1">
                                
                          <input type="number" class="form-control input-box" id="subtot" name="subtot"  readonly>
                         
                          </td>  
                        </tr>
                        <tr>
                          <td class="py-1">
                           Discount %
                          </td>
                          <td>
                            <input type="number" class="form-control " id="discount" name="discount"  >
                          </td>
                          
                        </tr>
                         <tr>
                          <td class="py-1">
                           Net Total
                          </td>
                          <td>
                             <input type="number" class="form-control " id="net" name="net"  readonly>
                          </td>
                          
                        </tr>
                        
                        <tr>
                          <td class="py-1">
                           Paid Amount - Cash
                          </td>
                          <td>
                            <input type="number" class="form-control" id="pcash" name="pcash" oninput="calculateBalance()">
                          <input type="hidden" class="form-control " id="pcard" name="pcard"  >
                          <input type="hidden" class="form-control " id="pcash1" name="pcash1"  >
                          </td>
                          
                        </tr>
                        
                        <tr>
                          <td class="py-1">
                           Balance
                          </td>
                          <td>
                            <input type="number" class="form-control " id="bal" name="bal"  >
                          </td>
                          
                        </tr>
                        <tr>
                          <td class="py-1">
                           Due Amount
                          </td>
                          <td>
                            <input type="number" class="form-control " id="due" name="due"  >
                          </td>
                          
                        </tr>

                        
                      </tbody>
                    </table>
                     <p class="card-description">
          <button type="submit" class="btn btn-primary mr-2">Create Invoice</button>
        <button type="button" class="btn btn-light" onclick="window.location.href='home.php';">Cancel</button>    
                  </p>
                    </form>
                  </div>
                </div>
              </div>
            </div>
          </div>   
       
</div>  
</div>   


<?php include('../includes/commonjs.php');?>
</body>
</html>

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

          page_disp();
function page_disp() {
    
   var inv_no= $("#inv_no").val();
       // alert(inv_no);
            $.ajax({
                type: 'POST',
                dataType: "json",
                url: 'einv_new1_disp.php',
                        data: {
                        'inv_no' : inv_no,  
                        
                },
                cache: false,
                success: function(result) {
                  // alert(result.length);
                    //alert(inv_no);
                    document.getElementById("qty").value = '';
                     document.getElementById("costprice").value = '';                 
                    $("#item-disp tr").remove();
                    $('#order-listing tr').remove();


                          var row = $('<tr class="bg-primary text-white" style="height: 10px;"><th width=5%>' + "#" + '</th><th width=30%>' + "Item" + '</th><th width=10%>' + "Qty" + '</th><th >' + "Price" + '</th><th width=10%>' + "Discount"
                            + '</th><th>' + "Tot" + '</th><th>' + "Action" + '</th></tr>');
                       
                          $('#order-listing').append(row);


                          var tot_qty=0;
                          var tot_sales=0;
                          var total_sales=0;
                          var fdis_tot=0;
                          var total_sales_final=0;
                          var qty=0;
                          var rcount=0;

                    for (var i=0; i<result.length; i++) {
                     // alert(result[i].item_id);
                     rcount=rcount + 1
                      var fdis=result[i].discount;
                      var itemid=result[i].item_id;
                      var tot=result[i].qty * result[i].sales_price;
                      var dis=result[i].item_dis;
                      var rawdis=(result[i].qty * result[i].sales_price) * dis/100;
                      qty=parseInt(result[i].qty);
                      tot_sales=tot - rawdis;

                      tot_qty = tot_qty + qty;
                      total_sales=total_sales + tot_sales;
                      fdis_tot = total_sales * fdis/100;
                      total_sales_final =total_sales - fdis_tot;


                    // alert("itemid");
                      var row = $('<tr style="height: 5px;"><td id="test" width=5%>' + rcount + '</td><td id="test" width=30%>' + result[i].item_name+ '</td><td width=15% align="right">' + result[i].qty +  
                        '<td width=20% align="right">' + result[i]. sales_price +
                       '</td><td width=15% align="right">' + result[i].item_dis + '</td><td align="right" width=20%>' + tot_sales.toFixed(2) + 
                       '</td><td>  <form method="post" action="#" enctype="multipart/form-data"> <input type="hidden" class="form-control pull-right" id="itemid" name="itemid"  value=' +  itemid +  ' ><input type="hidden" class="form-control pull-right" id="invref" name="invref"  value=' +  inv_no +  ' >                         <button type="submit" formaction="inv_new1_removeitem.php" class="btn btn-outline-secondary btn-rounded btn-icon" style="width: 15px; height: 15px;">                        <i class="fas fa-trash text-danger" style="font-size: 10px;"></i>                      </button></form></td></tr>'   );
                        $('#order-listing').append(row);
                    }


                     var row = $(' <tfoot><tr style="height: 5px;" class="bg-warning text-black"><td width=5%>' + "Total" + '</td><td >' + " " + '</td><td align="right" width=12% >' + tot_qty + '</td><td width=17% >' + " " + '</td><td width=14%>' + " "
                            + '</td><td align="right" width=18%>' + " " + '</td><td>' + " " + '</td></tr>');
                          $('#order-listing').append(row);
                            document.getElementById("subtot").value = total_sales.toFixed(2);

                           var row = $('<tfoot><tr class="bg-warning text-black"><td width=28%>' + "Discount   " + fdis + '</td><td width=12%>' + "" + '</td><td width=17% >' + " " + '</td><td width=14%>' + " " 
                            + '</td><td align="right"  width=18%>' + fdis_tot + '</td><td>' + " " + '</td></tr>');
                         // $('#order-listing').append(row);
                                document.getElementById("discount").value = fdis_tot.toFixed(2);

                           var row = $('<tfoot><tr class="bg-warning text-black"><td width=28%>' + "Net Total" + '</td><td width=12%>' + "" + '</td><td width=17% >' + " " + '</td><td width=14%>' + " " 
                            + '</td><td align="right" width=18%>' + total_sales_final.toFixed(2) + '</td><td>' + " " + '</td></tr> </tfoot>');
                         // $('#order-listing').append(row);
                         document.getElementById("net").value = total_sales_final.toFixed(2);

                      }   ////~~~~~~~~~~end of sucess functions
                });  ///~~~~~~~~~~~~~~~~~~end of  $.ajax({
}

          

          ///////End of page refresh

           $("button").click(function(){
               // alert("Please Selectsssss Orderssss Type");
                //////!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                 //var category = 100;
                 var category = $("#item_id").val();
                 var issue_qty = $("#qty").val();
                 var invref= $("#invref").val();
                 //var costprice= $("#costprice").val();

                 $.ajax({
                type: 'POST',
                 dataType: "json",
                url: 'inv_new1_ajax.php',
                        data: {
                        'invref' : invref,  
                        'category' : category , 
                        'issue_qty' : issue_qty ,  
                       // 'costprice' : costprice ,      

                },
                cache: false,
                success: function(result) {
                 // alert("ff");
                
                 

                      }   ////~~~~~~~~~~end of sucess functions
                });  ///~~~~~~~~~~~~~~~~~~end of  $.ajax({
                  location.reload();
                  // page_disp();
              });  //// end of  $("button").click(function(){


              ///  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
               $('#item_id').on('change', function(){

                var item_id = $('#item_id').val();
                var loc_id = $('#loc_id').val();
                var vatp= $('#vatp').val();
                var leavespace=" ";
                //alert(vatp);

                 $.ajax({
                 type: 'POST',
                 dataType: "json",
                 url: 'inv_new1_itemdisp.php',
                        data: {
                        'item_id' : item_id, 
                         'loc_id' : loc_id, 
                         },
                cache: false,
                success: function(result1) {
                  // alert(result1[0].loc_qoh);
                    for (var i=0; i<result1.length; i++) {
                      //alert(result[i].item_id);
                      var itemid=result1[i].item_id;
                      var location_qoh=result1[i].loc_qoh;
                 
if (location_qoh === null) {
  location_qoh=0
} else {
  //console.log("The string is not empty or null");
}

    // Calculate VAT excluded price
    var sales_price = parseFloat(result1[i].sales_price);
    var vat_excluded_price = sales_price / (1 + vatp / 100);
    vat_excluded_price = vat_excluded_price.toFixed(2);


                     // alert(itemid);
                     // $("#stock-listing tr").remove();
            document.getElementById("costprice").value = result1[i].sales_price;
          //  document.getElementById("dis").value = result1[i].discount_rate
                     // $("#stock-listing tr").remove();
                         // var row = $('<tr class="bg-success text-black"><td width=10%>' + "Item" + '</td><td width=10%>' + "Unit" + '</td><td width=10%>'+ "QOH" + '</td><td width=10%>' + "ROL" +  '</td>');
               // $('#item-disp').append(row);
              
                    var qoh_disp="QOH : ".concat(location_qoh);
                    $(".result").html("Des : " . concat(result1[i].description)); 
                    $(".result-unit").html("QOH: ".concat(location_qoh) .  concat('&nbsp'));
                  
                    $(".resultsp").html("Sales Price : " . concat(result1[i].sales_price) . concat(leavespace) .concat("W/O VAT  :") . concat(vat_excluded_price ) . concat(leavespace));
                    
                    document.getElementById("lqty").value =result1[i].loc_qoh;
                    $("#qty").focus();   
                     
           // $("#sticker").focus();
            // document.getElementById("sticker").focus();

                     // var row = $('<tr class="table-success text-black"><td width=10%>' + result1[i].description+ '</td><td width=10%>' + result1[i].unit_des +   '</td><td width=10%>' + result1[i].qoh +   '</td><td width=10%>' + result1[i].rol +   '</td>'  );

                       // $('#stock-listing').append(row);
                    }
                    
                   

                      }   ////~~~~~~~~~~end of sucess functions
                });  ///~~~~~~~~~~~~~~~~~~end of  $.ajax({

                


    

                 //alert(item_id);
                 }); ///// $('#item_id').on('change', function(){

              ///~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

 $('#qty').on('change', function(){
   var qty = $('#qty').val();
   var lqty = $('#lqty').val();

var difqty=lqty - qty;
//alert(difqty);
if (difqty<0)
{   
  alert("Cant Invoice this qty"); 
 $("#qty").focus();
  document.getElementById("qty").value =lqty;

 }   

  });////


     
    });////end of $( document ).ready(function() {

function validateForm() { 

    //````````route````````````````````````````````````
  alert('s');
    if($('#bname').val().trim().length == 0) {
           alert("Please enter the route you visited !!!");               
            return false;
    } ////``````````````````````````````````````````

  
 } ///validateForm() { 

</script>

 <!-- End custom js for this page-->
  <script>
  $(function () {
    //alert("Please Select Order Type");
    //Initialize Select2 Elements
    $('.select2').select2()

    //Initialize Select2 Elements
    $('.select2bs4').select2({
      theme: 'bootstrap4'
    })



     
  })

</script>
<script>
  function calculateBalance() {
    let netTotal = parseFloat(document.getElementById("net").value) || 0;
    let paidCash = parseFloat(document.getElementById("pcash").value) || 0;
    let balance = netTotal - paidCash;
  
    
    if (netTotal > paidCash) {
         document.getElementById("pcash1").value = paidCash.toFixed(2);
    } else {
        document.getElementById("pcash1").value = netTotal.toFixed(2);
    }
    
    if (balance >= 0) {
       document.getElementById("due").value = balance.toFixed(2);  // Due input
       document.getElementById("bal").value =0;
    } else {
      document.getElementById("due").value = 0; // If negative, set balance to 0
      document.getElementById("bal").value = balance.toFixed(2); // Keep 2 decimal places
    }
  }
</script>

<script>
document.getElementById("discount").addEventListener("input", function() {
    let subtot = parseFloat(document.getElementById("subtot").value) || 0;
    let discount = parseFloat(this.value) || 0;

    // Calculate discount amount
    let discountAmount = (subtot * discount) / 100;
    
    // Calculate net total
    let netTotal = subtot - discountAmount;

    // Update net total field
    document.getElementById("net").value = netTotal.toFixed(2);
});
</script>
