<?php
// Fetch invoice details if edit is triggered
if (isset($_GET['edit_invoice']) && isset($_GET['update_id'])) {
    $invoice_id = inject_checker($connection, $_GET['update_id']);

    // Fetch invoice data
    $stmt = $connection->prepare("SELECT * FROM `invoice_order` WHERE `invoice_id` = ?");
    $stmt->bind_param("i", $invoice_id);
    $stmt->execute();
    $invoiceResult = $stmt->get_result();

    if ($invoiceResult && $invoiceResult->num_rows > 0) {
        $invoiceData = $invoiceResult->fetch_assoc();

        $receiverID = $invoiceData['receiver_id'] ?? '';
        $receiverName = $invoiceData['receiver_name'] ?? '';
        $receiverClass = $invoiceData['receiver_class'] ?? '';
        $note = $invoiceData['note'] ?? '';
        $subTotal = $invoiceData['sub_total'] ?? 0;
        $amountPaid = $invoiceData['total_amount_paid'] ?? 0;
        $amountDue = $invoiceData['total_amount_due'] ?? 0;
        $term = $invoiceData['term'] ?? $current_term;
        $session = $invoiceData['session'] ?? $current_session;

        // Fetch invoice items
        $stmtItems = $connection->prepare("SELECT * FROM `invoice_item_order` WHERE `invoice_id` = ?");
        $stmtItems->bind_param("i", $invoice_id);
        $stmtItems->execute();
        $itemsResult = $stmtItems->get_result();

        $invoiceItems = [];
        while ($item = $itemsResult->fetch_assoc()) {
            $invoiceItems[] = $item;
        }

    } else {
        $_SESSION['msg'] = "Invoice not found.";
        $_SESSION['type'] = "danger";
        header("Location: view_invoice");
        exit();
    }
}

// Handle form submission to update invoice
if (isset($_POST['edit_invoice_btn'])) {
    $invoice_id = inject_checker($connection, $_POST['invoice_id']); // Hidden input for invoice_id

    // Sanitize inputs
    $receiverName = inject_checker($connection, $_POST['studentName']);
    $receiverID = inject_checker($connection, $_POST['reg_number']);
    $receiverClass = inject_checker($connection, $_POST['studentClass']);
    $subTotal = floatval($_POST['subTotal']);
    $amountPaid = floatval($_POST['amountPaid']);
    $amountDue = floatval($_POST['amountDue']);
    $note = inject_checker($connection, $_POST['notes']);
    $orderDate = date('Y-m-d');
    $term = $current_term;
    $session = $current_session;

    // Update main invoice
    $stmtUpdate = $connection->prepare("UPDATE `invoice_order` SET order_date=?, receiver_name=?, receiver_id=?, receiver_class=?, sub_total=?, total_amount_paid=?, total_amount_due=?, note=?, term=?, session=? WHERE invoice_id=?");
    $stmtUpdate->bind_param("ssssdddsssi", $orderDate, $receiverName, $receiverID, $receiverClass, $subTotal, $amountPaid, $amountDue, $note, $term, $session, $invoice_id);
    
    if ($stmtUpdate->execute()) {
        // Delete old items
        $stmtDel = $connection->prepare("DELETE FROM `invoice_item_order` WHERE `invoice_id` = ?");
        $stmtDel->bind_param("i", $invoice_id);
        $stmtDel->execute();

        // Re-insert updated items
        $stmtInsert = $connection->prepare("INSERT INTO `invoice_item_order` (invoice_id, item_name, item_quantity, item_price, item_final_amount) VALUES (?, ?, ?, ?, ?)");
        for ($j = 0; $j < count($_POST['productName']); $j++) {
            $itemName = inject_checker($connection, $_POST['productName'][$j]);
            $itemQuantity = intval($_POST['quantity'][$j]);
            $itemPrice = floatval($_POST['price'][$j]);
            $itemTotal = floatval($_POST['total'][$j]);

            $stmtInsert->bind_param("isidd", $invoice_id, $itemName, $itemQuantity, $itemPrice, $itemTotal);
            if (!$stmtInsert->execute()) {
                $_SESSION['msg'] = "Error updating item: " . $stmtInsert->error;
                $_SESSION['type'] = "danger";
                header("Location: view_invoice");
                exit();
            }
        }

        $_SESSION['msg'] = "Invoice has been successfully updated!";
        $_SESSION['type'] = "success";
        header("Location: view_invoice");
        exit();

    } else {
        $_SESSION['msg'] = "Error updating invoice: " . $stmtUpdate->error;
        $_SESSION['type'] = "danger";
        header("Location: view_invoice");
        exit();
    }
}
?>

<div class='card'>
	<div class='panel panel-primary'>
		<div class='panel-heading'>
			<h4 class='text-center'>Edit Invoice</h4>
		</div>
		<form action="" id="invoice-form" method="post" class="invoice-form" role="form">
			<input type="hidden" name="invoice_hidden_id" value="<?php echo htmlspecialchars($invoice_id); ?>">

			<div class="row">
				<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4">
					<h3>From,</h3>
					<?php echo htmlspecialchars($school_name); ?><br>
					<?php echo htmlspecialchars($schoo_motto); ?><br>
					<?php echo htmlspecialchars($current_term); ?><br>
					<?php echo htmlspecialchars($current_session); ?><br>
				</div>
				<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4 pull-right">
					<h3>To,</h3>
					<div class="form-group">
						<input type="text" class="form-control" name="invoice_id" id="invoice_id"
							   value="<?php echo htmlspecialchars($invoice_id); ?>" readonly>
					</div>
					<div class="form-group">
						<input type="text" class="form-control" name="reg_number" id="reg_number"
							   value="<?php echo htmlspecialchars($receiverID); ?>" readonly>
					</div>
					<div class="form-group">
						<input type="text" class="form-control" name="studentName" id="studentName"
							   value="<?php echo htmlspecialchars($receiverName); ?>" readonly>
					</div>
					<div class="form-group">
						<input type="text" class="form-control" name="studentClass" id="studentClass"
							   value="<?php echo htmlspecialchars($receiverClass); ?>" 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="form-control" 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>
						<?php
						if (!empty($invoiceItems)) { // Use $invoiceItems to match the fetched data
							$i = 1;
							foreach ($invoiceItems as $item) { // Use $invoiceItems here
								echo "<tr>
										<td><input class='itemRow' type='checkbox'></td>
										<td><input type='text' name='productCode[]' class='form-control' value='" . htmlspecialchars($item['item_code']) . "'></td>
										<td><input type='text' name='productName[]' class='form-control' value='" . htmlspecialchars($item['item_name']) . "'></td>
										<td><input type='number' name='quantity[]' class='form-control' value='" . htmlspecialchars($item['item_quantity']) . "'></td>
										<td><input type='number' name='price[]' class='form-control' value='" . htmlspecialchars($item['item_price']) . "'></td>
										<td><input type='number' name='total[]' class='form-control' value='" . htmlspecialchars($item['item_final_amount']) . "'></td>
									  </tr>";
								$i++;
							}
						}
						?>
					</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"><?php echo htmlspecialchars($note); ?></textarea>
					</div>
					<br>
					<div class="form-group">
						<input type="submit" name="edit_invoice_btn" value="Update Invoice" class="btn btn-success submit_btn">
					</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:</label>
							<div class="input-group">
								<div class="input-group-addon currency">₦</div>
								<input type="number" class="form-control" name="subTotal" id="subTotal" value="<?php echo htmlspecialchars($subTotal); ?>">
							</div>
						</div>
						<div class="form-group">
							<label>Amount Paid:</label>
							<div class="input-group">
								<div class="input-group-addon currency">₦</div>
								<input type="number" class="form-control" name="amountPaid" id="amountPaid"value="<?php echo htmlspecialchars($amountPaid); ?>">
							</div>
						</div>
						<div class="form-group">
							<label>Amount Due:</label>
							<div class="input-group">
								<div class="input-group-addon currency">₦</div>
								<input type="number" class="form-control" name="amountDue" id="amountDue" value="<?php echo htmlspecialchars($amountDue); ?>">
							</div>
						</div>
					</span>
				</div>
			</div>
			<div class="clearfix"></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>	
