jQuery(function ($) {

	$('.appointment-status').on('change', function () {

		let select = $(this);
		let id = select.data('id');
		let status = parseInt(select.val());
		let oldVal = select.data('current');

		// 🚫 Restrict Cancelled (2)
		if (status === 2) {
			Swal.fire({
				icon: 'info',
				title: 'Restricted',
				text: 'Cancelled status is available in Pro version.'
			});
			select.val(oldVal);
			return;
		}

		Swal.fire({
			title: 'Are you sure?',
			text: "Do you want to change status?",
			icon: 'warning',
			showCancelButton: true,
			confirmButtonText: 'Yes, update it!'
		}).then((result) => {

			if (result.isConfirmed) {

				$.post(ssasAppointmentStatus.ajaxurl, {
					action: 'ssas_update_appointment_status',
					id: id,
					status: status,
					nonce: ssasAppointmentStatus.nonce
				}, function (response) {

					if (response.success) {
						Swal.fire('Updated!', 'Status updated successfully.', 'success');
						select.data('current', status);
					} else {
						Swal.fire('Error!', 'Update failed.', 'error');
						select.val(oldVal);
					}

				}).fail(function () {
					Swal.fire('Error!', 'Server error.', 'error');
					select.val(oldVal);
				});

			} else {
				select.val(oldVal);
			}
		});
	});

	// ✅ Store initial value
	$('.appointment-status').each(function () {
		$(this).data('current', parseInt($(this).val()));
	});

});
