<?php
	include"../../connect/db.php";

	$user = $_POST['user'];

	// Fetch code_count from users table
	$userSql = mysqli_query($con, "SELECT code_count FROM users WHERE account_num = '$user'");
	$code_count = 6; // default
	if ($userSql && mysqli_num_rows($userSql) > 0) {
		$userRow = mysqli_fetch_assoc($userSql);
		$code_count = isset($userRow['code_count']) ? (int)$userRow['code_count'] : 6;
		$code_count = max(1, min(6, $code_count));
	}

	$sql = mysqli_query($con,"SELECT * FROM code WHERE user = '$user' ");

	$row = mysqli_fetch_assoc($sql);

	echo '<div class="row"><div class="col-sm-2"></div><div style="text-align:center" class="col-sm-8">';

	for ($i = 1; $i <= $code_count; $i++) {
		$codeVal = isset($row["code$i"]) ? $row["code$i"] : '';
		echo '
		<div class="row">
			<div class="col-md-8">
				<div class="form-group">
					<label for="">CODE ' . $i . '</label>
					<input class="form-control" type="text" name="code' . $i . '" value="' . $codeVal . '">
				</div>
			</div>
			<div class="col-md-4"> <span class="btn btn-sm btn-success" onclick="codeUpdate' . $i . '(\'' . $user . '\',\'code' . $i . '\')">Update</span> </div>
		</div><br>';
	}

	echo '</div><div class="col-sm-2"></div></div>';
?>