
function createTable(records) {
	if (!records.length) return '<p>No records found.</p>';
	let html = '<table class="table table-bordered table-sm">';
	html += '<thead><tr><th>Select</th>';
	Object.keys(records[0]).forEach(function (key) {
		html += '<th>' + key + '</th>';
	});
	html += '</tr></thead><tbody>';

	records.forEach(function (record) {
		html += '<tr>';
		html += '<td><input type="radio" name="ticketSelect" value="' + record.ticketid + '"></td>';
		Object.values(record).forEach(function (val) {
			html += '<td>' + val + '</td>';
		});
		html += '</tr>';
	});
	html += '</tbody></table>';
	html += '<button type="button" class="btn btn-primary mt-2" id="assignTicketBtn">Assign Ticket</button>';
	return html;
}

// When modal opens
$('#myModal').on('show.bs.modal', function (e) {
	const email = $('#openModalBtn').data('email');
	$('#modalTableBody').html('<p>Loading...</p>');

	$.ajax({
		url: 'fetchData.php',
		method: 'POST',
		data: { action: 'get_cases', email: email },
		dataType: 'json',
		success: function (records) {
			$('#modalTableBody').html(createTable(records));
		},
		error: function () {
			$('#modalTableBody').html('<p>Error loading data.</p>');
		}
	});
});

// Open modal
$('#openModalBtn').on('click', function () {
	const myModal = new bootstrap.Modal(document.getElementById('myModal'));
	myModal.show();
});

// Handle Assign Ticket
$(document).on('click', '#assignTicketBtn', function () {
	const selectedTicket = $('input[name="ticketSelect"]:checked').val();
    const Mid = $("#Mid").val();
	if (!selectedTicket) {
		alert('Please select a ticket.');
		return;
	}
	
	$.ajax({
		url: 'fetchData.php',
		method: 'POST',
		data: { action: 'assign_ticket', ticketid: selectedTicket, Mid: Mid },
		success: function (res) {
			alert('Ticket tagged successfully!');
			$('#myModal').modal('hide');
			location.reload();
		},
		error: function () {
			alert('Error tagging ticket.');
		}
	});
});
