add_action('wp_footer', function () {
    if (is_singular('service') && !is_user_logged_in()) {
        ?>
        <script>
            document.addEventListener('DOMContentLoaded', function() {
				const buyBtn = document.querySelector('.service-price .btn');
				if (buyBtn) {
					buyBtn.addEventListener('click', function(e) {
						if (!document.body.classList.contains('logged-in')) {
							e.preventDefault();

							// Check if the message already exists
							if (!document.querySelector('.login-warning')) {
								const msg = document.createElement('div');
								msg.className = 'login-warning';
								msg.style.color = 'red';
								msg.style.marginTop = '10px';
								msg.innerHTML = "⚠️ Vous devez vous <a href='/login/' style='color:blue; font-weight:bold; text-decoration:underline;'>connecter ici</a> avant d’acheter ce service.";

								buyBtn.insertAdjacentElement('afterend', msg);

								// Redirect automatically after 2 seconds
								setTimeout(function() {
									window.location.href = '/login/';
								}, 2000);
							}
						}
					});
				}
			});
        </script>
        <?php
    }
});
