<?php
	include 'db_Connection.php'; // load file db_Connection.php
	//include 'session_validate.php'; // cek session validate	
	
	$userID = $_SESSION['username'];
	$Level = $_SESSION['level'];
	
	//Generate random number_format
	$number = rand(100,100000);
	$t=time();
	$random = $number.''.$t;
?>
<!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>Purchase Order</title>
    <!-- plugins:css -->
    <link rel="stylesheet" href="../../assets/vendors/mdi/css/materialdesignicons.min.css">
    <link rel="stylesheet" href="../../assets/vendors/ti-icons/css/themify-icons.css">
    <link rel="stylesheet" href="../../assets/vendors/css/vendor.bundle.base.css">
    <link rel="stylesheet" href="../../assets/vendors/font-awesome/css/font-awesome.min.css">
    <!-- endinject -->
    <!-- Plugin css for this page -->
    <link rel="stylesheet" href="../../assets/vendors/select2/select2.min.css">
    <link rel="stylesheet" href="../../assets/vendors/select2-bootstrap-theme/select2-bootstrap.min.css">
    <!-- End plugin css for this page -->
    <!-- inject:css -->
    <!-- endinject -->
    <!-- Layout styles -->
    <link rel="stylesheet" href="../../assets/css/style.css">
    <!-- End layout styles -->
    <link rel="shortcut icon" href="../../assets/images/favicon.png" />
	<!--get jquery -->
	<script src="../js/jquery-3.4.1.min.js"></script>
	
<script>
$(document).ready(function(){       
    $(".postsubmit").click( function() {
	var PO_Number_val = document.getElementById("PO_Number");
	var Principal_Code_val = document.getElementById("Principal_Code");		
	var PO_Date_val = document.getElementById("PO_Date");
	var Payment_Type_val = document.getElementById("Payment_Type");	
	var Amount_val = document.getElementById("Amount");
	var Percentage_val = document.getElementById("Percentage");
	
	var PO_Number = PO_Number_val.value;
	var Principal_Code = Principal_Code_val.value;
	var Principal_Name = $("#Principal_Name option:selected").text();
	var PO_Date = PO_Date_val.value;
	var Payment_Type = Payment_Type_val.value;	
	var Amount = Amount_val.value;
	var Percentage = Percentage_val.value;
	var Subtotal = $("#subtotal").text();		
	
	var rowcount = $('#list_item tr').length - 2;
	var Product_Code = [];
	var Product_Name = [];
	var Product_Type = [];
	var Description = [];
	var Price = [];
	var Quantity = [];
	var Total = [];
	
	if(Amount > Subtotal){
		alert("OverPayment");
		return false;
	}
	
	if(Principal_Name == "None"){
		alert("Please select Principal Name");
		//e.preventDefault();
		return false;
	}
	else{
	//insert PO_detail		
	for(i = 1; i <= rowcount; i++){	
		//makeRequest(i);
		Product_Code[i] = $('#list_item').find('tr:eq('+ i +')').find('td:eq(0)').html();
		Product_Name[i] = $('#list_item').find('tr:eq('+ i +')').find('td:eq(1)').html();
		Product_Type[i] = $('#list_item').find('tr:eq('+ i +')').find('td:eq(2)').html();
		Description[i] = $('#list_item').find('tr:eq('+ i +')').find('td:eq(3)').html();
		Price[i] = $('#list_item').find('tr:eq('+ i +')').find('td:eq(4)').html();
		Quantity[i] = $('#list_item').find('tr:eq('+ i +')').find('td:eq(5)').html();
		Total[i] = $('#list_item').find('tr:eq('+ i +')').find('td:eq(6)').html();
		//console.log(Product_Code, ProductName, Product_Type, Description, Price, Quantity, Total);		
	}			
		var dataPost = {
                "PO_Number": PO_Number,
                "Principal_Code": Principal_Code,
				"Principal_Name": Principal_Name,
                "PO_Date": PO_Date,
                "Payment_Type": Payment_Type,                
                "Amount": Amount,
				"Percentage": Percentage,
				"rowcount": rowcount,
				"Product_Code": Product_Code,
				"Product_Name": Product_Name,
				"Product_Type": Product_Type,
				"Description": Description,
				"Price": Price,
				"Quantity": Quantity,
				"Total": Total,
				"Subtotal": Subtotal
                };
            var dataString = JSON.stringify(dataPost);
	
	if($("form")[0].checkValidity()) {	
	$.ajax({
                type: "POST",
                url: "..//forms/po_validate.php",
                dataType: "json",                        
                data: {data_post: dataString},
                async:false,
                success : function(data){                     
                    if(data.result == "duplicate"){
                       alert("Duplicate PO Number");                                  
                       // swal("Warning!", "Group Already Exist", "warning"); 
                       //flag = 1;                  
                   }                   
                   else{
					   alert("Generate PO Succsess");
                      //swal("Warning!", "trap", "warning"); 
                      //flag = 1;  
                   }
                },
                error : function(data){ 
                    alert("Data Failed to send");
                    //alert(data.result);
                    //flag = 1;
                    //return false;
                }
            });
	}
	}					
    });                   
});    
</script>
	
<script>
$(document).ready(function(){
	$('#Principal_Name').change(function(){
		//selected value
		var inputValue = $(this).val();
		//alert(inputValue);
		document.getElementById("Principal_Code").value = inputValue;
	});
});
</script>

<script>
$(document).ready(function(){
	$('#Product_Name').change(function(){
		//selected value
		var inputValue = $(this).val();
		//alert(inputValue);

		if(inputValue == "0"){
			document.getElementById("Product_Code").value = "";
			document.getElementById("Product_Type").value = "";
			document.getElementById("Description").value = "";
		}
		else{
			var arraylist = inputValue.split("|");
			document.getElementById("Product_Code").value = arraylist[0];
			document.getElementById("Product_Type").value = arraylist[1];
			document.getElementById("Description").value = arraylist[2];
			//console.log(arraylist[1])		
		}				
	});
});
</script>	

<script>
$(document).ready(function(){
	$('#Payment_Type').change(function(){
		//selected value
		var inputValue = $(this).val();
		//alert(inputValue);
		if(inputValue == "Downpayment"){
			$(".rButton").show();
			document.getElementById("Amount").disabled = false;
			document.getElementById("Percentage").disabled = true;
		}
		else{
			$(".rButton").hide();
			//document.getElementById("Amount").disabled = false;
			document.getElementById("Amount").disabled = true;
			document.getElementById("Percentage").disabled = true;
			$("#R_Nominal").prop("checked", true);
		}
		
	});
});
</script>

<script>
$(function(){
	$("input:radio[id='R_Nominal']").click(function(){		
		document.getElementById("Amount").disabled = false;
		document.getElementById("Percentage").disabled = true;
});
});
</script>

<script>
$(function(){
	$("input:radio[id='R_Percentage']").click(function(){
		document.getElementById("Amount").disabled = true;
		document.getElementById("Percentage").disabled = false;
});
});
</script>

<script>
function AddItem(){
	var product_code = document.getElementById("Product_Code").value;
	var product_name = $("#Product_Name option:selected").text();	
	var product_type = document.getElementById("Product_Type").value;
	var description = document.getElementById("Description").value;
	var purchase_price = document.getElementById("Purchase_Price").value;
	var qty = document.getElementById("Quantity").value;	
	var total = purchase_price * qty;	
	var rows = "";	
	
	if(product_name == "None"){
		alert("Please select Product Name");
	}
	else{	
	rows += "<tr><td>" + product_code + "</td><td>" + product_name + "</td><td>" + product_type + "</td><td>" + description + "</td><td>" 
			+ purchase_price + "</td><td>" + qty + "</td><td>" + total + "</td></tr>";
	$(rows).appendTo("#list_item tbody");	
			
	//$("#subtotal").html(total);	
	var sum_total = $("#subtotal").text();	
	var intsum_total = parseInt(sum_total);
	var sum_subtotal = intsum_total + total;
	$("#subtotal").html(sum_subtotal);
	//alert(sum_subtotal);
	}			
}
</script>

<script>
	function RemoveZero(){		
		var price = document.getElementsByClassName("remZero")[0].value;
		var qty = document.getElementsByClassName("remZero")[1].value;
		//alert(qty);
		//var price = document.getElementById("Purchase_Price").value;				
		const intPrice = parseInt(price ,10);
		const intQty = parseInt(qty ,10);	
		document.getElementById("Purchase_Price").value = intPrice;
		document.getElementById("Quantity").value = intQty;		
		if(price == ""){
			document.getElementById("Purchase_Price").value = 0;
		}
		if(qty == ""){
			document.getElementById("Quantity").value = 0;
		}
	}
</script>

<script>
	function RemoveZero1(){		
		var Amount = document.getElementsByClassName("remZero1")[0].value;
		var Percentage = document.getElementsByClassName("remZero1")[1].value;
		
		const intPrice = parseInt(Amount ,10);
		const intQty = parseInt(Percentage ,10);	
		document.getElementById("Amount").value = intPrice;
		document.getElementById("Percentage").value = intQty;		
		if(Amount == ""){
			document.getElementById("Amount").value = 0;
		}
		if(Percentage == ""){
			document.getElementById("Percentage").value = 0;
		}
	}
</script>
	
  </head>
  <body>
    <div class="container-scroller">
      <!-- partial:../../partials/_navbar.html -->
      <nav class="navbar default-layout-navbar col-lg-12 col-12 p-0 fixed-top d-flex flex-row">
        <div class="text-center navbar-brand-wrapper d-flex align-items-center justify-content-start">
          <a class="navbar-brand brand-logo" href="../../index.php"><img src="../../assets/images/logo_IMS.svg" alt="logo" /></a>
          <a class="navbar-brand brand-logo-mini" href="../../index.php"><img src="../../assets/images/logo-mini.svg" alt="logo" /></a>
        </div>
        <div class="navbar-menu-wrapper d-flex align-items-stretch">
          <button class="navbar-toggler navbar-toggler align-self-center" type="button" data-toggle="minimize">
            <span class="mdi mdi-menu"></span>
          </button>		  
          <ul class="navbar-nav navbar-nav-right">
            <li class="nav-item nav-profile dropdown">
              <a class="nav-link dropdown-toggle" id="profileDropdown" href="#" data-bs-toggle="dropdown" aria-expanded="false">
                <div class="nav-profile-img">
                  <img src="../../assets/images/faces/blank.png" alt="image">
                  <span class="availability-status online"></span>
                </div>
                <div class="nav-profile-text">
                  <p class="mb-1 text-black"><?php echo $userID; ?></p>
                </div>
              </a>
              <div class="dropdown-menu navbar-dropdown" aria-labelledby="profileDropdown">
                <a class="dropdown-item" href="../../pages/forms/change_password.php">
                  <i class="mdi mdi-cached me-2 text-success"></i>Change Password</a>
                <div class="dropdown-divider"></div>
                <a class="dropdown-item" href="../../pages/forms/logout.php">
                  <i class="mdi mdi-logout me-2 text-primary"></i> Signout </a>
              </div>
            </li>
			
            </li>
			
            <li class="nav-item nav-settings d-none d-lg-block">
              <a class="nav-link" href="#">
                <i class="mdi mdi-format-line-spacing"></i>
              </a>
            </li>
			
          </ul>
          <button class="navbar-toggler navbar-toggler-right d-lg-none align-self-center" type="button" data-toggle="offcanvas">
            <span class="mdi mdi-menu"></span>
          </button>
        </div>
      </nav>
      <!-- partial -->
      <div class="container-fluid page-body-wrapper">
        <!-- partial:../../partials/_sidebar.html -->
        <nav class="sidebar sidebar-offcanvas" id="sidebar">
          <ul class="nav">
            <li class="nav-item nav-profile">
              <a href="#" class="nav-link">
                <div class="nav-profile-image">
                  <img src="../../assets/images/faces/blank.png" alt="profile" />
                  <span class="login-status online"></span>
                  <!--change to offline or busy as needed-->
                </div>
                <div class="nav-profile-text d-flex flex-column">
                  <span class="font-weight-bold mb-2"><?php echo $userID; ?></span>
                  <span class="text-secondary text-small"><?php echo $Level; ?></span>
                </div>
                <i class="mdi mdi-bookmark-check text-success nav-profile-badge"></i>
              </a>
            </li>

            <li class="nav-item">
              <a class="nav-link" data-bs-toggle="collapse" href="#forms" aria-expanded="false" aria-controls="forms">
                <span class="menu-title">Manage</span>
                <i class="mdi mdi-format-list-bulleted menu-icon"></i>
              </a>
              <div class="collapse" id="forms">
                <ul class="nav flex-column sub-menu">
                  <li class="nav-item">
					<a class="nav-link" href="../../pages/forms/Users.php">Users</a>
                    <a class="nav-link" href="../../pages/forms/Principal.php">Principal</a>
					<a class="nav-link" href="../../pages/forms/Customer.php">Customer</a>
					<a class="nav-link" href="../../pages/forms/Product.php">Product</a>
                  </li>
                </ul>
              </div>
            </li>	

			<li class="nav-item">
              <a class="nav-link" data-bs-toggle="collapse" href="#maintance" aria-expanded="false" aria-controls="maintance">
                <span class="menu-title">Maintance</span>
                <i class="mdi mdi-table-large menu-icon"></i>
              </a>
              <div class="collapse" id="maintance">
                <ul class="nav flex-column sub-menu">
                  <li class="nav-item">
					<a class="nav-link" href="../../pages/forms/Users_Maintance.php">Users</a>
                    <a class="nav-link" href="Principal_Maintance.php">Principal</a>
					<a class="nav-link" href="Customer_Maintance.php">Customer</a>
					<a class="nav-link" href="Product_Maintance.php">Product</a>
                  </li>
                </ul>
              </div>
            </li>	

			<li class="nav-item">
              <a class="nav-link" data-bs-toggle="collapse" href="#transaction" aria-expanded="false" aria-controls="transaction">
                <span class="menu-title">Transaction</span>
                <i class="mdi mdi-format-list-bulleted menu-icon"></i>
              </a>
              <div class="collapse" id="transaction">
                <ul class="nav flex-column sub-menu">
                  <li class="nav-item">
                    <a class="nav-link" href="Purchase_Order.php">Purchase Order</a>
					<a class="nav-link" href="Sales_Invoice.php">Sales Invoive</a>
                  </li>
                </ul>
              </div>
            </li>
			
			<li class="nav-item">
              <a class="nav-link" data-bs-toggle="collapse" href="#view" aria-expanded="false" aria-controls="view">
                <span class="menu-title">View</span>
                <i class="mdi mdi-table-large menu-icon"></i>
              </a>
              <div class="collapse" id="view">
                <ul class="nav flex-column sub-menu">
                  <li class="nav-item">
                    <a class="nav-link" href="Stock.php">Stock</a>
					<a class="nav-link" href="view_po.php">PO</a>	
					<a class="nav-link" href="view_si.php">SI</a>	
                  </li>
                </ul>
              </div>
            </li>
			
          </ul>
        </nav>
        <!-- partial -->
        <div class="main-panel">
          <div class="content-wrapper">
            <div class="page-header">
              <h3 class="page-title"> Create Purchase Order </h3>
            </div>
            <div class="col-12 grid-margin">
                <div class="card">
                  <div class="card-body">
                    <form class="form-sample" method='POST'>                      
                      <div class="row">
                        <div class="col-md-6">
                          <div class="form-group row">
                            <label class="col-sm-3 col-form-label">Principal Name</label>
                            <div class="col-sm-9">
                              <select class="form-select" id="Principal_Name">
							  <option value="">None</option>
                                <?php                                                     
                                    require_once 'db_con_Maintance_Principal.php';
                                    $query = "SELECT * FROM principal WHERE STATUS=0";
                                    $result = mysqli_query($conn, $query);                                                    
                                    while($data = mysqli_fetch_assoc($result) ){                                                    
                                    echo "<option value='" . $data[Principal_Code] . "'>" . $data['Principal_Name'] . "</option>";    
                                    }						
                                ?>
                              </select>							
                            </div>								
                          </div>						  						  						 
                        </div>
                        <div class="col-md-6">
                          <div class="form-group row">
                            <label class="col-sm-3 col-form-label">Principal Code</label>
                            <div class="col-sm-9">
                              <input type="text" id="Principal_Code" class="form-control" value="<?php echo($data['Principal_Code']) ?>" disabled required />
                            </div>
                          </div>
                        </div>						
						<div class="col-md-6">
                          <div class="form-group row">
                            <label class="col-sm-3 col-form-label">PO Number</label>
                            <div class="col-sm-9">
                              <input type="text" id="PO_Number" class="form-control" value="<?php echo($random); ?>" disabled required />
                            </div>
                          </div>
                        </div>						
						<div class="col-md-6">
                          <div class="form-group row">
                            <label class="col-sm-3 col-form-label">PO Date</label>
                            <div class="col-sm-9">
                              <input type="date" id="PO_Date" class="form-control" placeholder="dd/mm/yyyy" value="<?php echo date('Y-m-d'); ?>" />
                            </div>
                          </div>
                        </div>						
                      </div>                                           
                      
					<p class="card-description"> Product Entry Section </p>
					  <div class="row">
						<div class="col-md-6">
                          <div class="form-group row">
                            <label class="col-sm-3 col-form-label">Product Name</label>
                            <div class="col-sm-9">
                              <select class="form-select" id="Product_Name">
							  <option value="0">None</option>
                                <?php                                                     
                                    require_once 'db_con_Maintance_Product.php';
                                    $query = "SELECT * FROM product WHERE STATUS=0";
                                    $result = mysqli_query($conn, $query);                                                    
                                    while($data = mysqli_fetch_assoc($result) ){                                                    
                                    echo "<option value='" . $data[Product_Code] . '|' . $data[Product_Type] . '|' . $data[Description] ."'>" . $data['Product_Name'] . "</option>";										
                                    }																										
                                ?>
                              </select>
                            </div>																				
                          </div>						  						  						 
                        </div>												                        
                        <div class="col-md-6">
                          <div class="form-group row">
                            <label class="col-sm-3 col-form-label">Product Code</label>
                            <div class="col-sm-9">
                              <input type="text" id="Product_Code" class="form-control" disabled />
                            </div>
                          </div>
                        </div>
						<div class="col-md-6">
                          <div class="form-group row">
                            <label class="col-sm-3 col-form-label">Product Type</label>
                            <div class="col-sm-9">
                              <input type="text" id="Product_Type" class="form-control" disabled />
                            </div>
                          </div>
                        </div>
					  <div class="col-md-6">
                          <div class="form-group row">
                            <label class="col-sm-3 col-form-label">Description</label>
                            <div class="col-sm-9">
                              <input type="text" id="Description" class="form-control" disabled />
                            </div>
                          </div>
                      </div>
					  <div class="col-md-6">
						<div class="form-group row">
							<label for="exampleInputName1">Purchase Price</label>
								<div class="input-group">
									<div class="input-group-prepend">
										<span class="input-group-text bg-gradient-primary text-white">Rp</span>
									</div>						
										<input type="number" min="1" class="form-control remZero" id="Purchase_Price" value=0 step="0.1" onkeyup="RemoveZero()" aria-label="Amount (to the nearest dollar)" required />
									<div class="input-group-append">
										<span class="input-group-text">.00</span>
									</div>
								</div>
						</div>
					  </div>
					  <div class="col-md-6">
						<div class="form-group row">
							<label for="exampleInputName1">Quantity</label>
								<div class="input-group">															
										<input type="number" min="1" class="form-control remZero" id="Quantity" value=0 onkeyup="RemoveZero()" aria-label="Amount (to the nearest dollar)" required />
									<div class="input-group-append">
										<span class="input-group-text">.00</span>
									</div>
								</div>
						</div>
					  </div>
					  <div class="col-md-2">
                          <div class="form-group row">
                            <button type="button" class="btn btn-gradient-primary me-2" onclick="AddItem()">Add Item</button>                            
                          </div>					
                      </div>
						<p> List Product Item Section</p>
                    <table class="table table-bordered" id="list_item">
                      <thead>
                        <tr>
                          <th>Product Code</th>
                          <th>Product Name</th>
                          <th>Product Type</th>
                          <th>Description</th>
                          <th>Price</th>
						  <th>Quantity</th>
						  <th>Total</th>
                        </tr>
                      </thead>
					  <tbody>					  
					</tbody>					
					<tfoot>
						<tr class="tr_subtotal">
							<th colspan="6">Sub Total:</th>
							<td id="subtotal">0</td>
						</tr>
					</tfoot>					
					</table>					
                 </div>
				<p> </p>
				<br>
				<p class="card-description"> Payment Type </p>
					  <div class="row">
						<div class="col-md-6">
                          <div class="form-group row">
                            <label class="col-sm-3 col-form-label">Payment Type</label>
                            <div class="col-sm-9">
                              <select class="form-select" id="Payment_Type">
                                <option>Cash</option>
                                <option>Downpayment</option>
                              </select>
                            </div>																				
                          </div>						  						  						 
                        </div>												                        
                        <div class="col-md-6">
                          <div class="form-group row">
                            <label class="col-sm-3 col-form-label"></label>							
                            <div class="col-sm-4">
                              <div class="form-check rButton" style="display:none;">
                                <label class="form-check-label">
                                  <input type="radio" class="form-check-input" name="radio_name" id="R_Nominal" value="" checked> Nominal </label>
                              </div>
                            </div>
                            <div class="col-sm-5">
                              <div class="form-check rButton" style="display:none;">
                                <label class="form-check-label">
                                  <input type="radio" class="form-check-input" name="radio_name" id="R_Percentage" value="option2"> Percentage </label>
                              </div>
                            </div>							
                          </div>
                        </div>		
						<div class="col-md-6">
						<div class="form-group row">
							<label for="exampleInputName1">Amount</label>
								<div class="input-group">
									<div class="input-group-prepend">
										<span class="input-group-text bg-gradient-primary text-white">Rp</span>
									</div>						
										<input type="number" min="1" class="form-control remZero1" id="Amount" onkeyup="RemoveZero1()" value=0 aria-label="Amount (to the nearest dollar)" disabled required />
									<div class="input-group-append">
										<span class="input-group-text">.00</span>
									</div>
								</div>
						</div>
						</div>											  					 				
						<div class="col-md-6">
						<div class="form-group row">
							<label for="exampleInputName1">Value</label>
								<div class="input-group">
									<div class="input-group-prepend">
										<span class="input-group-text bg-gradient-primary text-white">%</span>
									</div>						
										<input type="number" min="1" max="99" class="form-control remZero1" onkeyup="RemoveZero1()" id="Percentage" value=0 aria-label="Amount (to the nearest dollar)" disabled required />									
								</div>
						</div>
						</div>												
                      </div>
				 
					  <button type="submit" class="btn btn-gradient-primary me-2 postsubmit">Submit</button>
                      <button class="btn btn-light">Cancel</button>
                    </form>
                  </div>
                </div>
              </div>
          <!-- content-wrapper ends -->
          <!-- partial:../../partials/_footer.html -->
          <footer class="footer">		  
          </footer>
          <!-- partial -->
        </div>
        <!-- main-panel ends -->
      </div>
      <!-- page-body-wrapper ends -->
    </div>
    <!-- container-scroller -->
    <!-- plugins:js -->
    <script src="../../assets/vendors/js/vendor.bundle.base.js"></script>
    <!-- endinject -->
    <!-- Plugin js for this page -->
    <script src="../../assets/vendors/select2/select2.min.js"></script>
    <script src="../../assets/vendors/typeahead.js/typeahead.bundle.min.js"></script>
    <!-- End plugin js for this page -->
    <!-- inject:js -->
    <script src="../../assets/js/off-canvas.js"></script>
    <script src="../../assets/js/misc.js"></script>
    <script src="../../assets/js/settings.js"></script>
    <script src="../../assets/js/todolist.js"></script>
    <script src="../../assets/js/jquery.cookie.js"></script>
    <!-- endinject -->
    <!-- Custom js for this page -->
    <script src="../../assets/js/file-upload.js"></script>
    <script src="../../assets/js/typeahead.js"></script>
    <script src="../../assets/js/select2.js"></script>
    <!-- End custom js for this page -->
  </body>
</html>
<?php	
	include 'session_validate.php'; // cek session validate	
?>
