<?php if ( ! defined( 'ABSPATH' ) ) exit; ?>
<!-- ========================================== -->
<!-- STRATEGIC DASHBOARD MODALS (ADDED DEC 2025) -->
<!-- ========================================== -->

<!-- 1. Order Details Modal -->
<div id="vmo-order-details-modal" class="vmo-modal-overlay" style="display: none;">
    <div class="vmo-modal-content" style="max-width: 800px;">
        <div class="vmo-modal-header">
            <h3>📦 Order Details</h3>
            <button class="vmo-modal-close" title="Close this window" onclick="document.getElementById('vmo-order-details-modal').style.display='none'">×</button>
        </div>
        <div class="vmo-modal-body" id="vmo-order-details-content">
            <div style="text-align: center; padding: 40px;">
                <div class="vmo-spinner"></div>
                <p>Loading order information...</p>
            </div>
        </div>
        <div class="vmo-modal-footer">
            <button class="vmo-btn vmo-btn-secondary" title="Close this window" onclick="document.getElementById('vmo-order-details-modal').style.display='none'">Close</button>
            <button class="vmo-btn vmo-btn-primary" title="Print a simple packing slip for this order" onclick="window.printPackingSlipFromModal && window.printPackingSlipFromModal()">Print Packing Slip</button>
        </div>
    </div>
</div>

<!-- 2. Carrier Configuration Modal -->
<div id="vmo-carrier-config-modal" class="vmo-modal-overlay" style="display: none;">
    <div class="vmo-modal-content" style="max-width: 600px;">
        <div class="vmo-modal-header">
            <h3>🚚 Configure Carrier</h3>
            <button class="vmo-modal-close" title="Close this window" onclick="document.getElementById('vmo-carrier-config-modal').style.display='none'">×</button>
        </div>
        <div class="vmo-modal-body">
            <div class="vmo-form-group">
                <label>Carrier Name</label>
                <input type="text" id="vmo-carrier-name" class="vmo-input" readonly>
            </div>
            <div class="vmo-form-group">
                <label>Account ID / Account Number</label>
                <input type="text" id="vmo-carrier-api-key" class="vmo-input" placeholder="Enter account ID">
            </div>
            <div class="vmo-form-group">
                <label>Secret Key</label>
                <input type="password" id="vmo-carrier-secret" class="vmo-input" placeholder="Enter Secret Key">
            </div>
            <div class="vmo-form-group">
                <label>Default Service Level</label>
                <select id="vmo-carrier-service" class="vmo-input">
                    <option value="ground">Ground (Standard)</option>
                    <option value="express">Express (2-Day)</option>
                    <option value="overnight">Overnight</option>
                </select>
            </div>
        </div>
        <div class="vmo-modal-footer">
            <button class="vmo-btn vmo-btn-secondary" title="Close without saving" onclick="document.getElementById('vmo-carrier-config-modal').style.display='none'">Cancel</button>
            <button class="vmo-btn vmo-btn-primary" title="Save this carrier configuration for your account" onclick="window.saveCarrierConfigFromModal && window.saveCarrierConfigFromModal()">Save Configuration</button>
        </div>
    </div>
</div>

<!-- 3. Fulfillment Center Modal -->
<div id="vmo-fulfillment-config-modal" class="vmo-modal-overlay" style="display: none;">
    <div class="vmo-modal-content" style="max-width: 600px;">
        <div class="vmo-modal-header">
            <h3>🏭 Fulfillment Center Config</h3>
            <button class="vmo-modal-close" title="Close this window" onclick="document.getElementById('vmo-fulfillment-config-modal').style.display='none'">×</button>
        </div>
        <div class="vmo-modal-body">
            <div class="vmo-form-group">
                <label>Provider</label>
                <input type="text" id="vmo-fulfillment-provider" class="vmo-input" readonly>
            </div>
            <div class="vmo-form-group">
                <label>Integration Status</label>
                <div class="vmo-status-badge vmo-status-active">Active</div>
            </div>
            <div class="vmo-form-group">
                <label>Sync Frequency</label>
                <select id="vmo-fulfillment-sync" class="vmo-input">
                    <option>Real-time</option>
                    <option>Hourly</option>
                    <option>Daily</option>
                </select>
            </div>
            <div class="vmo-form-group">
                <label>Auto-Fulfill Orders</label>
                <label class="vmo-toggle">
                    <input id="vmo-fulfillment-auto" type="checkbox" checked>
                    <span class="vmo-slider"></span>
                </label>
            </div>
        </div>
        <div class="vmo-modal-footer">
            <button class="vmo-btn vmo-btn-secondary" title="Close without saving" onclick="document.getElementById('vmo-fulfillment-config-modal').style.display='none'">Cancel</button>
            <button class="vmo-btn vmo-btn-primary" title="Save fulfillment settings for your account" onclick="window.saveFulfillmentConfigFromModal && window.saveFulfillmentConfigFromModal()">Save Settings</button>
        </div>
    </div>
</div>

<!-- 4. Bulk Shipping Modal -->
<div id="vmo-bulk-shipping-modal" class="vmo-modal-overlay" style="display: none;">
    <div class="vmo-modal-content" style="max-width: 900px;">
        <div class="vmo-modal-header">
            <h3>📦 Bulk Shipping Processor</h3>
            <button class="vmo-modal-close" title="Close this window" onclick="document.getElementById('vmo-bulk-shipping-modal').style.display='none'">×</button>
        </div>
        <div class="vmo-modal-body">
            <div class="vmo-alert vmo-alert-info" id="vmo-bulk-shipping-status">
                Checking for pending orders...
            </div>
            <table class="vmo-table" style="margin-top: 20px;">
                <thead>
                    <tr>
                        <th>Order</th>
                        <th>Customer</th>
                        <th>Destination</th>
                        <th>Selected Carrier</th>
                        <th>Rate</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody id="vmo-bulk-shipping-list">
                    <!-- Dynamic Content -->
                </tbody>
            </table>
            <div id="vmo-bulk-shipping-empty" style="display:none; text-align:center; padding:40px; color:#888;">
                <div style="font-size:40px; margin-bottom:10px;">📦</div>
                <p>No pending orders found requiring shipping.</p>
            </div>
        </div>
        <div class="vmo-modal-footer">
            <div style="margin-right: auto; font-weight: bold;" id="vmo-bulk-shipping-total">Total: $0.00</div>
            <button class="vmo-btn vmo-btn-secondary" title="Close this window" onclick="document.getElementById('vmo-bulk-shipping-modal').style.display='none'">Close</button>
            <button class="vmo-btn vmo-btn-primary" title="Process all listed orders in bulk (approve shipment + create fulfillment)" id="vmo-bulk-shipping-action" onclick="window.processBulkShippingOrders && window.processBulkShippingOrders()" disabled>Purchase & Print Labels</button>
        </div>
    </div>
</div>

<script>
(function(){
    function vmoNotify(msg, type){
        try {
            if (typeof window.notify === 'function') return window.notify(msg, type || 'info');
            if (typeof window.showToast === 'function') return window.showToast(msg, type || 'info');
        } catch(e) {}
        try { console.log('[VMO]', type || 'info', msg); } catch(e) {}
    }

    function vmoPost(action, extra){
        if (typeof window.ajaxPost === 'function') {
            return window.ajaxPost(action, extra || {});
        }
        const ajaxUrl = (typeof window.VMO_AJAX !== 'undefined' ? window.VMO_AJAX : (window.ajaxurl || '/wp-admin/admin-ajax.php'));
        const nonce = (typeof window.VMO_NONCE_ADMIN !== 'undefined' ? window.VMO_NONCE_ADMIN : (window.VMO_NONCE || ''));
        const security = (typeof window.VMO_NONCE_BUILDER !== 'undefined' ? window.VMO_NONCE_BUILDER : (window.VMO_NONCE || ''));
        const params = new URLSearchParams({ action: action, nonce: nonce, security: security, ...(extra || {}) });
        return fetch(ajaxUrl, { method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body: params }).then(r=>r.json());
    }

    window.saveCarrierConfigFromModal = function(){
        const carrierName = (document.getElementById('vmo-carrier-name')?.value || '').trim();
        const carrierId = carrierName.toLowerCase().replace(/\s+/g,'_');
        const apiKey = (document.getElementById('vmo-carrier-api-key')?.value || '').trim();
        const secret = (document.getElementById('vmo-carrier-secret')?.value || '').trim();
        const service = (document.getElementById('vmo-carrier-service')?.value || '').trim();

        if (!carrierId) {
            vmoNotify('Carrier not selected', 'error');
            return;
        }

        vmoNotify('Saving carrier configuration...', 'info');
        vmoPost('vmo_save_carrier_config', { carrier_id: carrierId, api_key: apiKey, secret: secret, service: service })
            .then(({success, data, message}) => {
                if (!success) {
                    vmoNotify(message || 'Failed to save carrier configuration', 'error');
                    return;
                }
                vmoNotify('Carrier configuration saved', 'success');
                const modal = document.getElementById('vmo-carrier-config-modal');
                if (modal) modal.style.display = 'none';
            })
            .catch(() => vmoNotify('Error saving carrier configuration', 'error'));
    };

    window.saveFulfillmentConfigFromModal = function(){
        const provider = (document.getElementById('vmo-fulfillment-provider')?.value || '').trim();
        const sync = (document.getElementById('vmo-fulfillment-sync')?.value || '').trim();
        const autoFulfill = !!document.getElementById('vmo-fulfillment-auto')?.checked;

        if (!provider) {
            vmoNotify('Fulfillment provider not selected', 'error');
            return;
        }

        vmoNotify('Saving fulfillment settings...', 'info');
        vmoPost('vmo_save_fulfillment_config', { provider: provider, sync_frequency: sync, auto_fulfill: autoFulfill ? '1' : '0' })
            .then(({success, message}) => {
                if (!success) {
                    vmoNotify(message || 'Failed to save fulfillment settings', 'error');
                    return;
                }
                vmoNotify('Fulfillment settings saved', 'success');
                const modal = document.getElementById('vmo-fulfillment-config-modal');
                if (modal) modal.style.display = 'none';
            })
            .catch(() => vmoNotify('Error saving fulfillment settings', 'error'));
    };

    window.printPackingSlipFromModal = function(){
        const modal = document.getElementById('vmo-order-details-modal');
        const orderId = modal && modal.dataset ? modal.dataset.orderId : '';
        const content = document.getElementById('vmo-order-details-content');
        const html = content ? content.innerHTML : '';
        if (!html) {
            vmoNotify('Nothing to print yet', 'info');
            return;
        }
        const w = window.open('', '_blank');
        if (!w) {
            vmoNotify('Pop-up blocked. Please allow pop-ups to print.', 'error');
            return;
        }
        w.document.open();
        w.document.write(`<!doctype html><html><head><title>Packing Slip ${orderId ? '#' + orderId : ''}</title><meta charset="utf-8"></head><body>${html}</body></html>`);
        w.document.close();
        w.focus();
        setTimeout(()=>{ try{ w.print(); } catch(e){} }, 250);
    };
})();
</script>
