// تشغيل الكود  اذا تحملت الصفحة
document.addEventListener('DOMContentLoaded', function() {
    initServices();
    highlightServiceFromUrl();
});

function initServices() {
    // يدور كل الخيارات للخدمه
    var options = document.querySelectorAll('.service-option, .quantity-field');
    for (var i = 0; i < options.length; i++) {
        options[i].addEventListener('change', function() {
            var serviceCard = this.closest('.enhanced-service-card');
            updateServicePrice(serviceCard);
        });
    }
}

function updateServicePrice(serviceCard) {
    var basePriceElement = serviceCard.querySelector('.total-price');
    var basePrice = parseFloat(basePriceElement.dataset.basePrice);
    var quantityField = serviceCard.querySelector('.quantity-field');
    var qty = quantityField ? parseFloat(quantityField.value) || 1 : 1;

    var totalPrice = basePrice * qty;

    // يحسب إضافات الخيارات
    var selects = serviceCard.querySelectorAll('.service-option');
    for (var i = 0; i < selects.length; i++) {
        var select = selects[i];
        var selectedOption = select.options[select.selectedIndex];
        var priceModifier = parseFloat(selectedOption.dataset.price) || 0;
        totalPrice += priceModifier * qty;
    }

    basePriceElement.textContent = totalPrice.toFixed(2);
}

function addServiceToCart(serviceId) {
    var serviceCard = document.querySelector('[data-service-id="' + serviceId + '"]');
    var quantityField = serviceCard.querySelector('.quantity-field');
    var quantity = quantityField ? parseFloat(quantityField.value) || 1 : 1;

    if (quantity < 1) {
        quantity = 1;
        if (quantityField) {
            quantityField.value = 1;
        }
    }

    var selectedOptions = {};
    var selects = serviceCard.querySelectorAll('.service-option');
    for (var i = 0; i < selects.length; i++) {
        var select = selects[i];
        var optionType = select.dataset.optionType;
        var selectedOption = select.options[select.selectedIndex];
        selectedOptions[optionType] = {
            id: selectedOption.value,
            name: selectedOption.text,
            price_modifier: parseFloat(selectedOption.dataset.price) || 0
        };
    }

    var formData = new FormData();
    formData.append('action', 'add_service');
    formData.append('service_id', serviceId);
    formData.append('quantity', quantity);
    formData.append('selected_options', JSON.stringify(selectedOptions));

    fetch('../php/cart_handler.php', {
        method: 'POST',
        body: formData
    })
    .then(function(response) { return response.json(); })
    .then(function(data) {
        if (data.success) {
            showSuccess(data.message);
            var cartCountElement = document.querySelector('.cart-count');
            if (cartCountElement) {
                cartCountElement.textContent = data.cart_count;
                cartCountElement.style.display = data.cart_count > 0 ? 'inline' : 'none';
            }
        } else {
            showError(data.message);
        }
    })
    .catch(function(error) {
        console.error('Error:', error);
        showError('An error occurred while adding to cart');
    });
}

function showSuccess(message) {
    showNotification(message, 'success');
}

function showError(message) {
    showNotification(message, 'error');
}

function highlightServiceFromUrl() {
    const urlParams = new URLSearchParams(window.location.search);
    const serviceId = urlParams.get('service_id');
    
    if (serviceId) {
        const serviceCard = document.querySelector(`[data-service-id="${serviceId}"]`);
        if (serviceCard) {
            setTimeout(() => {
                serviceCard.scrollIntoView({ 
                    behavior: 'smooth', 
                    block: 'center' 
                });
                serviceCard.style.border = '2px solid #007cba';
                serviceCard.style.boxShadow = '0 0 15px rgba(0,124,186,0.3)';
                
                setTimeout(() => {
                    serviceCard.style.border = '';
                    serviceCard.style.boxShadow = '';
                }, 3000);
            }, 500);
        }
    }
}

