<?php
ini_set('display_errors', '0');
ini_set('display_startup_errors', '0');
error_reporting(E_ALL);
ob_start();
session_start();

include 'load.php';

if(isset($_POST['save']))

{		

	
		
		
		
		// if no error occured, continue ....

		if(!isset($errMSG))

		{	

			$temp_purchase_order = mysqli_query($conn, "SELECT * FROM temp_purchase_order");
			$temp_purchase = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM temp_purchase_order"));
			
			$temp_purchase_sum = mysqli_fetch_array(mysqli_query($conn, "SELECT SUM(price*qty) as tot,invoice_no FROM temp_purchase_order"));
			$tot = $temp_purchase_sum['tot'];
			$invoice_no = $temp_purchase_sum['invoice_no'];
			if ($temp_purchase_order->num_rows > 0) {
				$stat = 0;
				$supplier = $temp_purchase['supplier'];
				$sql = "INSERT INTO mobile_purchase_order (suppler_id,total_amount,invoice_no)VALUES ('$supplier','$tot','$invoice_no')";
				if ($conn->query($sql) === TRUE) {
					$last_id = $conn->insert_id;
					
				while($row = $temp_purchase_order->fetch_assoc()) { 
					
					$qty = $row['qty'];
					$product_id = $row['product_id'];
					$prodductinfo = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM mobileproducts WHERE prid='$product_id'"));
					$price = $prodductinfo['price'];
					
					$sql2 = "INSERT INTO purchase_order_items (product_id,qty,supplyer_id,purchase_order_id,price)VALUES ('$product_id','$qty','$supplier','$last_id','$price')";
						if ($conn->query($sql2) === TRUE) {
							$sql3 = "UPDATE tbl_stock SET qty = qty + $qty WHERE prid = '$product_id'";
								if ($conn->query($sql3) === TRUE) {
									$sql7 = "DELETE FROM temp_purchase_order";
                					if ($conn->query($sql7) === TRUE) {
										$stat = 1;
									}
								}
						}

				}
				
			}else{
				$errMSG = "Error! Please add products";
			}

			if($stat==1){
				
					$successMSG = "Successfully! Add Your Products....";
								header("refresh:2;listpurchaseorder.php");
			}else{
				$errMSG = "error while inserting....";
			}





		}

	}
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0">
<meta name="description" content="POS - Payroll | Pos & Invetory System | Dashboard
">
<meta name="keywords" content="Payroll | Pos & Invetory System | Dashboard
">
<meta name="author" content="Payroll | Pos & Invetory System | Dashboard
">
<meta name="robots" content="noindex, nofollow">

<title>Home | Payroll | Pos & Invetory System | Dashboard
</title>


<?php
require_once 'headercss.php';
?>
</head>
<body>
<div id="global-loader">
<div class="whirly-loader"> </div>
</div>

<div class="main-wrapper">
<?php
require_once 'header.php';
?>

<?php
require_once 'navbar.php';
?>

<div class="page-wrapper">
<div class="content">
<div class="page-header">
<div class="page-title">
<h4>Purchase Order Management</h4>
<h6>Add/Update Purchase Order</h6>
</div>
<div class="page-btn" style="display: flex;">
                        <a style="margin-right:10px;" ="addsupplier.php" class="btn btn-added"><img src="assets/img/icons/plus.svg"
                                alt="img">Add Supplier</a>
								<a href="addproduct.php" class="btn btn-added"><img src="assets/img/icons/plus.svg"
                                alt="img">Add Product</a>
                    </div>
					





</div>

<div class="card">
<div class="card-body">

									<?php

									if(isset($errMSG)){

									?>
			
									<div class="alert alert-danger alert-dismissible alert-alt solid fade show">
									<button type="button" class="close h-100" data-dismiss="alert" aria-label="Close"><span><i class="mdi mdi-close"></i></span></button>
									<strong>Error!</strong> <?php echo $errMSG; ?>
									</div>

									<?php

									}
	
									else if(isset($successMSG)){

									?>
			
									<div class="alert alert-success alert-dismissible alert-alt solid fade show">
									<button type="button" class="close h-100" data-dismiss="alert" aria-label="Close"><span><i class="mdi mdi-close"></i></span></button>
									<strong>Success!</strong> <?php echo $successMSG; ?>.
									</div>

									<?php

									}

									?>
<div class="row">
<div class="col-lg-3 col-sm-6 col-12">
									<div class="form-group">
										<label for="fullName">Supplier</label>
										<select name="supplier" class="form-control select2" id="inputsupplier" required>
											<option disabled selected value="0">Select Supplier</option>
											<?php

											$stmt = $DB_con->prepare('SELECT * FROM mobilesuppliers ORDER BY spid');

											$stmt->execute();

											if ($stmt->rowCount() > 0) {

												while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

													extract($row);

													?>
													<option value="<?php echo $row['spid']; ?>"><?php echo $row['spname']; ?>
													</option>
													<?php
												}
											}
											?>
										</select>
									</div>
								</div>
								<div class="col-lg-3 col-sm-6 col-12">
<div class="form-group">
<label for="fullName">Invoice No</label>
<input type="text" id="invoice_no" class="form-control" placeholder="Enter Invoice No">
</div>
</div>


<div class="col-lg-3 col-sm-6 col-12">
<div class="form-group">
<label for="fullName">Product</label>
      <select class="form-control product select2">
        <option value="">Select Product</option>
            <?php 
                $sql = "SELECT * FROM mobileproducts";
                $result = $conn->query($sql);
                
                if ($result->num_rows > 0) {
                  while($row = $result->fetch_assoc()) {
                        echo "<option value='".$row['prid']."'>".$row['proname']."</option>";
                  }
                }
            
            
            ?>                        
    </select>                              
</div>
</div>


<!--<div class="col-lg-4 col-sm-6 col-12">
<div class="form-group">
<label for="fullName">Price</label>
<input type="number" name="price" min="0.01" step="0.01" class="form-control" placeholder="Enter Price">
</div>
</div>-->

<div class="col-lg-3 col-sm-6 col-12">
<div class="form-group">
<label for="fullName">Qty</label>
<input type="number" name="qty" min="1" step="0.01" class="form-control qty" placeholder="Enter Qty">
</div>
</div>



<div class="col-lg-12">
<span class="btn btn-submit me-2 mb-2 add">Add</span>


</div>

<div class="col-lg-12">
<table class="table">
  <thead class="thead-dark">
    <tr>
      <th scope="col">Prodcut</th>
      <th scope="col">Qty</th>
	  <th scope="col">Price</th>
	  <th scope="col">Total</th>
	  <th scope="col">Action</th>
    </tr>
  </thead>
  <tbody>
	
   
  </tbody>
</table>



</div>



<form method="POST" enctype="multipart/form-data">




								<div class="col-lg-2">
										<button type="submit" name="save" class="btn btn-submit me-2 mt-2">Save</button>
								</div>
</form>



</div>
</div>

</div>
</div>
</div>


<script src="assets/js/jquery-3.6.0.min.js"></script>

<script src="assets/js/feather.min.js"></script>

<script src="assets/js/jquery.slimscroll.min.js"></script>

<script src="assets/js/jquery.dataTables.min.js"></script>
<script src="assets/js/dataTables.bootstrap4.min.js"></script>

<script src="assets/js/bootstrap.bundle.min.js"></script>

<script src="assets/plugins/select2/js/select2.min.js"></script>

<script src="assets/plugins/sweetalert/sweetalert2.all.min.js"></script>
<script src="assets/plugins/sweetalert/sweetalerts.min.js"></script>

<script src="assets/js/script.js"></script>

<script>
	$(document).ready(function(){
		$('.select2').select2();
		loaditems();

		$(".add").click(function(){
			var product = $('.product').val(); 
			var supplier = $('#inputsupplier').val(); 
			var qty = $('.qty').val();
			var invoice_no = $('#invoice_no').val();
			$.ajax({
           		type: "POST",
				data: {product:product,qty:qty,supplier:supplier,invoice_no:invoice_no},
				url: "add-prodcut-to-list.php",
					success: function(data){
						loaditems();
					}
				});
  		});

		 
		  
	});

	function remove(id){
		$.ajax({
           		type: "POST",
				data: {id:id},
				url: "add-prodcut-to-list.php",
					success: function(data){
						loaditems();
					}
				});
	}

	function loaditems(){
		$.ajax({
           		type: "POST",
				//data: {id:id},
				url: "load-purchase-order-tbody.php",
					success: function(data){
						$("tbody").html(data);
					}
				});
	}
</script>


</body>
</html>