/**
 * Order Management JavaScript
 */
class OrderManager {
    constructor() {
        this.currentOrderId = null;
        this.modal = null;
        this.initEventListeners();
    }

    initEventListeners() {
        // Update status buttons
        document.querySelectorAll('.update-status').forEach(button => {
            button.addEventListener('click', this.handleStatusButtonClick.bind(this));
        });

        // Save status button
        const saveButton = document.getElementById('saveStatus');
        if (saveButton) {
            saveButton.addEventListener('click', this.handleSaveStatus.bind(this));
        }

        // Search and filter functionality
        this.initSearchAndFilter();
    }

    handleStatusButtonClick(event) {
        this.currentOrderId = event.currentTarget.dataset.orderId;
        this.modal = new bootstrap.Modal(document.getElementById('updateStatusModal'));
        this.modal.show();
    }


    async handleSaveStatus() {
        const saveButton = document.getElementById('saveStatus');
        const orderStatus = document.getElementById('orderStatus').value;
        const paymentStatus = document.getElementById('paymentStatus').value;
        const statusNotes = document.getElementById('statusNotes')?.value || '';
        
        // Show loading state
        saveButton.disabled = true;
        saveButton.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Saving...';
    
        try {
            // Get CSRF token safely
            let csrfToken = '';
            const metaTag = document.querySelector('meta[name="csrf-token"]');
            if (metaTag) {
                csrfToken = metaTag.content;
            } else {
                // Fallback to hidden input if meta tag doesn't exist
                const tokenInput = document.querySelector('input[name="_token"]');
                if (tokenInput) {
                    csrfToken = tokenInput.value;
                }
            }
    
            if (!this.currentOrderId) {
                // Try to get order ID from the URL if not set
                const urlParts = window.location.pathname.split('/');
                const potentialOrderId = urlParts[urlParts.length - 1];
                if (!isNaN(potentialOrderId)) {
                    this.currentOrderId = potentialOrderId;
                } else {
                    throw new Error('Order ID not found');
                }
            }
    
            const response = await fetch(`/admin/orders/${this.currentOrderId}/status`, {
                method: 'PATCH',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'X-CSRF-TOKEN': csrfToken
                },
                body: JSON.stringify({
                    order_status: orderStatus,
                    payment_status: paymentStatus,
                    status_notes: statusNotes
                })
            });
    
            // Check if response is OK
            if (!response.ok) {
                // Try to parse error response as JSON
                let errorData;
                try {
                    errorData = await response.json();
                    throw new Error(errorData.message || `Server error: ${response.status}`);
                } catch (jsonError) {
                    // If JSON parsing fails, use status text
                    throw new Error(`Server error: ${response.status} ${response.statusText}`);
                }
            }
    
            const data = await response.json();
            
            if (data.success) {
                this.showToast('Success', 'Order status updated successfully!', 'success');
                
                // Reload page after 1 second
                setTimeout(() => {
                    window.location.reload();
                }, 1000);
            } else {
                throw new Error(data.message || 'Failed to update status');
            }
        } catch (error) {
            console.error('Error:', error);
            this.showToast('Error', error.message || 'An error occurred. Please try again.', 'danger');
            
            // Reset button state
            saveButton.disabled = false;
            saveButton.innerHTML = 'Save changes';
        }
    }


    // async handleSaveStatus() {
    //     const saveButton = document.getElementById('saveStatus');
    //     const orderStatus = document.getElementById('orderStatus').value;
    //     const paymentStatus = document.getElementById('paymentStatus').value;
    //     const statusNotes = document.getElementById('statusNotes')?.value || '';
        
    //     // Show loading state
    //     saveButton.disabled = true;
    //     saveButton.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Saving...';
    
    //     try {
    //         // Get CSRF token safely
    //         let csrfToken = '';
    //         const metaTag = document.querySelector('meta[name="csrf-token"]');
    //         if (metaTag) {
    //             csrfToken = metaTag.content;
    //         } else {
    //             // Fallback to hidden input if meta tag doesn't exist
    //             const tokenInput = document.querySelector('input[name="_token"]');
    //             if (tokenInput) {
    //                 csrfToken = tokenInput.value;
    //             }
    //         }
    
    //         const response = await fetch(`/admin/orders/${this.currentOrderId}/status`, {
    //             method: 'PATCH',
    //             headers: {
    //                 'Content-Type': 'application/json',
    //                 'X-CSRF-TOKEN': csrfToken
    //             },
    //             body: JSON.stringify({
    //                 order_status: orderStatus,
    //                 payment_status: paymentStatus,
    //                 status_notes: statusNotes
    //             })
    //         });

    //         const data = await response.json();
            
    //         if (data.success) {
    //             this.showToast('Success', 'Order status updated successfully!', 'success');
                
    //             // Reload page after 1 second
    //             setTimeout(() => {
    //                 window.location.reload();
    //             }, 1000);
    //         } else {
    //             throw new Error(data.message || 'Failed to update status');
    //         }
    //     } catch (error) {
    //         console.error('Error:', error);
    //         this.showToast('Error', error.message || 'An error occurred. Please try again.', 'danger');
            
    //         // Reset button state
    //         saveButton.disabled = false;
    //         saveButton.innerHTML = 'Save changes';
    //     }
    // }

    initSearchAndFilter() {
        const searchInput = document.getElementById('searchInput');
        const dateFrom = document.getElementById('dateFrom');
        const dateTo = document.getElementById('dateTo');
        const exportButton = document.getElementById('exportOrders');
        
        if (searchInput) {
            let searchTimeout;
            searchInput.addEventListener('keyup', () => {
                clearTimeout(searchTimeout);
                searchTimeout = setTimeout(this.filterOrders.bind(this), 500);
            });
        }
        
        if (dateFrom) dateFrom.addEventListener('change', this.filterOrders.bind(this));
        if (dateTo) dateTo.addEventListener('change', this.filterOrders.bind(this));
        if (exportButton) exportButton.addEventListener('click', this.exportOrders.bind(this));
    }

    filterOrders() {
        const search = document.getElementById('searchInput')?.value || '';
        const dateFrom = document.getElementById('dateFrom')?.value || '';
        const dateTo = document.getElementById('dateTo')?.value || '';

        const params = new URLSearchParams({
            search: search,
            date_from: dateFrom,
            date_to: dateTo
        });

        window.location.href = `/admin/orders?${params.toString()}`;
    }

    exportOrders() {
        const search = document.getElementById('searchInput')?.value || '';
        const dateFrom = document.getElementById('dateFrom')?.value || '';
        const dateTo = document.getElementById('dateTo')?.value || '';

        const params = new URLSearchParams({
            search: search,
            date_from: dateFrom,
            date_to: dateTo
        });

        window.location.href = `/admin/orders/export?${params.toString()}`;
    }

    showToast(title, message, type = 'success') {
        const toast = document.createElement('div');
        toast.className = 'position-fixed bottom-0 end-0 p-3';
        toast.style.zIndex = '5';
        toast.innerHTML = `
            <div class="toast show" role="alert" aria-live="assertive" aria-atomic="true">
                <div class="toast-header bg-${type} text-white">
                    <strong class="me-auto">${title}</strong>
                    <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
                </div>
                <div class="toast-body">
                    ${message}
                </div>
            </div>
        `;
        document.body.appendChild(toast);
        
        // Auto-remove after 5 seconds
        setTimeout(() => {
            toast.remove();
        }, 5000);
    }
}

// Initialize when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
    new OrderManager();
});