/* ===================================
   STAFF UTILITIES JS
   ==================================== */

/**
 * Fetch staff data via AJAX
 * @param {string} action - The API action to call
 * @param {object} params - Additional parameters
 * @returns {Promise}
 */
function getStaffData(action, params = {}) {
    // Resolve relative to the current page path so projects in subfolders work.
    const url = new URL('api/get-staff-data.php', window.location.href);
    url.searchParams.append('action', action);

    Object.keys(params).forEach(key => {
        url.searchParams.append(key, params[key]);
    });

    return fetch(url)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .catch(error => {
            console.error('Error fetching staff data:', error);
            return { success: false, message: 'Error fetching data' };
        });
}

/**
 * Update reservation status
 * @param {number} reservationId - The reservation ID
 * @param {string} status - The new status
 * @returns {Promise}
 */
function updateReservationStatus(reservationId, status) {
    const formData = new FormData();
    formData.append('action', 'update_reservation_status');
    formData.append('reservation_id', reservationId);
    formData.append('status', status);

    return fetch('api/get-staff-data.php', {
        method: 'POST',
        body: formData
    })
        .then(response => response.json())
        .catch(error => {
            console.error('Error updating reservation:', error);
            return { success: false, message: 'Error updating reservation' };
        });
}

/**
 * Update service reservation status
 * @param {number} serviceReservationId - The service reservation ID
 * @param {string} status - The new status
 * @returns {Promise}
 */
function updateServiceReservationStatus(serviceReservationId, status) {
    const formData = new FormData();
    formData.append('action', 'update_service_reservation_status');
    formData.append('service_reservation_id', serviceReservationId);
    formData.append('status', status);

    return fetch('api/get-staff-data.php', {
        method: 'POST',
        body: formData
    })
        .then(response => response.json())
        .catch(error => {
            console.error('Error updating service reservation:', error);
            return { success: false, message: 'Error updating service reservation' };
        });
}

/**
 * Update room reservation payment status
 * @param {number} reservationId - The reservation ID
 * @param {string} paymentStatus - unpaid|partial|paid
 * @returns {Promise}
 */
function updateReservationPaymentStatus(reservationId, paymentStatus) {
    const formData = new FormData();
    formData.append('action', 'update_reservation_payment_status');
    formData.append('reservation_id', reservationId);
    formData.append('payment_status', paymentStatus);

    return fetch('api/get-staff-data.php', {
        method: 'POST',
        body: formData
    })
        .then(response => response.json())
        .catch(error => {
            console.error('Error updating reservation payment status:', error);
            return { success: false, message: 'Error updating reservation payment status' };
        });
}

/**
 * Update service reservation payment status
 * @param {number} serviceReservationId - The service reservation ID
 * @param {string} paymentStatus - unpaid|partial|paid
 * @returns {Promise}
 */
function updateServiceReservationPaymentStatus(serviceReservationId, paymentStatus) {
    const formData = new FormData();
    formData.append('action', 'update_service_reservation_payment_status');
    formData.append('service_reservation_id', serviceReservationId);
    formData.append('payment_status', paymentStatus);

    return fetch('api/get-staff-data.php', {
        method: 'POST',
        body: formData
    })
        .then(response => response.json())
        .catch(error => {
            console.error('Error updating service payment status:', error);
            return { success: false, message: 'Error updating service payment status' };
        });
}

/**
 * Format date to readable format
 * @param {string} dateString - The date string
 * @returns {string}
 */
function formatDate(dateString) {
    const options = { year: 'numeric', month: 'short', day: 'numeric' };
    return new Date(dateString).toLocaleDateString('en-US', options);
}

/**
 * Format time to readable format
 * @param {string} timeString - The time string
 * @returns {string}
 */
function formatTime(timeString) {
    const options = { hour: '2-digit', minute: '2-digit' };
    return new Date(`2000-01-01 ${timeString}`).toLocaleTimeString('en-US', options);
}

/**
 * Show notification
 * @param {string} type - 'success', 'error', 'warning', 'info'
 * @param {string} message - The notification message
 * @param {number} duration - Duration in milliseconds
 */
function showNotification(type, message, duration = 3000) {
    const alertClass = {
        'success': 'alert-success',
        'error': 'alert-danger',
        'warning': 'alert-warning',
        'info': 'alert-info'
    }[type] || 'alert-info';

    const alertHtml = `
        <div class="alert ${alertClass} alert-dismissible fade show position-fixed top-0 start-50 translate-middle-x mt-3" role="alert">
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    `;

    document.body.insertAdjacentHTML('afterbegin', alertHtml);

    if (duration > 0) {
        setTimeout(() => {
            const alert = document.querySelector('.alert');
            if (alert) {
                alert.remove();
            }
        }, duration);
    }
}

/**
 * Refresh dashboard data
 */
function refreshDashboard() {
    Promise.all([
        getStaffData('get_dashboard_stats'),
        getStaffData('get_today_checkins'),
        getStaffData('get_pending_reservations'),
        getStaffData('get_recent_reservations')
    ]).then(([stats, checkins, pending, recent]) => {
        if (stats.success) {
            updateStatsDisplay(stats.data);
        }
        if (checkins.success) {
            updateCheckInsDisplay(checkins.data);
        }
        if (pending.success) {
            updatePendingDisplay(pending.data);
        }
        if (recent.success) {
            updateRecentDisplay(recent.data);
        }
    }).catch(error => {
        console.error('Error refreshing dashboard:', error);
    });
}

/**
 * Update stats display
 * @param {object} stats - The statistics data
 */
function updateStatsDisplay(stats) {
    // Update stat numbers if elements exist
    const elements = {
        'total_guests': '.stat-card-guests .stat-number',
        'total_reservations': '.stat-card-reservations .stat-number',
        'active_reservations': '.stat-card-active .stat-number',
        'checked_in_guests': '.stat-card-checkin .stat-number'
    };

    Object.keys(elements).forEach(key => {
        const el = document.querySelector(elements[key]);
        if (el && stats[key] !== undefined) {
            el.textContent = stats[key];
        }
    });
}

/**
 * Update check-ins display
 * @param {array} checkins - The check-ins data
 */
function updateCheckInsDisplay(checkins) {
    const container = document.querySelector('.checkin-list');
    if (!container) return;

    if (checkins.length === 0) {
        container.parentElement.innerHTML = `
            <div class="empty-state">
                <i class="icofont-calendar"></i>
                <p>No check-ins scheduled for today</p>
            </div>
        `;
        return;
    }

    container.innerHTML = checkins.map(checkin => `
        <div class="checkin-item">
            <div class="checkin-guest">
                <h5 class="guest-name">${checkin.first_name} ${checkin.last_name}</h5>
                <p class="guest-room">
                    <i class="icofont-door"></i> Room ${checkin.room_number}
                </p>
            </div>
            <div class="checkin-status">
                <span class="badge ${checkin.status === 'checked_in' ? 'bg-success' : 'bg-warning'}">
                    ${capitalize(checkin.status.replace('_', ' '))}
                </span>
            </div>
        </div>
    `).join('');
}

/**
 * Update pending display
 * @param {array} pending - The pending reservations data
 */
function updatePendingDisplay(pending) {
    const container = document.querySelector('.pending-list');
    if (!container) return;

    if (pending.length === 0) {
        container.parentElement.innerHTML = `
            <div class="empty-state">
                <i class="icofont-check-alt"></i>
                <p>All reservations confirmed!</p>
            </div>
        `;
        return;
    }

    container.innerHTML = pending.slice(0, 5).map(res => `
        <div class="pending-item">
            <div class="pending-info">
                <h5 class="pending-name">${res.first_name} ${res.last_name}</h5>
                <p class="pending-dates">
                    <i class="icofont-calendar"></i> 
                    ${formatDate(res.check_in_date)} - ${formatDate(res.check_out_date)}
                </p>
            </div>
            <div class="pending-action">
                <a href="reservation.php?id=${res.id}" class="btn btn-sm btn-outline-success">
                    <i class="icofont-check"></i> Review
                </a>
            </div>
        </div>
    `).join('');
}

/**
 * Update recent reservations display
 * @param {array} recent - The recent reservations data
 */
function updateRecentDisplay(recent) {
    const tbody = document.querySelector('.staff-table tbody');
    if (!tbody) return;

    if (recent.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="6" class="text-center py-4">
                    <i class="icofont-search"></i>
                    <p>No reservations found</p>
                </td>
            </tr>
        `;
        return;
    }

    tbody.innerHTML = recent.slice(0, 8).map(res => `
        <tr>
            <td>
                <div class="guest-info">
                    <strong>${res.first_name} ${res.last_name}</strong>
                    <br>
                    <small class="text-muted">${res.email}</small>
                </div>
            </td>
            <td class="d-none d-md-table-cell">
                <span class="room-badge">Room ${res.room_number}</span>
            </td>
            <td class="d-none d-lg-table-cell">
                <small>${formatDate(res.check_in_date)}</small>
            </td>
            <td class="d-none d-lg-table-cell">
                <small>${formatDate(res.check_out_date)}</small>
            </td>
            <td>
                <span class="status-badge status-${res.status.toLowerCase()}">
                    ${capitalize(res.status.replace('_', ' '))}
                </span>
            </td>
            <td class="text-end">
                <a href="reservation.php?id=${res.id}" class="btn-action" title="View Details">
                    <i class="icofont-eye"></i>
                </a>
            </td>
        </tr>
    `).join('');
}

/**
 * Capitalize string
 * @param {string} str - The string to capitalize
 * @returns {string}
 */
function capitalize(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
}

/**
 * Auto-refresh dashboard data periodically
 * @param {number} interval - Interval in milliseconds
 */
function startAutoRefresh(interval = 300000) { // Default 5 minutes
    setInterval(refreshDashboard, interval);
}

// Export functions for use in other scripts
window.StaffUtils = {
    getStaffData,
    updateReservationStatus,
    updateReservationPaymentStatus,
    updateServiceReservationStatus,
    updateServiceReservationPaymentStatus,
    formatDate,
    formatTime,
    showNotification,
    refreshDashboard,
    startAutoRefresh
};
