/**
 * Traveler - Tour & Travel Web Application
 * Main JavaScript File
 */

document.addEventListener('DOMContentLoaded', function() {
    
    // ============================================
    // Navbar Scroll Effect
    // ============================================
    const navbar = document.querySelector('.navbar');
    if (navbar) {
        window.addEventListener('scroll', function() {
            if (window.scrollY > 50) {
                navbar.classList.add('scrolled');
            } else {
                navbar.classList.remove('scrolled');
            }
        });
    }

    // ============================================
    // Mobile Navigation & Sidebar
    // ============================================
    const navToggle = document.querySelector('.nav-toggle');
    const navMenu = document.querySelector('.nav-menu');
    const mobileSidebar = document.querySelector('.mobile-sidebar');
    const mobileSidebarOverlay = document.querySelector('.mobile-sidebar-overlay');
    const mobileSidebarClose = document.querySelector('.mobile-sidebar-close');
    const mobileSidebarCloseUser = document.querySelector('.mobile-sidebar-close-user');

    // ============================================
    // Mobile Sidebar Functions
    // ============================================
    function openMobileSidebar() {
        if (mobileSidebar && mobileSidebarOverlay) {
            mobileSidebar.classList.add('active');
            mobileSidebarOverlay.classList.add('active');
            document.body.style.overflow = 'hidden';
            
            // Update toggle icon
            if (navToggle) {
                const icon = navToggle.querySelector('i');
                if (icon) {
                    icon.classList.remove('fa-bars');
                    icon.classList.add('fa-times');
                }
            }
        }
    }

    function closeMobileSidebar() {
        if (mobileSidebar && mobileSidebarOverlay) {
            mobileSidebar.classList.remove('active');
            mobileSidebarOverlay.classList.remove('active');
            document.body.style.overflow = '';
            
            // Update toggle icon
            if (navToggle) {
                const icon = navToggle.querySelector('i');
                if (icon) {
                    icon.classList.remove('fa-times');
                    icon.classList.add('fa-bars');
                }
            }
        }
    }

    // Single event handler for the toggle button (handles both desktop nav and mobile sidebar)
    if (navToggle) {
        navToggle.addEventListener('click', function(e) {
            e.stopPropagation();
            
            // On mobile (< 1024px), toggle sidebar
            if (window.innerWidth < 1024) {
                if (mobileSidebar && mobileSidebar.classList.contains('active')) {
                    closeMobileSidebar();
                } else {
                    openMobileSidebar();
                }
            } else {
                // On desktop, toggle nav menu
                if (navMenu) {
                    navMenu.classList.toggle('active');
                    const icon = this.querySelector('i');
                    if (navMenu.classList.contains('active')) {
                        icon.classList.remove('fa-bars');
                        icon.classList.add('fa-times');
                    } else {
                        icon.classList.remove('fa-times');
                        icon.classList.add('fa-bars');
                    }
                }
            }
        });
    }

    // Close menu when clicking outside (desktop only)
    document.addEventListener('click', function(e) {
        if (window.innerWidth >= 1024 && navToggle && navMenu) {
            if (!navToggle.contains(e.target) && !navMenu.contains(e.target)) {
                navMenu.classList.remove('active');
                const icon = navToggle.querySelector('i');
                if (icon) {
                    icon.classList.remove('fa-times');
                    icon.classList.add('fa-bars');
                }
            }
        }
    });

    // Close button handlers
    if (mobileSidebarClose) {
        mobileSidebarClose.addEventListener('click', closeMobileSidebar);
    }

    if (mobileSidebarCloseUser) {
        mobileSidebarCloseUser.addEventListener('click', closeMobileSidebar);
    }

    // Overlay click handler
    if (mobileSidebarOverlay) {
        mobileSidebarOverlay.addEventListener('click', closeMobileSidebar);
    }

    // Close sidebar on link click
    document.querySelectorAll('.mobile-sidebar-link, .mobile-sidebar-btn').forEach(function(link) {
        link.addEventListener('click', closeMobileSidebar);
    });

    // Close sidebar on escape key
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape' && mobileSidebar && mobileSidebar.classList.contains('active')) {
            closeMobileSidebar();
        }
    });

    // ============================================
    // User Menu Dropdown (Authenticated User)
    // ============================================
    const userMenu = document.querySelector('.user-menu');
    const userMenuTrigger = document.querySelector('.user-menu-trigger');

    if (userMenu && userMenuTrigger) {
        userMenuTrigger.addEventListener('click', function(e) {
            e.stopPropagation();
            userMenu.classList.toggle('active');
            
            // Close user dropdown if open (for unauthenticated)
            const userDropdown = document.querySelector('.user-dropdown');
            if (userDropdown) {
                userDropdown.classList.remove('active');
            }
        });

        // Close menu when clicking outside
        document.addEventListener('click', function(e) {
            if (userMenu && !userMenu.contains(e.target)) {
                userMenu.classList.remove('active');
            }
        });

        // Close menu on escape key
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && userMenu && userMenu.classList.contains('active')) {
                userMenu.classList.remove('active');
            }
        });
    }

    // ============================================
    // User Dropdown Menu (Desktop - Unauthenticated)
    // ============================================
    const userDropdown = document.querySelector('.user-dropdown');
    const userDropdownTrigger = document.querySelector('.user-icon-trigger');

    if (userDropdown && userDropdownTrigger) {
        userDropdownTrigger.addEventListener('click', function(e) {
            e.stopPropagation();
            userDropdown.classList.toggle('active');
            
            // Close user menu if open (for authenticated)
            if (userMenu) {
                userMenu.classList.remove('active');
            }
        });

        // Close dropdown when clicking outside
        document.addEventListener('click', function(e) {
            if (userDropdown && !userDropdown.contains(e.target)) {
                userDropdown.classList.remove('active');
            }
        });

        // Close dropdown on escape key
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && userDropdown && userDropdown.classList.contains('active')) {
                userDropdown.classList.remove('active');
            }
        });
    }

    // ============================================
    // Hero Slider
    // ============================================
    const heroSlider = document.querySelector('.hero-slider');
    if (heroSlider) {
        const slides = heroSlider.querySelectorAll('.hero-slide');
        const dots = heroSlider.querySelectorAll('.slider-dot');
        const prevBtn = heroSlider.querySelector('.slider-arrow.prev');
        const nextBtn = heroSlider.querySelector('.slider-arrow.next');
        let currentSlide = 0;
        let slideInterval;

        function showSlide(index) {
            slides.forEach(s => s.classList.remove('active'));
            dots.forEach(d => d.classList.remove('active'));
            
            currentSlide = index;
            if (currentSlide >= slides.length) currentSlide = 0;
            if (currentSlide < 0) currentSlide = slides.length - 1;
            
            slides[currentSlide].classList.add('active');
            if (dots[currentSlide]) dots[currentSlide].classList.add('active');
        }

        function nextSlide() {
            showSlide(currentSlide + 1);
        }

        function prevSlide() {
            showSlide(currentSlide - 1);
        }

        function startAutoSlide() {
            slideInterval = setInterval(nextSlide, 5000);
        }

        function stopAutoSlide() {
            clearInterval(slideInterval);
        }

        if (nextBtn) nextBtn.addEventListener('click', function() {
            stopAutoSlide();
            nextSlide();
            startAutoSlide();
        });

        if (prevBtn) prevBtn.addEventListener('click', function() {
            stopAutoSlide();
            prevSlide();
            startAutoSlide();
        });

        dots.forEach(function(dot, index) {
            dot.addEventListener('click', function() {
                stopAutoSlide();
                showSlide(index);
                startAutoSlide();
            });
        });

        if (slides.length > 0) {
            showSlide(0);
            startAutoSlide();
        }
    }

    // ============================================
    // Back to Top Button
    // ============================================
    const backToTop = document.querySelector('.back-to-top');
    if (backToTop) {
        window.addEventListener('scroll', function() {
            if (window.scrollY > 300) {
                backToTop.classList.add('visible');
            } else {
                backToTop.classList.remove('visible');
            }
        });

        backToTop.addEventListener('click', function() {
            window.scrollTo({ top: 0, behavior: 'smooth' });
        });
    }

    // ============================================
    // Alert Close Buttons
    // ============================================
    document.querySelectorAll('.close-alert').forEach(function(btn) {
        btn.addEventListener('click', function() {
            this.closest('.alert').style.display = 'none';
        });
    });

    // Auto-hide alerts after 5 seconds
    document.querySelectorAll('.alert').forEach(function(alert) {
        setTimeout(function() {
            alert.style.opacity = '0';
            alert.style.transform = 'translateY(-10px)';
            setTimeout(function() {
                alert.style.display = 'none';
            }, 300);
        }, 5000);
    });

    // ============================================
    // Booking Form Calculator
    // ============================================
    const bookingForm = document.querySelector('.booking-form');
    if (bookingForm) {
        const numPeople = bookingForm.querySelector('#num_people');
        const pricePerPerson = bookingForm.querySelector('#price_per_person');
        const totalDisplay = bookingForm.querySelector('#total_amount_display');
        const totalInput = bookingForm.querySelector('#total_amount');

        function calculateTotal() {
            if (numPeople && pricePerPerson) {
                const people = parseInt(numPeople.value) || 1;
                const price = parseFloat(pricePerPerson.value) || 0;
                const total = people * price;
                if (totalDisplay) totalDisplay.textContent = '₹' + total.toLocaleString('en-IN', {minimumFractionDigits: 2});
                if (totalInput) totalInput.value = total.toFixed(2);
            }
        }

        if (numPeople) numPeople.addEventListener('change', calculateTotal);
        if (numPeople) numPeople.addEventListener('input', calculateTotal);
    }

    // ============================================
    // Form Validation
    // ============================================
    document.querySelectorAll('form[data-validate]').forEach(function(form) {
        form.addEventListener('submit', function(e) {
            let isValid = true;
            
            // Clear previous errors
            form.querySelectorAll('.form-error').forEach(el => el.remove());
            form.querySelectorAll('.form-control.error').forEach(el => el.classList.remove('error'));

            // Required fields
            form.querySelectorAll('[required]').forEach(function(field) {
                if (!field.value.trim()) {
                    isValid = false;
                    field.classList.add('error');
                    const error = document.createElement('div');
                    error.className = 'form-error';
                    error.textContent = 'This field is required';
                    field.parentNode.appendChild(error);
                }
            });

            // Email validation
            form.querySelectorAll('input[type="email"]').forEach(function(field) {
                if (field.value && !isValidEmail(field.value)) {
                    isValid = false;
                    field.classList.add('error');
                    const error = document.createElement('div');
                    error.className = 'form-error';
                    error.textContent = 'Please enter a valid email address';
                    field.parentNode.appendChild(error);
                }
            });

            // Phone validation
            form.querySelectorAll('input[data-validate-phone]').forEach(function(field) {
                if (field.value && !isValidPhone(field.value)) {
                    isValid = false;
                    field.classList.add('error');
                    const error = document.createElement('div');
                    error.className = 'form-error';
                    error.textContent = 'Please enter a valid phone number';
                    field.parentNode.appendChild(error);
                }
            });

            // Password match
            const password = form.querySelector('input[name="password"]');
            const confirmPassword = form.querySelector('input[name="confirm_password"]');
            if (password && confirmPassword && password.value !== confirmPassword.value) {
                isValid = false;
                confirmPassword.classList.add('error');
                const error = document.createElement('div');
                error.className = 'form-error';
                error.textContent = 'Passwords do not match';
                confirmPassword.parentNode.appendChild(error);
            }

            if (!isValid) {
                e.preventDefault();
                // Scroll to first error
                const firstError = form.querySelector('.form-control.error');
                if (firstError) {
                    firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
                    firstError.focus();
                }
            }
        });
    });

    function isValidEmail(email) {
        return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
    }

    function isValidPhone(phone) {
        return /^[\+]?[0-9\s\-\(\)]{10,15}$/.test(phone);
    }

    // ============================================
    // Image Preview on Upload
    // ============================================
    document.querySelectorAll('input[type="file"][data-preview]').forEach(function(input) {
        input.addEventListener('change', function() {
            const previewId = this.getAttribute('data-preview');
            const preview = document.getElementById(previewId);
            
            if (preview && this.files && this.files[0]) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    preview.innerHTML = '<img src="' + e.target.result + '" alt="Preview">';
                };
                reader.readAsDataURL(this.files[0]);
            }
        });
    });

    // ============================================
    // Confirm Delete
    // ============================================
    document.querySelectorAll('[data-confirm]').forEach(function(element) {
        element.addEventListener('click', function(e) {
            const message = this.getAttribute('data-confirm') || 'Are you sure you want to delete this item?';
            if (!confirm(message)) {
                e.preventDefault();
            }
        });
    });

    // ============================================
    // Smooth Scroll for Anchor Links
    // ============================================
    document.querySelectorAll('a[href^="#"]').forEach(function(anchor) {
        anchor.addEventListener('click', function(e) {
            const target = document.querySelector(this.getAttribute('href'));
            if (target) {
                e.preventDefault();
                target.scrollIntoView({ behavior: 'smooth', block: 'start' });
            }
        });
    });

    // ============================================
    // Scroll Animations (Intersection Observer)
    // ============================================
    const observerOptions = {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    };

    const observer = new IntersectionObserver(function(entries) {
        entries.forEach(function(entry) {
            if (entry.isIntersecting) {
                entry.target.classList.add('fade-in-up');
                // Remove the animation-hidden class after animation completes
                entry.target.addEventListener('animationend', function() {
                    this.classList.remove('animation-hidden');
                }, { once: true });
                observer.unobserve(entry.target);
            }
        });
    }, observerOptions);

    document.querySelectorAll('.package-card, .place-card, .why-us-card, .testimonial-card').forEach(function(el) {
        el.classList.add('animation-hidden');
        observer.observe(el);
    });

    // ============================================
    // Search Functionality
    // ============================================
    const searchForm = document.querySelector('.search-box');
    if (searchForm) {
        searchForm.addEventListener('submit', function(e) {
            const searchInput = this.querySelector('input[name="search"]');
            if (searchInput && !searchInput.value.trim()) {
                e.preventDefault();
                searchInput.focus();
                searchInput.classList.add('error');
                setTimeout(() => searchInput.classList.remove('error'), 2000);
            }
        });
    }

    // ============================================
    // Itinerary Accordion
    // ============================================
    document.querySelectorAll('.itinerary-item .day-content').forEach(function(item) {
        const description = item.querySelector('.day-description');
        const meta = item.querySelector('.day-meta');
        
        if (description) {
            // Initially collapse all except first
            const parent = item.closest('.itinerary-item');
            const allItems = document.querySelectorAll('.itinerary-item');
            
            if (parent !== allItems[0]) {
                description.style.maxHeight = '0';
                description.style.overflow = 'hidden';
                description.style.transition = 'max-height 0.3s ease';
                if (meta) {
                    meta.style.maxHeight = '0';
                    meta.style.overflow = 'hidden';
                    meta.style.transition = 'max-height 0.3s ease';
                }
            }
        }

        item.querySelector('.day-title').addEventListener('click', function() {
            const desc = item.querySelector('.day-description');
            const metaEl = item.querySelector('.day-meta');
            
            if (desc) {
                if (desc.style.maxHeight === '0px') {
                    desc.style.maxHeight = desc.scrollHeight + 'px';
                    if (metaEl) metaEl.style.maxHeight = metaEl.scrollHeight + 'px';
                } else {
                    desc.style.maxHeight = '0';
                    if (metaEl) metaEl.style.maxHeight = '0';
                }
            }
        });
    });

    // ============================================
    // Package Gallery Lightbox
    // ============================================
    document.querySelectorAll('.gallery-item').forEach(function(item) {
        item.addEventListener('click', function() {
            const img = this.querySelector('img');
            if (img) {
                const overlay = document.createElement('div');
                overlay.className = 'lightbox-overlay';
                overlay.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.9);z-index:9999;display:flex;align-items:center;justify-content:center;cursor:pointer;animation:fadeIn 0.3s ease';
                
                const lightboxImg = document.createElement('img');
                lightboxImg.src = img.src;
                lightboxImg.style.cssText = 'max-width:90%;max-height:90%;object-fit:contain;border-radius:8px';
                
                overlay.appendChild(lightboxImg);
                document.body.appendChild(overlay);
                
                overlay.addEventListener('click', function() {
                    this.remove();
                });
            }
        });
    });

});

// ============================================
// Admin Panel JavaScript
// ============================================

// Sidebar Toggle (Desktop and Mobile)
function toggleSidebar() {
    const sidebar = document.querySelector('.admin-sidebar');
    const overlay = document.querySelector('.sidebar-overlay');
    
    if (sidebar) {
        // On mobile (< 769px), toggle mobile-open class
        if (window.innerWidth < 769) {
            sidebar.classList.toggle('mobile-open');
            if (overlay) {
                overlay.classList.toggle('active');
            }
        } else {
            // On desktop, toggle collapsed state
            sidebar.classList.toggle('collapsed');
        }
    }
}

// Close sidebar when clicking overlay on mobile
document.addEventListener('click', function(e) {
    if (e.target.classList.contains('sidebar-overlay')) {
        toggleSidebar();
    }
});

// User Panel Sidebar Toggle
function toggleUserSidebar() {
    const sidebar = document.querySelector('.user-sidebar');
    const overlay = document.querySelector('.user-sidebar-overlay');
    
    if (sidebar && overlay) {
        sidebar.classList.toggle('active');
        overlay.classList.toggle('active');
        document.body.style.overflow = overlay.classList.contains('active') ? 'hidden' : '';
    }
}

// Close user sidebar on escape key
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        const sidebar = document.querySelector('.user-sidebar');
        const overlay = document.querySelector('.user-sidebar-overlay');
        if (sidebar && sidebar.classList.contains('active')) {
            sidebar.classList.remove('active');
            overlay.classList.remove('active');
            document.body.style.overflow = '';
        }
    }
});

// Submenu Toggle
function toggleSubmenu(element) {
    const parent = element.closest('.has-submenu');
    const submenu = parent.querySelector('.submenu');
    
    // Close other submenus
    document.querySelectorAll('.has-submenu.open').forEach(function(item) {
        if (item !== parent) {
            item.classList.remove('open');
            item.querySelector('.submenu').classList.remove('open');
        }
    });
    
    parent.classList.toggle('open');
    submenu.classList.toggle('open');
}

// Settings Tab Switch
function switchSettingsTab(tabId) {
    document.querySelectorAll('.settings-tabs a').forEach(a => a.classList.remove('active'));
    document.querySelectorAll('.settings-panel').forEach(p => p.classList.remove('active'));
    
    document.querySelector(`[data-tab="${tabId}"]`).classList.add('active');
    document.getElementById(tabId).classList.add('active');
}

// Print Invoice
function printInvoice(bookingId) {
    window.open('invoice.php?id=' + bookingId + '&print=1', '_blank', 'width=800,height=600');
}

// Delete Confirmation
function confirmDelete(url, itemName) {
    if (confirm('Are you sure you want to delete "' + itemName + '"? This action cannot be undone.')) {
        window.location.href = url;
    }
}

// Dynamic Image Upload Preview
function previewImages(input, containerId) {
    const container = document.getElementById(containerId);
    if (!container) return;
    
    container.innerHTML = '';
    
    if (input.files) {
        Array.from(input.files).forEach(function(file) {
            const reader = new FileReader();
            reader.onload = function(e) {
                const div = document.createElement('div');
                div.className = 'image-preview-item';
                div.innerHTML = `
                    <img src="${e.target.result}" alt="Preview">
                    <button type="button" class="remove-image" onclick="this.parentElement.remove()">
                        <i class="fas fa-times"></i>
                    </button>
                `;
                container.appendChild(div);
            };
            reader.readAsDataURL(file);
        });
    }
}

// Format Currency
function formatCurrency(amount) {
    return '₹' + parseFloat(amount).toLocaleString('en-IN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    });
}

// AJAX Helper
function ajaxRequest(url, method, data, callback) {
    const xhr = new XMLHttpRequest();
    xhr.open(method, url, true);
    
    if (method === 'POST' && !(data instanceof FormData)) {
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    }
    
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                try {
                    const response = JSON.parse(xhr.responseText);
                    callback(null, response);
                } catch(e) {
                    callback(null, xhr.responseText);
                }
            } else {
                callback('Request failed with status: ' + xhr.status);
            }
        }
    };
    
    xhr.send(data);
}

// Show Toast Notification
function showToast(message, type = 'success') {
    const toast = document.createElement('div');
    toast.className = `alert alert-${type}`;
    toast.style.cssText = 'position:fixed;top:20px;right:20px;z-index:9999;min-width:300px;animation:slideDown 0.3s ease';
    toast.innerHTML = `
        <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'danger' ? 'exclamation-circle' : 'info-circle'}"></i>
        ${message}
        <button class="close-alert" onclick="this.parentElement.remove()">&times;</button>
    `;
    document.body.appendChild(toast);
    
    setTimeout(function() {
        toast.style.opacity = '0';
        toast.style.transform = 'translateY(-10px)';
        setTimeout(() => toast.remove(), 300);
    }, 4000);
}
