<?php
if (isset($_POST['invoice_btn'])) {
    // Sanitize and collect invoice details
    $receiverName = inject_checker($connection, $_POST['studentName']);
    $receiverID = inject_checker($connection, $_POST['reg_number']);
    $receiverClass = inject_checker($connection, $_POST['studentClass']);
    $subTotal = inject_checker($connection, $_POST['subTotal']);
    $amountPaid = inject_checker($connection, $_POST['amountPaid']);
    $amountDue = inject_checker($connection, $_POST['amountDue']);
    $note = inject_checker($connection, $_POST['notes']);
    $term = $current_term;
    $session = $current_session;
    $orderDate = date('Y-m-d');
    $invoiceID = uniqid("INV_");

    // Start transaction
    $connection->begin_transaction();

    try {
        // Insert invoice header
        $invoiceOrderQuery = "INSERT INTO invoice_order 
            (order_date, receiver_name, invoice_id, receiver_id, receiver_class, sub_total, total_amount_paid, total_amount_due, note, term, session) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        
        $stmt = $connection->prepare($invoiceOrderQuery);
        $stmt->bind_param("sssssssssss", $orderDate, $receiverName, $invoiceID, $receiverID, $receiverClass, $subTotal, $amountPaid, $amountDue, $note, $term, $session);
        $stmt->execute();

        // Insert invoice items
        $itemQuery = "INSERT INTO invoice_item_order 
            (invoice_id, item_name, item_quantity, item_price, item_final_amount) 
            VALUES (?, ?, ?, ?, ?)";
        $stmtItem = $connection->prepare($itemQuery);

        for ($j = 0; $j < count($_POST['productName']); $j++) {
            $itemName = inject_checker($connection, $_POST['productName'][$j]);
            $itemQuantity = inject_checker($connection, $_POST['quantity'][$j]);
            $itemPrice = inject_checker($connection, $_POST['price'][$j]);
            $itemTotal = inject_checker($connection, $_POST['total'][$j]);

            $stmtItem->bind_param("ssddd", $invoiceID, $itemName, $itemQuantity, $itemPrice, $itemTotal);
            $stmtItem->execute();
        }

        // Commit transaction
        $connection->commit();

        $_SESSION['msg'] = "Invoice saved successfully!";
        $_SESSION['type'] = "success";
    } catch (Exception $e) {
        $connection->rollback();
        $_SESSION['msg'] = "Failed to save invoice: " . $e->getMessage();
        $_SESSION['type'] = "danger";
    }

    header("Location: view_invoice");
    exit();
}
?>

<div class='card'>
    <div class='panel panel-primary'>
        <div class='panel-heading'>
            <h4 class='text-center'>New Invoice</h4>
        </div>
		<form action="" id="invoice-form" method="post" class="invoice-form" role="form" novalidate=""> 
			<input id="currency" type="hidden" value="₦">
			<div class="row">
				<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4">
					<h3>From,</h3>
					<?php echo $admin_name; ?><br>	
					<?php echo $admin_motto; ?><br>	
					<?php echo $current_term; ?><br>
					<?php echo $current_session; ?><br>			
				</div>      		
				<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4 pull-right">
					<h3>To,</h3>
					<!-- Invoice ID Input -->
					<div class="form-group">
						<input type="text" class="form-control" name="invoiceID" id="invoiceID" 
							   placeholder="Invoice ID" value="<?php echo uniqid('INV_'); ?>" readonly>
					</div>
					<div class="form-group">
						<input type="text" class="form-control" name="reg_number" id="reg_number" 
							   placeholder="Student Reg No" onchange="fetchStudentDetails(this.value)">
					</div>
					<div class="form-group">
						<input type="text" class="form-control" name="studentName" id="studentName" 
							   placeholder="Student Name" readonly>
					</div>
					<div class="form-group">
						<input type="text" class="form-control" name="studentClass" id="studentClass" 
							   placeholder="Student Class" readonly>
					</div>
				</div>
			</div>
			<div class="row">
				<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
					<table class="table table-bordered table-hover" id="invoiceItem">	
						<tr>
							<th width="2%"><input id="checkAll" class="formcontrol" type="checkbox"></th>
							<th width="15%">Item No</th>
							<th width="30%">Item Name</th>
							<th width="15%">Quantity</th>
							<th width="15%">Price</th>								
							<th width="15%">Total</th>
						</tr>							
						<tr>
							<td><input class="itemRow" type="checkbox"></td>
							<td><input type="text" name="productCode[]" id="productCode_1" class="form-control" autocomplete="off"></td>
							<td><input type="text" name="productName[]" id="productName_1" class="form-control" autocomplete="off"></td>			
							<td><input type="number" name="quantity[]" id="quantity_1" class="form-control quantity" autocomplete="off"></td>
							<td><input type="number" name="price[]" id="price_1" class="form-control price" autocomplete="off"></td>
							<td><input type="number" name="total[]" id="total_1" class="form-control total" autocomplete="off"></td>
						</tr>						
					</table>
				</div>
			</div>
			<div class="row">
				<div class="col-xs-12 col-sm-3 col-md-3 col-lg-3">
					<button class="btn btn-danger delete" id="removeRows" type="button">- Delete</button>
					<button class="btn btn-success" id="addRows" type="button">+ Add More</button>
				</div>
			</div>
			<div class="row">	
				<div class="col-xs-12 col-sm-8 col-md-8 col-lg-8">
					<h3>Notes: </h3>
					<div class="form-group">
						<textarea class="form-control txt" rows="5" name="notes" id="notes" placeholder="Your Notes"></textarea>
					</div>
					<br>
					<div class="form-group">
						<input data-loading-text="Saving Invoice..." type="submit" name="invoice_btn" value="Save Invoice" class="btn btn-success submit_btn invoice-save-btm">						
					</div>
					
				</div>
				<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4">
					<span class="form-inline">
						<div class="form-group">
							<label>Subtotal:  &nbsp; &nbsp; &nbsp; &nbsp;</label>
							<div class="input-group">
								<div class="input-group-addon currency">₦</div>
								<input value="" type="number" class="form-control" name="subTotal" id="subTotal" placeholder="Subtotal">
							</div>
						</div>					
						<div class="form-group">
							<label>Amount Paid:</label>
							<div class="input-group">
								<div class="input-group-addon currency">₦</div>
								<input value="" type="number" class="form-control" name="amountPaid" id="amountPaid" placeholder="Amount Paid">
							</div>
						</div>
						<div class="form-group">
							<label>Amount Due: &nbsp;</label>
							<div class="input-group">
								<div class="input-group-addon currency">₦</div>
								<input value="" type="number" class="form-control" name="amountDue" id="amountDue" placeholder="Amount Due">
							</div>
						</div>
					</span>
				</div>
			</div>
			<div class="clearfix"></div>		      	
		</div>
	</form>			
</div>
</div>	

<script>
   $(document).ready(function(){
	$(document).on('click', '#checkAll', function() {          	
		$(".itemRow").prop("checked", this.checked);
	});	
	$(document).on('click', '.itemRow', function() {  	
		if ($('.itemRow:checked').length == $('.itemRow').length) {
			$('#checkAll').prop('checked', true);
		} else {
			$('#checkAll').prop('checked', false);
		}
	});  
	var count = $(".itemRow").length;
	$(document).on('click', '#addRows', function() { 
		count++;
		var htmlRows = '';
		htmlRows += '<tr>';
		htmlRows += '<td><input class="itemRow" type="checkbox"></td>';          
		htmlRows += '<td><input type="text" name="productCode[]" id="productCode_'+count+'" class="form-control" autocomplete="off"></td>';          
		htmlRows += '<td><input type="text" name="productName[]" id="productName_'+count+'" class="form-control" autocomplete="off"></td>';	
		htmlRows += '<td><input type="number" name="quantity[]" id="quantity_'+count+'" class="form-control quantity" autocomplete="off"></td>';   		
		htmlRows += '<td><input type="number" name="price[]" id="price_'+count+'" class="form-control price" autocomplete="off"></td>';		 
		htmlRows += '<td><input type="number" name="total[]" id="total_'+count+'" class="form-control total" autocomplete="off"></td>';          
		htmlRows += '</tr>';
		$('#invoiceItem').append(htmlRows);
	}); 
	$(document).on('click', '#removeRows', function(){
		$(".itemRow:checked").each(function() {
			$(this).closest('tr').remove();
		});
		$('#checkAll').prop('checked', false);
		calculateTotal();
	});		
	$(document).on('blur', "[id^=quantity_]", function(){
		calculateTotal();
	});	
	$(document).on('blur', "[id^=price_]", function(){
		calculateTotal();
	});	
	$(document).on('blur', "#taxRate", function(){		
		calculateTotal();
	});	
	$(document).on('blur', "#amountPaid", function(){
		var amountPaid = $(this).val();
		var subTotal = $('#subTotal').val();	
		if(amountPaid && subTotal) {
			subTotal = subTotal-amountPaid;			
			$('#amountDue').val(subTotal);
		} else {
			$('#amountDue').val(subTotal);
		}	
	});	
	$(document).on('click', '.deleteInvoice', function(){
		var id = $(this).attr("id");
		if(confirm("Are you sure you want to remove this?")){
			$.ajax({
				url:"action.php",
				method:"POST",
				dataType: "json",
				data:{id:id, action:'delete_invoice'},				
				success:function(response) {
					if(response.status == 1) {
						$('#'+id).closest("tr").remove();
					}
				}
			});
		} else {
			return false;
		}
	});
});	
function calculateTotal(){
	var totalAmount = 0; 
	$("[id^='price_']").each(function() {
		var id = $(this).attr('id');
		id = id.replace("price_",'');
		var price = $('#price_'+id).val();
		var quantity  = $('#quantity_'+id).val();
		if(!quantity) {
			quantity = 1;
		}
		var total = price*quantity;
		$('#total_'+id).val(parseFloat(total));
		totalAmount += total;			
	});
	$('#subTotal').val(parseFloat(totalAmount));	
	var subTotal = $('#subTotal').val();	
	if(subTotal) {	
		var amountPaid = $('#amountPaid').val();
		var totalAftertax = $('#subTotal').val();	
		if(amountPaid && subTotal) {
			subTotal = subTotal-amountPaid;			
			$('#amountDue').val(subTotal);
		} else {		
			$('#amountDue').val(totalAftertax);
		}
	}
}


function fetchStudentDetails(regNumber) {
    if (regNumber !== "") {
        // Create AJAX request
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "fetch_student_details.php", true); // Update with the correct path to your PHP script
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                var response = JSON.parse(xhr.responseText); // Parse JSON response
                
                if (response.status === "success") {
                    // Populate fields with student details
                    document.getElementById("studentName").value = response.fullname;
                    document.getElementById("studentClass").value = response.class;
                } else {
                    // Handle errors
                    alert(response.message);
                    document.getElementById("studentName").value = "";
                    document.getElementById("studentClass").value = "";
                }
            }
        };

        // Send request with reg_number
        xhr.send("reg_number=" + encodeURIComponent(regNumber));
    } else {
        alert("Please enter a registration number.");
        document.getElementById("studentName").value = "";
        document.getElementById("studentClass").value = "";
    }
}
</script>
