class DiscountManager {
    constructor() {
        this.currentOffers = [];
        this.cartTotal = 0;
        this.init();
    }

    init() {
        this.loadAvailableOffers();
        this.setupEventListeners();
    }

    setupEventListeners() {
        document.addEventListener('cartUpdated', (e) => {
            this.cartTotal = e.detail.total;
            this.calculateBestDiscount();
        });
    }

    async loadAvailableOffers() {
        try {
            const response = await fetch('../php/apply_offers.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: 'get_available_offers',
                    order_amount: this.cartTotal
                })
            });

            const data = await response.json();
            if (data.success) {
                this.currentOffers = data.offers;
                this.displayOffersOnServices();
            }
        } catch (error) {
            console.error('Error loading offers:', error);
        }
    }

    displayOffersOnServices() {
        const serviceCards = document.querySelectorAll('.service-card');
        
        serviceCards.forEach(card => {
            const serviceId = this.getServiceIdFromCard(card);
            const applicableOffers = this.getApplicableOffers(serviceId);
            
            if (applicableOffers.length > 0) {
                this.addOfferBadgeToService(card, applicableOffers[0]);
            }
        });
    }

    getServiceIdFromCard(card) {
        const addButton = card.querySelector('button[onclick*="addToCart"]');
        if (addButton) {
            const onclick = addButton.getAttribute('onclick');
            const match = onclick.match(/addToCart\((\d+)\)/);
            return match ? parseInt(match[1]) : null;
        }
        return null;
    }

    getApplicableOffers(serviceId) {
        return this.currentOffers.filter(offer => {
            if (!offer.applicable_services) return true;
            
            try {
                const applicableServices = JSON.parse(offer.applicable_services);
                return applicableServices.includes(serviceId);
            } catch {
                return true; 
            }
        });
    }

    addOfferBadgeToService(card, offer) {
        const existingBadge = card.querySelector('.offer-badge-service');
        if (existingBadge) {
            existingBadge.remove();
        }

        const badge = document.createElement('div');
        badge.className = 'offer-badge-service';
        badge.innerHTML = `
            <span class="offer-text">
                ${offer.discount_type === 'percentage' ? 
                    `${offer.discount_value}% OFF` : 
                    `SAR ${offer.discount_value} OFF`}
            </span>
            <span class="offer-title">${offer.title}</span>
        `;

        const priceElement = card.querySelector('.price');
        if (priceElement) {
            card.insertBefore(badge, priceElement);
        }
    }

    async calculateBestDiscount() {
        if (this.cartTotal === 0) return null;

        try {
            const response = await fetch('../php/apply_offers.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: 'apply_offer',
                    order_amount: this.cartTotal
                })
            });

            const data = await response.json();
            if (data.success && data.result.discount_amount > 0) {
                this.displayDiscountPreview(data.result);
                return data.result;
            }
        } catch (error) {
            console.error('Error calculating discount:', error);
        }
        return null;
    }

    displayDiscountPreview(discountResult) {
        let previewElement = document.querySelector('.discount-preview');
        
        if (!previewElement) {
            previewElement = document.createElement('div');
            previewElement.className = 'discount-preview';
            
            const cartSummary = document.querySelector('.cart-summary');
            if (cartSummary) {
                cartSummary.insertBefore(previewElement, cartSummary.firstChild);
            }
        }

        previewElement.innerHTML = `
            <div class="discount-preview-content">
                <h4>🎉 Discount Applied!</h4>
                <p><strong>${discountResult.offer_title}</strong></p>
                <p class="savings">You save: SAR ${discountResult.discount_amount.toFixed(2)}</p>
                <p class="final-amount">Final total: SAR ${discountResult.final_amount.toFixed(2)}</p>
            </div>
        `;
    }

    formatDiscount(offer) {
        if (offer.discount_type === 'percentage') {
            return `${offer.discount_value}% OFF`;
        } else {
            return `SAR ${offer.discount_value} OFF`;
        }
    }

    async updateDiscounts(newTotal) {
        this.cartTotal = newTotal;
        await this.loadAvailableOffers();
        return await this.calculateBestDiscount();
    }
}

document.addEventListener('DOMContentLoaded', function() {
    window.discountManager = new DiscountManager();
});

function triggerCartUpdate(total) {
    const event = new CustomEvent('cartUpdated', {
        detail: { total: total }
    });
    document.dispatchEvent(event);
}

async function addToCartWithDiscount(serviceId) {
    try {
        const result = await addToCart(serviceId);
        
        if (window.discountManager) {
            const cartTotal = await getCartTotal();
            await window.discountManager.updateDiscounts(cartTotal);
        }
        
        return result;
    } catch (error) {
        console.error('Error adding to cart with discount:', error);
        return addToCart(serviceId); 
    }
}

async function getCartTotal() {
    try {
        const response = await fetch('../php/cart_handler.php?action=get_details');
        const data = await response.json();
        return data.success ? data.totalAmount : 0;
    } catch (error) {
        console.error('Error getting cart total:', error);
        return 0;
    }
}

