// service_details.js - New logic for multi-step form

let currentStep = 1;
const totalSteps = 3; // Based on the new HTML structure

// Function to update the step indicators
function updateStepIndicator(step) {
    document.querySelectorAll('.form-steps-indicator .step').forEach(indicator => {
        const stepNum = parseInt(indicator.getAttribute('data-step'));
        indicator.classList.remove('active', 'completed');
        if (stepNum === step) {
            indicator.classList.add('active');
        } else if (stepNum < step) {
            indicator.classList.add('completed');
        }
    });
}

// Function to show a specific step
function showStep(step) {
    document.querySelectorAll('.form-step').forEach(formStep => {
        formStep.classList.remove('active');
    });
    document.querySelector(`.form-step[data-step="${step}"]`).classList.add('active');
    currentStep = step;
    updateStepIndicator(step);
}

// Function to validate the current step before moving next
function validateStep(step) {
    let isValid = true;
    const currentFormStep = document.querySelector(`.form-step[data-step="${step}"]`);
    
    // Check required fields in the current step
    currentFormStep.querySelectorAll('[required]').forEach(input => {
        if (!input.value) {
            isValid = false;
            input.classList.add('is-invalid'); // Add a class for visual feedback
        } else {
            input.classList.remove('is-invalid');
        }
    });
    
    // Specific validation for pickup/delivery address
    const pickupOption = document.getElementById('pickup_option');
    const pickupAddress = document.getElementById('pickup_address');
    if (step === 3 && pickupOption && pickupAddress) {
        if (pickupOption.value === 'pickup' && !pickupAddress.value) {
            isValid = false;
            pickupAddress.classList.add('is-invalid');
        } else {
            pickupAddress.classList.remove('is-invalid');
        }
    }

    // Add more specific validation logic here if needed (e.g., for household item selection)

    return isValid;
}

// Function to handle next step button click
function handleNextStep(event) {
    const nextStep = parseInt(event.target.getAttribute('data-next-step'));
    if (validateStep(currentStep)) {
        showStep(nextStep);
    } else {
        alert('Please fill in all required fields before proceeding.');
    }
}

// Function to handle previous step button click
function handlePrevStep(event) {
    const prevStep = parseInt(event.target.getAttribute('data-prev-step'));
    showStep(prevStep);
}

// Function to handle quantity change
function changeQuantity(delta) {
    const quantityInput = document.getElementById('quantity');
    let currentQty = parseInt(quantityInput.value) || 1;
    let newQty = currentQty + delta;
    if (newQty < 1) newQty = 1;
    quantityInput.value = newQty;
    updatePrice();
}

// Function to update the price summary
function updatePrice() {
    let optionsTotal = 0;
    const basePrice = serviceData.price || 0;
    const quantity = parseInt(document.getElementById('quantity')?.value) || 1;
    
    // 1. Calculate options total
    document.querySelectorAll('.service-option:not(#pickup_option)').forEach(select => {
        const selectedOption = select.options[select.selectedIndex];
        if (selectedOption && selectedOption.value) {
            const priceModifier = parseFloat(selectedOption.getAttribute('data-price')) || 0;
            optionsTotal += priceModifier;
        }
    });
    
    // 2. Calculate final total
    // Assuming the base price is per piece, and options are one-time or per-piece based on context
    // For simplicity, we'll assume base price is per piece and options are one-time modifiers for now.
    // This logic might need refinement based on the backend's exact pricing model.
    const subTotal = (basePrice * quantity) + optionsTotal;
    
    // 3. Update display
    document.getElementById('base-total').textContent = `SAR ${basePrice.toFixed(2)} x ${quantity}`;
    document.getElementById('options-total').textContent = `SAR ${optionsTotal.toFixed(2)}`;
    document.querySelector('.options-total').style.display = optionsTotal !== 0 ? 'flex' : 'none';
    document.getElementById('final-total').textContent = `SAR ${subTotal.toFixed(2)}`;
}

// Function to handle pickup/delivery option change
function handlePickupOptionChange() {
    const pickupOption = document.getElementById('pickup_option');
    const pickupAddressGroup = document.getElementById('pickup-address-group');
    const pickupAddress = document.getElementById('pickup_address');
    
    if (pickupOption.value === 'pickup') {
        pickupAddressGroup.style.display = 'block';
        pickupAddress.setAttribute('required', 'required');
    } else {
        pickupAddressGroup.style.display = 'none';
        pickupAddress.removeAttribute('required');
    }
}

// Function to handle household item selection (original logic)
function selectHouseholdItem(itemType, optionId) {
    // Deselect all buttons
    document.querySelectorAll('.item-type-btn').forEach(btn => {
        btn.classList.remove('selected');
    });
    
    // Select the clicked button
    const selectedBtn = document.querySelector(`.item-type-btn[data-item-type="${itemType}"]`);
    if (selectedBtn) {
        selectedBtn.classList.add('selected');
    }
    
    // Update item label in quantity section
    document.getElementById('item-label').textContent = selectedBtn.querySelector('.item-name').textContent;
    
    // Logic to dynamically load other options for the selected item type (if needed)
    // This part is complex and depends on the backend logic, so we'll keep it simple for now.
    // The original code didn't show the dynamic loading logic, only the container.
    // For the sake of the layout improvement, we assume the options are already in Step 1.
    
    // Update price
    updatePrice();
}

// Function to handle the final form submission
function addDetailedServiceToCart() {
    // This function will be called by the form's submit event listener
    // Gather all data and submit via AJAX or standard form submission
    const form = document.getElementById('order-form');
    if (!form.checkValidity()) {
        // If browser validation fails, stop submission
        return;
    }
    
    // Collect all data
    const formData = new FormData(form);
    const data = {
        service_id: serviceData.id,
        quantity: parseInt(document.getElementById('quantity').value),
        special_instructions: document.getElementById('special-instructions').value,
        pickup_option: document.getElementById('pickup_option').value,
        pickup_address: document.getElementById('pickup_address').value,
        options: {}
    };
    
    document.querySelectorAll('.service-option').forEach(select => {
        const optionType = select.getAttribute('data-option-type');
        if (select.value && optionType !== 'Pickup Option') {
            data.options[optionType] = select.value;
        }
    });
    
    // The original code used an onclick handler on a button, which suggests a custom JS function.
    // We will simulate the original function call here, but the user needs to implement the actual AJAX/fetch call.
    console.log('Form data ready for submission:', data);
    alert('Form submitted! (Actual submission logic needs to be implemented by the user)');
    
    // Prevent default form submission if using AJAX
    // event.preventDefault(); 
}


// Event Listeners
document.addEventListener('DOMContentLoaded', function() {
    // Initialize the first step
    showStep(1);
    
    // Attach event listeners for navigation
    document.querySelectorAll('.next-step').forEach(button => {
        button.addEventListener('click', handleNextStep);
    });
    
    document.querySelectorAll('.prev-step').forEach(button => {
        button.addEventListener('click', handlePrevStep);
    });
    
    // Attach event listener for pickup option change
    const pickupOption = document.getElementById('pickup_option');
    if (pickupOption) {
        pickupOption.addEventListener('change', handlePickupOptionChange);
    }
    
    // Attach event listeners for price update on option change
    document.querySelectorAll('.service-option').forEach(select => {
        select.addEventListener('change', updatePrice);
    });
    
    // Attach event listener for quantity change
    const quantityInput = document.getElementById('quantity');
    if (quantityInput) {
        quantityInput.addEventListener('change', updatePrice);
    }
    
    // Attach event listener for form submission
    const form = document.getElementById('order-form');
    if (form) {
        form.addEventListener('submit', function(event) {
            event.preventDefault(); // Prevent default form submission
            if (validateStep(currentStep)) {
                addDetailedServiceToCart();
            } else {
                alert('Please fill in all required fields before submitting.');
            }
        });
    }
    
    // Initial price update
    updatePrice();
});

// Expose selectHouseholdItem and changeQuantity to global scope for inline HTML calls
window.selectHouseholdItem = selectHouseholdItem;
window.changeQuantity = changeQuantity;
window.addDetailedServiceToCart = addDetailedServiceToCart; // Expose for compatibility with original PHP
