// Promotional Offer Popup System - Database Version
class OfferPopupManagerDB {
    constructor() {
        this.currentOffer = null;
        this.countdownInterval = null;
        this.hasShown = false;
        this.init();
    }

    async init() {
        // Load current offer data from database
        await this.loadCurrentOffer();
        
        // Check if offer should be displayed
        if (this.shouldShowOffer()) {
            // Show popup after a short delay
            setTimeout(() => {
                this.showOfferPopup();
            }, 2000);
        }
    }

    async loadCurrentOffer() {
        try {
            const response = await fetch('api/save-offer-db.php');
            const data = await response.json();
            
            if (data.success && data.offer) {
                this.currentOffer = data.offer;
            }
        } catch (error) {
            console.error('Error loading offer:', error);
        }
    }

    shouldShowOffer() {
        if (!this.currentOffer) {
            return false;
        }

        const now = new Date();
        const startDate = new Date(this.currentOffer.start_date);
        const endDate = new Date(this.currentOffer.end_date);

        // Check if current time is within offer period
        const isWithinPeriod = now >= startDate && now <= endDate;
        
        // Check if already shown in this session
        const sessionKey = `offer_shown_${this.currentOffer.id}`;
        const alreadyShown = sessionStorage.getItem(sessionKey) === 'true';

        return isWithinPeriod && !alreadyShown && !this.hasShown;
    }

    showOfferPopup() {
        const popup = document.getElementById('offerPopup');
        const offerImage = document.getElementById('offerImage');
        
        if (!popup || !offerImage || !this.currentOffer) {
            return;
        }

        // Set offer image
        offerImage.src = this.currentOffer.image_url;
        offerImage.alt = this.currentOffer.title || 'Special Offer';

        // Show popup
        popup.style.display = 'block';
        document.body.style.overflow = 'hidden';

        // Mark as shown
        this.hasShown = true;
        const sessionKey = `offer_shown_${this.currentOffer.id}`;
        sessionStorage.setItem(sessionKey, 'true');

        // Start countdown timer
        this.startCountdown();
    }

    closeOfferPopup() {
        const popup = document.getElementById('offerPopup');
        if (popup) {
            popup.style.display = 'none';
            document.body.style.overflow = 'auto';
        }

        // Stop countdown
        if (this.countdownInterval) {
            clearInterval(this.countdownInterval);
            this.countdownInterval = null;
        }
    }

    startCountdown() {
        if (!this.currentOffer) return;

        const endDate = new Date(this.currentOffer.end_date);

        // Update countdown immediately
        this.updateCountdown(endDate);

        // Update every second
        this.countdownInterval = setInterval(() => {
            this.updateCountdown(endDate);
        }, 1000);
    }

    updateCountdown(endDate) {
        const now = new Date();
        const timeRemaining = endDate - now;

        if (timeRemaining <= 0) {
            // Offer has ended
            this.closeOfferPopup();
            this.offerEnded();
            return;
        }

        // Calculate time units
        const days = Math.floor(timeRemaining / (1000 * 60 * 60 * 24));
        const hours = Math.floor((timeRemaining % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        const minutes = Math.floor((timeRemaining % (1000 * 60 * 60)) / (1000 * 60));
        const seconds = Math.floor((timeRemaining % (1000 * 60)) / 1000);

        // Update display
        this.updateCountdownDisplay('days', days);
        this.updateCountdownDisplay('hours', hours);
        this.updateCountdownDisplay('minutes', minutes);
        this.updateCountdownDisplay('seconds', seconds);
    }

    updateCountdownDisplay(unit, value) {
        const element = document.getElementById(`countdown-${unit}`);
        if (element) {
            element.textContent = value.toString().padStart(2, '0');
        }
    }

    offerEnded() {
        // Clear session storage
        if (this.currentOffer) {
            const sessionKey = `offer_shown_${this.currentOffer.id}`;
            sessionStorage.removeItem(sessionKey);
        }
        
        // Optionally show a message that offer has ended
        console.log('Offer has ended');
    }
}

// Global functions for onclick handlers
function closeOfferPopup() {
    if (window.offerManagerDB) {
        window.offerManagerDB.closeOfferPopup();
    }
}

// Initialize offer popup manager when DOM is loaded
document.addEventListener('DOMContentLoaded', function() {
    window.offerManagerDB = new OfferPopupManagerDB();
});
