/* ===================================
   DASHBOARD JAVASCRIPT
   ==================================== */

document.addEventListener('DOMContentLoaded', function() {
    initializeDashboard();
});

function initializeDashboard() {
    initializeSidebarToggle();
    initializeFormHandlers();
    initializeButtons();
    handleResponsiveInitialization();
}

// Debounce helper for resize events
function debounce(func, delay) {
    let timeoutId;
    return function(...args) {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => func(...args), delay);
    };
}

// Handle responsive initialization
function handleResponsiveInitialization() {
    handleResponsive();
    window.addEventListener('resize', debounce(handleResponsive, 250));
}

// ============ SIDEBAR TOGGLE ============
function initializeSidebarToggle() {
    const toggleSidebarBtn = document.getElementById('toggleSidebar');
    const sidebarToggleBtn = document.getElementById('sidebarToggle');
    const sidebar = document.querySelector('.dashboard-sidebar');
    const overlay = document.getElementById('sidebarOverlay');

    if (toggleSidebarBtn) {
        toggleSidebarBtn.addEventListener('click', function() {
            sidebar.classList.add('active');
            overlay.classList.add('active');
        });
    }

    if (sidebarToggleBtn) {
        sidebarToggleBtn.addEventListener('click', function() {
            sidebar.classList.remove('active');
            overlay.classList.remove('active');
        });
    }

    if (overlay) {
        overlay.addEventListener('click', function() {
            sidebar.classList.remove('active');
            this.classList.remove('active');
        });
    }

    // Close sidebar when a link is clicked (on mobile)
    const navLinks = document.querySelectorAll('.nav-link');
    navLinks.forEach(link => {
        link.addEventListener('click', function() {
            if (window.innerWidth < 992) {
                sidebar.classList.remove('active');
                overlay.classList.remove('active');
            }
        });
    });
}

// ============ FORM HANDLERS ============
function initializeFormHandlers() {
    const profileForm = document.getElementById('profileForm');
    
    if (profileForm) {
        profileForm.addEventListener('submit', function(e) {
            e.preventDefault();
            submitProfileForm();
        });

        // Auto-save indication
        const formInputs = profileForm.querySelectorAll('input');
        formInputs.forEach(input => {
            input.addEventListener('change', function() {
                showFormChangedIndicator();
            });
        });
    }
}

function submitProfileForm() {
    const form = document.getElementById('profileForm');
    const formData = new FormData(form);

    // Show loading state
    const submitBtn = form.querySelector('button[type="submit"]');
    const originalText = submitBtn.textContent;
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Saving...';

    fetch('api/update-profile.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification('Profile updated successfully!', 'success');
            setTimeout(() => {
                location.reload();
            }, 1500);
        } else {
            showNotification(data.message || 'An error occurred', 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showNotification('An error occurred while updating profile', 'error');
    })
    .finally(() => {
        submitBtn.disabled = false;
        submitBtn.textContent = originalText;
    });
}

function showFormChangedIndicator() {
    // You can add visual feedback here
    const submitBtn = document.querySelector('.form-actions .btn-primary');
    if (submitBtn && !submitBtn.classList.contains('changed')) {
        submitBtn.classList.add('changed');
        submitBtn.style.animation = 'pulse 0.5s ease';
    }
}

// ============ BUTTON HANDLERS ============
function initializeButtons() {
    // View Reservation Details
    window.viewReservationDetails = function(id) {
        console.log('Viewing reservation details for ID:', id);
        // This could open a modal or navigate to a detail page
        // For now, showing a simple alert
        // You could implement a modal here
        fetchReservationDetails(id);
    };

    // Cancel Reservation
    window.cancelReservation = function(id) {
        if (confirm('Are you sure you want to cancel this reservation? This action cannot be undone.')) {
            submitCancellation('reservation', id);
        }
    };

    // View Service Details
    window.viewServiceDetails = function(id) {
        console.log('Viewing service details for ID:', id);
        fetchServiceDetails(id);
    };

    // Cancel Service
    window.cancelService = function(id) {
        if (confirm('Are you sure you want to cancel this service? This action cannot be undone.')) {
            submitCancellation('service', id);
        }
    };
}

function fetchReservationDetails(id) {
    fetch(`api/get-reservation-details.php?id=${id}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                displayReservationModal(data.reservation);
            } else {
                showNotification(data.message || 'Could not load reservation details', 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showNotification('Error loading reservation details', 'error');
        });
}

function fetchServiceDetails(id) {
    fetch(`api/get-service-details.php?id=${id}`)
        .then(async response => {
            const text = await response.text();
            let data = null;
            try {
                data = JSON.parse(text);
            } catch (e) {
                throw new Error('Invalid server response');
            }

            if (!response.ok) {
                throw new Error(data.message || 'Could not load service details');
            }
            return data;
        })
        .then(data => {
            if (data.success) {
                displayServiceModal(data.service);
            } else {
                showNotification(data.message || 'Could not load service details', 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showNotification('Error loading service details', 'error');
        });
}

function submitCancellation(type, id) {
    const endpoint = type === 'reservation' ? 'api/cancel-reservation.php' : 'api/cancel-service.php';
    
    fetch(endpoint, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `id=${id}`
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification(`${type.charAt(0).toUpperCase() + type.slice(1)} cancelled successfully!`, 'success');
            setTimeout(() => {
                location.reload();
            }, 1500);
        } else {
            showNotification(data.message || 'Could not cancel ' + type, 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showNotification('Error cancelling ' + type, 'error');
    });
}

function displayReservationModal(reservation) {
    // Create and display a modal with reservation details
    const modal = createModal('Reservation Details', `
        <div class="modal-body">
            <div class="detail-row">
                <span class="label">Reservation ID:</span>
                <span class="value">#${reservation.id}</span>
            </div>
            <div class="detail-row">
                <span class="label">Room:</span>
                <span class="value">${reservation.room_type} (${reservation.room_number})</span>
            </div>
            <div class="detail-row">
                <span class="label">Check-in:</span>
                <span class="value">${new Date(reservation.check_in_date).toLocaleDateString()}</span>
            </div>
            <div class="detail-row">
                <span class="label">Check-out:</span>
                <span class="value">${new Date(reservation.check_out_date).toLocaleDateString()}</span>
            </div>
            <div class="detail-row">
                <span class="label">Status:</span>
                <span class="value">${reservation.status}</span>
            </div>
            <div class="detail-row">
                <span class="label">Total Price:</span>
                <span class="value">$${parseFloat(reservation.total_price).toFixed(2)}</span>
            </div>
        </div>
    `);
    displayModal(modal);
}

function displayServiceModal(service) {
    // Create and display a modal with service details
    const modal = createModal('Service Details', `
        <div class="modal-body">
            <div class="detail-row">
                <span class="label">Service ID:</span>
                <span class="value">#${service.id}</span>
            </div>
            <div class="detail-row">
                <span class="label">Service:</span>
                <span class="value">${service.facility_name || 'Service'}</span>
            </div>
            <div class="detail-row">
                <span class="label">Start Date:</span>
                <span class="value">${new Date(service.service_start_date).toLocaleDateString()}</span>
            </div>
            <div class="detail-row">
                <span class="label">End Date:</span>
                <span class="value">${new Date(service.service_end_date).toLocaleDateString()}</span>
            </div>
            <div class="detail-row">
                <span class="label">Guests:</span>
                <span class="value">${service.number_of_guests}</span>
            </div>
            <div class="detail-row">
                <span class="label">Status:</span>
                <span class="value">${service.status}</span>
            </div>
            <div class="detail-row">
                <span class="label">Total Price:</span>
                <span class="value">$${parseFloat(service.total_price || 0).toFixed(2)}</span>
            </div>
        </div>
    `);
    displayModal(modal);
}

// ============ MODAL SYSTEM ============
function createModal(title, content) {
    const wrapper = document.createElement('div');
    wrapper.className = 'dashboard-modal-overlay';
    wrapper.innerHTML = `
        <div class="dashboard-modal" role="dialog" aria-modal="true">
            <div class="dashboard-modal-header">
                <h4>${title}</h4>
                <button type="button" class="dashboard-modal-close" aria-label="Close">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="dashboard-modal-content">
                ${content}
            </div>
        </div>
    `;
    return wrapper;
}

function displayModal(modalEl) {
    // Remove an existing modal if open
    const existing = document.querySelector('.dashboard-modal-overlay');
    if (existing) {
        existing.remove();
    }

    document.body.appendChild(modalEl);
    document.body.classList.add('dashboard-modal-open');

    const closeBtn = modalEl.querySelector('.dashboard-modal-close');
    if (closeBtn) {
        closeBtn.addEventListener('click', () => closeDashboardModal(modalEl));
    }

    modalEl.addEventListener('click', (e) => {
        if (e.target === modalEl) {
            closeDashboardModal(modalEl);
        }
    });

    const escHandler = (e) => {
        if (e.key === 'Escape') {
            closeDashboardModal(modalEl);
            document.removeEventListener('keydown', escHandler);
        }
    };
    document.addEventListener('keydown', escHandler);
}

function closeDashboardModal(modalEl) {
    if (modalEl && modalEl.parentElement) {
        modalEl.parentElement.removeChild(modalEl);
    }
    document.body.classList.remove('dashboard-modal-open');
}

// ============ NOTIFICATION SYSTEM ============
function showNotification(message, type = 'info') {
    // Remove existing notifications
    const existingNotifications = document.querySelectorAll('.notification');
    existingNotifications.forEach(notif => notif.remove());

    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.innerHTML = `
        <div class="notification-content">
            <i class="fas fa-${getNotificationIcon(type)}"></i>
            <span>${message}</span>
        </div>
        <button class="notification-close" onclick="this.parentElement.remove()">
            <i class="fas fa-times"></i>
        </button>
    `;

    document.body.appendChild(notification);

    // Auto-remove after 5 seconds
    setTimeout(() => {
        if (notification.parentElement) {
            notification.remove();
        }
    }, 5000);
}

function getNotificationIcon(type) {
    switch(type) {
        case 'success': return 'check-circle';
        case 'error': return 'exclamation-circle';
        case 'warning': return 'exclamation-triangle';
        case 'info': return 'info-circle';
        default: return 'info-circle';
    }
}

// Add notification styles
const notificationStyles = `
<style>
    .dashboard-modal-open {
        overflow: hidden;
    }

    .dashboard-modal-overlay {
        position: fixed;
        inset: 0;
        z-index: 10000;
        background: rgba(14, 30, 50, 0.55);
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 18px;
    }

    .dashboard-modal {
        width: min(620px, 95vw);
        max-height: 90vh;
        overflow: auto;
        background: #fff;
        border-radius: 12px;
        border: 1px solid #e5ecf3;
        box-shadow: 0 16px 40px rgba(16,36,61,.25);
    }

    .dashboard-modal-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 12px;
        padding: 14px 16px;
        border-bottom: 1px solid #e8eef5;
    }

    .dashboard-modal-header h4 {
        margin: 0;
        color: #10243d;
        font-size: 20px;
    }

    .dashboard-modal-close {
        border: 0;
        background: #f2f6fb;
        color: #294560;
        width: 34px;
        height: 34px;
        border-radius: 50%;
        cursor: pointer;
    }

    .dashboard-modal-content {
        padding: 14px 16px 18px;
    }

    .dashboard-modal-content .detail-row {
        display: flex;
        justify-content: space-between;
        gap: 14px;
        border-bottom: 1px solid #eef3f8;
        padding: 10px 0;
    }

    .dashboard-modal-content .detail-row .label {
        color: #617790;
        font-weight: 500;
    }

    .dashboard-modal-content .detail-row .value {
        color: #10243d;
        font-weight: 600;
        text-align: right;
    }

    .notification {
        position: fixed;
        top: 20px;
        right: 20px;
        max-width: 400px;
        padding: 15px 20px;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        z-index: 9999;
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 15px;
        animation: slideIn 0.3s ease-out;
    }

    @keyframes slideIn {
        from {
            transform: translateX(400px);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }

    .notification-success {
        background: #d4edda;
        color: #155724;
        border: 1px solid #c3e6cb;
    }

    .notification-error {
        background: #f8d7da;
        color: #721c24;
        border: 1px solid #f5c6cb;
    }

    .notification-warning {
        background: #fff3cd;
        color: #856404;
        border: 1px solid #ffeeba;
    }

    .notification-info {
        background: #d1ecf1;
        color: #0c5460;
        border: 1px solid #bee5eb;
    }

    .notification-content {
        display: flex;
        align-items: center;
        gap: 10px;
        flex: 1;
    }

    .notification-close {
        background: none;
        border: none;
        color: inherit;
        cursor: pointer;
        font-size: 16px;
        padding: 0;
        display: flex;
        align-items: center;
    }

    @media (max-width: 575px) {
        .dashboard-modal-content .detail-row {
            flex-direction: column;
            gap: 6px;
        }

        .dashboard-modal-content .detail-row .value {
            text-align: left;
        }

        .notification {
            left: 10px;
            right: 10px;
        }
    }
</style>
`;

document.head.insertAdjacentHTML('beforeend', notificationStyles);

// ============ RESPONSIVE BEHAVIOR ============
function handleResponsive() {
    const sidebar = document.querySelector('.dashboard-sidebar');
    const overlay = document.getElementById('sidebarOverlay');
    const viewport = window.innerWidth;
    
    // Close sidebar on small screens
    if (viewport < 992) {
        sidebar.classList.remove('active');
        if (overlay) {
            overlay.classList.remove('active');
        }
    }
    
    // Add body class for responsive CSS hooks
    const body = document.body;
    body.classList.remove('is-mobile', 'is-tablet', 'is-desktop');
    
    if (viewport < 480) {
        body.classList.add('is-mobile');
    } else if (viewport < 992) {
        body.classList.add('is-tablet');
    } else {
        body.classList.add('is-desktop');
    }
}

// ============ CHART INITIALIZATION ============
function initializeCharts() {
    // This function can be used to initialize charts if needed
    // Currently using simple statistics cards
}

// ============ UTILITY FUNCTIONS ============
function formatDate(date) {
    const options = { year: 'numeric', month: 'short', day: 'numeric' };
    return new Date(date).toLocaleDateString('en-US', options);
}

function formatCurrency(amount) {
    return new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: 'USD'
    }).format(amount);
}

// Log dashboard initialization
console.log('Dashboard initialized successfully');
