/**
 * 3CX Call Core - Shared functionality for 3CX calls
 * Used by both Admin Integration and Task Detail pages
 * 
 * This file provides a unified interface for 3CX calling functionality
 * while allowing different API endpoints and configurations for different contexts.
 */

window.ThreeCXCore = (function () {
    'use strict';

    // Configuration for different contexts - Using proper ThreeCX routes
    const contexts = {
        admin: {
            apiUrl: '/admin/integrations/threecx/test-call',
            statusUrl: '/admin/integrations/threecx/call-status',
            callHistoryUrl: null, // Admin doesn't save call history
            useUserExtension: false // Use fixed extension
        },
        task: {
            // Task-specific endpoints using proper ThreeCX module routes
            apiUrl: '/api/v1/threecx/call/start', // Proper ThreeCX call start endpoint
            statusUrl: '/api/v1/threecx/call/status',
            callHistoryUrl: '/api/threecx/logs/task', // Proper ThreeCX task logs endpoint
            useUserExtension: true // Use logged-in user's extension
        }
    };

    let currentContext = 'admin'; // Default to admin context

    /**
     * Set the current context (admin or task)
     */
    function setContext(context) {
        if (contexts[context]) {
            currentContext = context;
        }
    }

    /**
     * Get configuration for current context
     */
    function getConfig() {
        return contexts[currentContext];
    }

    /**
     * Get user extension from current user data
     * This will be implemented based on how user data is exposed to frontend
     */
    function getUserExtension() {
        // Try multiple ways to get user extension
        if (window.currentUser && window.currentUser.extension) {
            return window.currentUser.extension;
        }

        // Check if user data is in a global variable (common in Laravel apps)
        if (window.auth && window.auth.user && window.auth.user.extension) {
            return window.auth.user.extension;
        }

        // Check Laravel's common pattern for user data
        if (window.Laravel && window.Laravel.user && window.Laravel.user.extension) {
            return window.Laravel.user.extension;
        }

        // Fallback to meta tag if set
        const metaExtension = document.querySelector('meta[name="user-extension"]');
        if (metaExtension) {
            return metaExtension.getAttribute('content');
        }

        // Final fallback - could be set by the calling page
        return window.userExtension || '650'; // Default extension
    }

    /**
 * Make a 3CX call using the shared modal
 */
    function makeCall(phoneNumber, options = {}) {
        const config = getConfig();

        // Determine extension to use - for admin context, let backend resolve from integration settings
        let extension;
        if (config.useUserExtension) {
            extension = getUserExtension();
        } else {
            // Admin context - don't pass extension, let backend use integration settings
            extension = undefined;
        }

        // Prepare call options
        const callOptions = {
            extension: extension,
            apiUrl: config.apiUrl,
            timeout: options.timeout || 30,
            taskId: options.taskId || null
        };

        // Set up global call context for automatic history logging when call ends
        if (options.taskId) {
            // Store task context globally for automatic call logging
            callOptions.taskId = options.taskId;
            console.log('📝 Task context set for automatic call logging:', options.taskId);
        }

        // Use the existing ThreeCXCallModal if available
        if (window.ThreeCXCallModal) {
            return window.ThreeCXCallModal.makeCall(phoneNumber, callOptions);
        } else {
            console.error('ThreeCXCallModal not loaded');
            alert('3CX Call functionality not available. Please refresh the page.');
        }
    }

    /**
     * Log call history (deprecated - now handled automatically when call ends)
     * Kept for backward compatibility
     */
    function logCallHistory(callData) {
        console.warn('logCallHistory is deprecated - call logging now happens automatically when calls end');
        return Promise.resolve();
    }



    /**
     * Initialize 3CX Core for a specific context
     */
    function init(context, options = {}) {
        setContext(context);

        // Set user extension if provided
        if (options.userExtension) {
            window.userExtension = options.userExtension;
        }

        console.log(`3CX Core initialized for context: ${context}`);
    }

    // Public API
    return {
        init: init,
        setContext: setContext,
        getConfig: getConfig,
        getUserExtension: getUserExtension,
        makeCall: makeCall,
        logCallHistory: logCallHistory,

        // Context constants
        CONTEXTS: {
            ADMIN: 'admin',
            TASK: 'task'
        }
    };
})();

// Export for CommonJS if available
if (typeof module !== 'undefined' && module.exports) {
    module.exports = window.ThreeCXCore;
}
