/**
 * Order Details Page Script
 * Handles order actions: Fulfill, Cancel, Add Note.
 * Uses Event Delegation for maximum robustness.
 */

document.addEventListener('DOMContentLoaded', function () {
    console.log('Order Details Script Loaded. Order ID:', typeof ORDER_ID !== 'undefined' ? ORDER_ID : 'UNDEFINED');

    // Helper to get bootstrap modal safely
    function getModal(id) {
        const el = document.getElementById(id);
        if (el) {
            return new bootstrap.Modal(el);
        }
        return null;
    }

    // MAIN EVENT LISTENER
    document.body.addEventListener('click', function (e) {
        const target = e.target;

        // Helper to find closest button if icon was clicked
        const btn = target.closest('button') || target.closest('a.dropdown-item');
        if (!btn) return;

        const id = btn.id;
        console.log('Clicked element ID:', id);

        // --- ACTION HANDLERS ---

        // 1. Hold Order
        if (id === 'holdOrderBtn' || id === 'holdOrderBtnTop') {
            e.preventDefault();
            if (confirm('Are you sure you want to put this order on HOLD?')) {
                updateOrder('hold', btn);
            }
        }

        // 2. Refund Order
        if (id === 'refundOrderBtn' || id === 'refundOrderBtnTop') {
            e.preventDefault();
            if (confirm('DANGER: This will REFUND the order and Cancel fulfillment.\nAre you sure?')) {
                updateOrder('refund', btn);
            }
        }

        // 3. Fulfill Order (Simple Modal)
        if (id === 'simpleFulfillBtn' || id === 'headerFulfillBtn' || id === 'itemsFulfillBtn') {
            e.preventDefault();
            const modal = getModal('simpleFulfillModal');
            if (modal) modal.show();
        }

        // 3b. Confirm Simple Fulfill
        if (id === 'confirmSimpleFulfillBtn') {
            e.preventDefault();
            const modalEl = document.getElementById('simpleFulfillModal');
            const modalInstance = bootstrap.Modal.getInstance(modalEl);
            updateOrder('fulfill', btn, null, () => modalInstance ? modalInstance.hide() : null);
        }

        // 4. Add/Edit Tracking Trigger
        if (id === 'addTrackingBtn' || id === 'editTrackingBtn' || id === 'headerAddTrackingBtn' || id === 'headerEditTrackingBtn') {
            e.preventDefault();
            // Pre-fill if editing
            const existingTracking = btn.dataset.tracking || '';
            document.getElementById('trackingNumberInput').value = existingTracking;

            const modal = getModal('addTrackingModal');
            if (modal) modal.show();
        }

        // 4b. Generate Tracking
        if (id === 'generateTrackingBtn') {
            e.preventDefault();
            const random = Math.random().toString(36).substring(2, 10).toUpperCase();
            document.getElementById('trackingNumberInput').value = 'TRK-' + random;
        }

        // 4c. Save Tracking
        if (id === 'saveTrackingBtn') {
            e.preventDefault();
            const trackingInput = document.getElementById('trackingNumberInput');
            const number = trackingInput.value.trim();
            if (!number) {
                alert('Please enter a tracking number.');
                return;
            }
            const modalEl = document.getElementById('addTrackingModal');
            const modalInstance = bootstrap.Modal.getInstance(modalEl);
            updateOrder('add_tracking', btn, { tracking_number: number }, () => modalInstance ? modalInstance.hide() : null);
        }

        // 5. Create Shipping Label (Trigger Modal)
        if (id === 'createShippingLabelBtn') {
            e.preventDefault();
            const modal = getModal('shippingLabelModal');
            if (modal) modal.show();
        }

        // 5b. Confirm Create Shipping Label
        if (id === 'confirmShippingLabelBtn') {
            e.preventDefault();
            const modalEl = document.getElementById('shippingLabelModal');
            const modalInstance = bootstrap.Modal.getInstance(modalEl);

            const originalText = btn.innerHTML;
            btn.disabled = true;
            btn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Creating...';

            const mockTrackingNumber = 'TRK-' + Math.random().toString(36).substring(2, 10).toUpperCase();

            setTimeout(() => {
                if (modalInstance) modalInstance.hide();

                // 1. Save Tracking Number (Triggers In Transit)
                updateOrder('add_tracking', btn, { tracking_number: mockTrackingNumber }, () => {
                    // 2. Open Label Print Window
                    window.open('print-label.php?id=' + ORDER_ID, '_blank', 'width=400,height=600');
                    alert(`Shipping Label Created!\nTracking Number Generated: ${mockTrackingNumber}`);
                });
            }, 1000);
        }

        // 6. Print Actions
        if (id === 'printOrderAction') {
            e.preventDefault();
            window.print();
        }

        if (id === 'printPackingSlipAction' || id === 'headerPrintSlipBtn') {
            e.preventDefault();
            window.open('print-packing-slip.php?id=' + ORDER_ID, '_blank');
        }

        // 7. Cancel Order Logic (Trigger Modal)
        if (id === 'cancelOrderAction') {
            e.preventDefault();
            const modal = getModal('cancelOrderModal');
            if (modal) modal.show();
        }

        // 7b. Confirm Cancel (Inside Modal)
        if (id === 'confirmCancelBtn') {
            e.preventDefault();
            const modalEl = document.getElementById('cancelOrderModal');
            const modalInstance = bootstrap.Modal.getInstance(modalEl);
            updateOrder('cancel', btn, null, () => modalInstance ? modalInstance.hide() : null);
        }

        // 8. Add Note Trigger
        if (id === 'addNoteBtn') {
            e.preventDefault();
            document.getElementById('orderNoteInput').value = '';
            const modal = getModal('addNoteModal');
            if (modal) modal.show();
        }

        // 8b. Save Note
        if (id === 'saveNoteBtn') {
            e.preventDefault();
            const noteInput = document.getElementById('orderNoteInput');
            const note = noteInput.value.trim();
            if (!note) {
                alert('Please enter a note.');
                return;
            }
            const modalEl = document.getElementById('addNoteModal');
            const modalInstance = bootstrap.Modal.getInstance(modalEl);
            updateOrder('add_note', btn, { note: note }, () => modalInstance ? modalInstance.hide() : null);
        }
    });

    /**
     * Helper to send API requests
     */
    function updateOrder(action, btnElement, extraData = {}, onSuccess = null) {
        if (!btnElement) return;

        const originalText = btnElement.innerHTML;
        btnElement.disabled = true;
        // Only add spinner if it's a button, not a link
        if (btnElement.tagName === 'BUTTON') {
            btnElement.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Processing...';
        }

        const params = new URLSearchParams();
        params.append('action', action);
        params.append('id', ORDER_ID);

        if (!extraData) extraData = {};

        for (const [key, value] of Object.entries(extraData)) {
            params.append(key, value);
        }

        fetch('api/orders.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: params
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    if (onSuccess) onSuccess();
                    window.location.reload();
                } else {
                    alert(data.message || 'Action failed');
                    btnElement.disabled = false;
                    btnElement.innerHTML = originalText;
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred.');
                btnElement.disabled = false;
                btnElement.innerHTML = originalText;
            });
    }
});
