// Modified by farhan akhtar on [27-08-2025]
$(document).ready(function() {

	$('#serviceable').on('change', function (e) {
		e.preventDefault();
		var value = $.trim($(this).val());
		var id = $('#channel_id').val();

		if (!id) {
			alert('Error: No channel ID found.');
			return;
		}

		if (parseInt(value) >= 1) {
			if (confirm("Are you sure you want to classify this?")) {
				$.ajax({
					url: 'servicable_emailqueue_popup.php',
					method: 'POST',
					data: { id: id, value: value },
					success: function (data) {
						    if (data === 'duplicate') {
								alert('This email is already classified with the selected value.');
							} else {
								alert('Classification updated successfully.');
								$.colorbox.close(); //Close the popup
								location.reload();
							}
					},
					error: function (xhr, status, error) {
						console.error('Error:', error);
						alert('An error occurred while updating. Please try again.');
					}
				});
			} else {
				// User canceled
				return false;
			}
		}
	});

	$('#create_disposition').on('click', function (e) {
		e.preventDefault();
		// alert(e)
		

		var dispostionInput = $('#dispostion_type');
		var dispostion_type = dispostionInput.length ? dispostionInput.val().trim() : '';;
		var remarks = $('#email_remark').val().trim();
		var channel_id = $('#channel_id').val().trim();
		// var send_from = $('#send_from').val().trim();
		var channel_type = $('#channel_type').val().trim();


		// Validate required fields
		if (!dispostion_type || !channel_id || !channel_type || !remarks) {
			alert('Please fill all required fields before creating the disposition.');
			return;
		}

		$.ajax({
			url: 'servicable_emailqueue_popup.php',
			method: 'POST',
			data: {
				action: 'dispostion_channel_insert',
				dispostion_type: dispostion_type,
				remarks: remarks,
				channel_id: channel_id,
				channel_type: channel_type
				// send_from: send_from
			},
			dataType:'json',
			beforeSend: function() {
				$('#create_disposition').prop('disabled', true).text('Saving...');
			},
			success: function(response) {
				try {
					if (response.status) {
						alert(response.message || 'Disposition successfully updated.');
					} else {
						alert(response.message || 'Error updating disposition.');
					}
				} catch (e) {
					// Fallback
					alert('Disposition updated.');
				}
				location.reload();
			},
			error: function(xhr, status, error) {
				console.error('Error:', error);
				alert('Error occurred while saving. Please try again.');
			},
			complete: function() {
				$('#create_disposition').prop('disabled', false).text('Dispose');
			}
		});
	});

	$('#submit_sentiment').on('click', function (e) {
		e.preventDefault();

		var sentiment = $('#sentiment').val().trim();
		var channel_type = $('#channel_type').val().trim();
		var channel_id = $('#channel_id').val().trim();

		if (!sentiment || !channel_type || !channel_id) {
			alert('Please make sure all fields are filled.');
			return;
		}

		$.ajax({
			url: 'servicable_emailqueue_popup.php',
			method: 'POST',
			data: {
				sentiment: sentiment,
				channel_type: channel_type,
				channel_id: channel_id,
				action: 'sentiment'
			},
			success: function (data) {
				// Optional: add a success toast
				alert('Sentiment updated successfully.');
				location.reload();
			},
			error: function (xhr, status, error) {
				console.error('Error:', error);
				alert('An error occurred. Please try again.');
			}
		});
	});
});

function checkAndRedirect(id, url) {
    fetch('check_mail_assignment.php?id=' + id)
        .then(res => res.json())
        .then(data => {
            if (data.assigned) {
                window.open(url, '_blank');
            } else {
                alert("First assign this mail to yourself, then you will be able to work on it.");
            }
        })
        .catch(err => {
            console.error(err);
            alert("Error checking assignment. Try again.");
        });
}
	
	