<?php
session_start();
$_SESSION['ticl_admin_id']=14;
$_SESSION['ticl_login_admin']='admin';
$_SESSION['ticl_user_type']='admin';

//error_reporting(E_ERROR | E_WARNING | E_PARSE);
error_reporting(E_ALL ^ (E_NOTICE | E_WARNING | E_DEPRECATED));
		
include 'head.php';
include('xcrud/xcrud.php');
$xcrud = Xcrud::get_instance();
echo Xcrud::load_css(); 
//include 'nav.php';
$bdd=new DB();
$values=array();
$transporter_rows = $bdd->getAll("SELECT * FROM transporter",$values);
$product_rows = $bdd->getAll("SELECT * FROM product",$values);
?>
<div class="content-wrapper">
	<section class="content-header">
		<div class="myBoxCss"><span style="font-size: large;">Add Truck</span> <span style="float: right;font-weight: bold;"><a href="Sample.xlsx" download>Download Sample Excel File</a></span></div>
    </section>
    <section class="content">   
		<div class="container-fluid">	
			<div class="row">
				<div class="myContainer col-md-12">
					<div class="col-md-2">
						<input type="date" class="form-control" id="bill_date">
					</div>
					<div class="col-md-2">
						<input type="text" class="form-control" id="invoice_no" placeholder="Invoice No" required>
					</div>
					<div class="col-md-2">
						<div class="my-custom-select">
							<select id="transporter" required>
								<option value="">Transporter</option>
<?php
foreach($transporter_rows as $row){
echo "<option value='{$row['id']}'>{$row['name']}</option>";
}
?>
							</select>
						</div>
						<!--<input type="text" class="form-control" id="transporter" placeholder="Transporter" required>-->
					</div>
					<div class="col-md-2">
						<input type="text" class="form-control" id="truck_no" placeholder="Truck No" required>
					</div>
					<div class="col-md-2">
						<input type="text" class="form-control" id="contact_number" placeholder="Contact No" required>
					</div>
					
					<div class="col-md-2">
						<div class="my-custom-select">
							<select id="vehicleDropdown">
								<option value="">Model</option>
<?php
foreach($product_rows as $row){
	echo "<option value='{$row['Id']}'>{$row['name']}</option>";
}
?>
							</select>
						</div>
					</div>
					
					<div class="col-md-12">
						<div id="selectedVehicles"></div>
					</div>
					
					<div class="col-md-12">
						<div class="my-vertical-center">
							<button id="submitBtn" class="my-submit-btn">SAVE</button>
						</div>
					</div>
				</div>
				<!--<form id="myForm" method="post" class="form-inline">
					<div class="form-group">
						<label for="class="form-inline"">Bill No</label>
						<input type="text" name="bill_no" class="form-control" id="bill_no" placeholder="Bill No." required>
					</div>
					
					<div class="form-group">
						<label for="class="form-inline"">Truck No</label>
						<input type="text" name="TruckNo" class="form-control" id="TruckNo" placeholder="TruckNo" required>
					</div>
					
					<div class="form-group">
						<label for="class="form-inline">Date</label>
						<input type="date" name="Date" class="form-control" id="Date" placeholder="Date" required>
					</div>
					
					<div class="form-group">
						<label for="class="form-inline">Excel file</label>
						<input type="file" name="excel_file" class="form-control" id="excel_file" required>
					</div>
					
					
					<div class="row" style="margin-top:10px">
						<div class="col-md-12 text-center">
						  <input type="submit" class="btn btn-primary mb-3" value="Submit">
						  <button type="button" class="btn btn-danger mb-3" onclick="window.location.reload()">Refresh</button>
						</div>
					</div>
				</form> -->

				<input type="hidden" name="TruckID" id="TruckID">
				<div id="truckTableContainer"></div>
			</div>
			
			<div class="row" style="margin-top:5px">
				<div class="box">
					<div class="table-responsive">
					<table class="table table-bordered table-hover" id="truck_detail_table">
						<thead>
							<tr style='background-color: antiquewhite;'><th>Date</th><th>Invoice No.</th><th>Transporter</th><th>Truck No</th><th>Contact No</th><th>Detail</th></tr>
						</thead>
						<tbody>

<?php
/*$values=array();
$model_rows = $bdd->getAll("SELECT * FROM model",$values);
foreach($model_rows as $row){
	echo "<option value='{$row['id']}'>{$row['name']}</option>";
}*/

$values=array();
$transit_vehicle_rows = $bdd->getAll("SELECT tv.*,t.name as transporter_name FROM transit_vehicle tv LEFT JOIN transporter as t ON tv.transporter=t.id WHERE tv.status='Pending' ORDER BY tv.id DESC",$values);
foreach($transit_vehicle_rows as $row){
	$model_str="<table class='table table-bordered'>";
	$values=array($row['id']);
	$model_rows = $bdd->getAll("SELECT p.name as product_name,tv.qty FROM transit_vehicle_data as tv LEFT JOIN product as p ON tv.model=p.id WHERE tv.tv_id=?",$values);
	foreach($model_rows as $mrow){
		$model_str.="<tr style='background-color: aliceblue;'><td>{$mrow['product_name']}</td><td>{$mrow['qty']}</td></tr>";
	}
	$model_str.="<tr><td><form method='post' action='AddTruckProcess.php' enctype='multipart/form-data'><input type='hidden' name='hidden_id' value='{$row['id']}'><input type='hidden' name='bill_no' value='{$row['bill_no']}'><input type='hidden' name='TruckNo' value='{$row['truck_no']}'><input type='hidden' name='Date' value='{$row['date']}'><input type='file' class='btn btn-primary' name='excel_file' accept='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel' required></td><td><button type='submit' class='btn btn-success'>Upload file</button><button type='button' class='btn btn-danger' style='float: right;' onClick='deleteRecord(this)' data-id='{$row['id']}'><i class='fa fa-trash'></i></button></form></td></tr></table>";
	echo "<tr><td>".date('d-m-Y', strtotime($row['date']))."</td><td>{$row['bill_no']}</td><td>{$row['transporter_name']}</td><td>{$row['truck_no']}</td><td>{$row['contact_no']}</td><td>$model_str</td></tr>";
}
?>

					  </tbody>
				  </table>
				  </div>
			  </div>
			</div>
		</div>
    </section>
</div>
<?php
include 'footer.php';
?>
<script>
function deleteRecord(ele){
	//console.log(ele.dataset.id);
	dataString='action=deleteTransitVehicle&id='+ele.dataset.id;
	$.ajax({
		type:'POST',
		async: true,
		url:'ajax_data.php',
		data:dataString,
		success:function(data){
			//$(".loader-div").hide();
			//$(el).closest("tr").remove();
			//clearSearch()
			location.reload();
		},
		error: function () {
			//$(".loader-div").hide();
		}
	});
}
document.getElementById('vehicleDropdown').addEventListener('change', function() {
	let vehicleName = this.value;
	let vehicleText = this.options[this.selectedIndex].text;
	if (vehicleName === "") return;

	let container = document.getElementById('selectedVehicles');

	// Create a wrapper div for the vehicle inputs
	let div = document.createElement('div');
	div.classList.add('my-input-group');

	// Create the vehicle name input (readonly)
	let vehicleInput = document.createElement('input');
	vehicleInput.type = 'text';
	vehicleInput.value = vehicleText;
	vehicleInput.readOnly = true;
	vehicleInput.classList.add('vehicle-name');
	
	// Create the vehicle name input (readonly)
	let vehicleInputHidden = document.createElement('input');
	vehicleInputHidden.type = 'hidden';
	vehicleInputHidden.value = vehicleName
	vehicleInputHidden.readOnly = true;
	vehicleInputHidden.classList.add('vehicle-id');

	// Create the quantity input
	let quantityInput = document.createElement('input');
	quantityInput.type = 'number';
	quantityInput.placeholder = 'Quantity';
	quantityInput.min = 1;
	quantityInput.classList.add('vehicle-quantity');
	//quantityInput.attributes.required = "required";
	quantityInput.required = true;

	// Create the remove button
	let removeButton = document.createElement('button');
	removeButton.innerText = 'Remove';
	removeButton.classList.add('my-remove-btn');
	removeButton.addEventListener('click', function() {
		container.removeChild(div);
	});

	// Append elements to div
	div.appendChild(vehicleInputHidden);
	div.appendChild(vehicleInput);
	div.appendChild(quantityInput);
	div.appendChild(removeButton);

	// Append div to container
	container.appendChild(div);

	// Reset dropdown to default
	this.value = "";
});

document.getElementById('submitBtn').addEventListener('click', function() {
	let valid_flag=true;
	let bill_date = document.getElementById('bill_date').value;
	let invoice_no = document.getElementById('invoice_no').value;
	let transporter = document.getElementById('transporter').value;
	let truck_no = document.getElementById('truck_no').value;
	let contact_number = document.getElementById('contact_number').value;
	
	if (bill_date == "" || invoice_no == "" || transporter == "" || truck_no == "" || contact_number == "") {
		alert("Please fill form!");
		valid_flag=false;
		return;
	}
	
	let vehicleData = [];
	
	vehicleData.push({bill_date: bill_date, invoice_no: invoice_no, transporter: transporter, truck_no: truck_no,  contact_number: contact_number});
	
	vehicleData.push([]);
	document.querySelectorAll('.my-input-group').forEach(group => {
		let vehicleId = group.querySelector('.vehicle-id').value;
		let vehicleName = group.querySelector('.vehicle-name').value;
		let quantity = group.querySelector('.vehicle-quantity').value;

		if (quantity !="") {
			vehicleData[1].push({ id: vehicleId, vehicle: vehicleName, quantity: quantity });
		}else{
			alert("Please add at least one vehicle with quantity!");
			valid_flag=false;
			return;
		}
	});

	if (vehicleData[1].length === 0) {
		alert("Please add at least one vehicle model with quantity!");
		valid_flag=false;
		return;
	}

	if (valid_flag){
		let jsonData = JSON.stringify(vehicleData);
		//console.log(jsonData);
		dataString='action=transitVehicle&jsonData='+jsonData;
		$.ajax({
			type:'POST',
			url:'ajax_data.php',
			data:dataString,
			success:function(response){
				console.log(response);
				value=JSON.parse(response);
				if(value.status=="error")
					alert(value.message)
				else
					//alert('done');
					//window.location.href = "InGodown.php?page=1";
					location.reload();
			}
		});
	}
});
		
$(document).ready(function() {
	$.noConflict();
	$('#truck_detail_table').DataTable();
	
  $('#myForm').submit(function(event) {
    event.preventDefault();
    var formData = new FormData(this);

    $.ajax({
      type: 'POST',
      url: 'AddTruckProcess.php',
      data: formData, // Use the FormData object
      processData: false, // Don't process data (needed for FormData)
      contentType: false, // Don't set content type (automatically set to multipart/form-data)
      success: function(response) {
        console.log(response);

        /*var responseParts = response.split('|');
        var truckID = responseParts[0];
        var tableHTML = responseParts[1];

        // Display the table
        $('#truckTableContainer').html(tableHTML);

        // Append the "Add" button
        var addButtonHtml = '<button id="addButton" class="btn btn-primary">Add New</button>';
        $('#truckTableContainer').append(addButtonHtml);

        // Set the truckID in the hidden input field
        $('#TruckID').val(truckID);

        // Disable the input and date fields
        $('#TruckNo').prop('disabled', true);
        $('#Date').prop('disabled', true);

        // Handle the "Add" button click event
        $('#addButton').click(function() {
          // Show the input fields and insert button
          showInputFields();
        });*/
        value=JSON.parse(response);
		if(value.status=="error")
			alert(value.message)
		else
			window.location.href = "InGodown.php?page=1";
      },
      error: function(xhr, status, error) {
        // Handle AJAX error
        console.log(error);
      }
    });
  });
});
</script>
<?php
$bdd->disconnect();
echo Xcrud::load_js();
?>
