<?php
/**
 * Brilyi – Voice Agent functionality
 * This file will contain all Brilyi voice agent–related code.
 * If you would like to include the Brilyi voice agent functionality in your own plugin contat support@brilyi.com
 */

// Exit if accessed directly
if (! defined('ABSPATH')) {
    exit;
}


//  Register voice settings independently
add_action('admin_init', 'ezhp_voice_register_settings');

global $ezhp_voice_agent_shortcode_used;
$ezhp_voice_agent_shortcode_used = false;

function ezhp_voice_register_settings()
{
    register_setting('ezhp_voice_settings_group', 'ezhp_voice_agent_id', 'sanitize_text_field');

    // Use custom sanitizer so the encrypted value isn't mangled
    register_setting('ezhp_voice_settings_group', 'ezhp_voice_api_key', 'ezhp_voice_api_key_sanitizer');

    // Store last 4 separately (safe to sanitize)
    register_setting('ezhp_voice_settings_group', 'ezhp_voice_api_key_last4', 'sanitize_text_field');

    // ✅ Ensure this group is whitelisted so options.php can save it
    add_filter('whitelist_options', function ($options) {
        if (!isset($options['ezhp_voice_settings_group'])) {
            $options['ezhp_voice_settings_group'] = [
                'ezhp_voice_agent_id',
                'ezhp_voice_api_key',
                'ezhp_voice_api_key_last4',
            ];
        }
        return $options;
    });

    add_settings_section(
        'ezhp_voice_settings_section',
        'Brilyi Voice Agent Settings',
        null,
        'ezhp-voice-settings'
    );



    add_settings_field(
        'ezhp_voice_api_key_field',
        'Brilyi API Key',
        'ezhp_voice_api_key_render',
        'ezhp-voice-settings',
        'ezhp_voice_settings_section'
    );
}

function ezhp_voice_api_key_render()
{
    $last4 = get_option('ezhp_voice_api_key_last4', '');

    echo '<div class="ezhp-field">';
    echo '<input type="password" name="ezhp_voice_api_key" value="" class="regular-text" ';
    echo ' placeholder="Enter new API key" autocomplete="new-password" autocapitalize="off" spellcheck="false" />';

    if (!empty($last4)) {
        echo '<p class="description" style="margin:6px 0 0;">Current key: ************' . esc_html($last4) . '</p>';
    }
    echo '<p class="description">Leave blank to keep the existing key.</p>';

    // Test Connection UI
    echo '<button type="button" class="button" id="ezhp-test-connection" style="margin-top:6px;">Test Connection</button>';
    echo '<div id="ezhp-test-result" style="margin-top:8px;"></div>';

    echo '</div>';
}

// -------------------------
// Enqueue Admin Scripts
// -------------------------
add_action('admin_enqueue_scripts', function($hook) {
    // Only load on the EZ Horoscope settings page
    if ($hook !== 'settings_page_ez-horoscope-settings') {
        return;
    }
    
    wp_enqueue_script('jquery');
    
    // Ensure ajaxurl is available
    wp_localize_script('jquery', 'ezhpVoice', array(
        'ajaxurl' => admin_url('admin-ajax.php')
    ));
    
    wp_add_inline_script('jquery', '
        (function($) {
            $(document).ready(function() {
                $(document).on("click", "#ezhp-test-connection", function() {
                    $("#ezhp-test-result").html("Testing connection...");
                    $.post(ajaxurl, {
                        action: "ezhp_test_brilyi_connection"
                    }, function(response) {
                        if (response && response.success) {
                            let msg = response.data ? response.data : "Connected successfully.";
                            $("#ezhp-test-result").html("<span style=\"color:green;\">✅ " + msg + "</span>");
                        } else {
                            let msg = (response && response.data) ? response.data : "Unknown error";
                            $("#ezhp-test-result").html("<span style=\"color:red;\">❌ " + msg + "</span>");
                        }
                    }).fail(function() {
                        $("#ezhp-test-result").html("<span style=\"color:red;\">❌ Request failed</span>");
                    });
                });
            });
        })(jQuery);
    ');
});

// -------------------------
// Sanitizer for Brilyi API Key
// -------------------------
function ezhp_voice_api_key_sanitizer($new_value)
{
    $old_value = get_option('ezhp_voice_api_key');

    // Blank submission => keep existing encrypted value
    if (empty($new_value)) {
        return $old_value;
    }

    // Encrypt and store last 4 chars separately
    $encrypted = ezhp_encrypt_api_key($new_value);
    $last4 = substr($new_value, -4);
    update_option('ezhp_voice_api_key_last4', $last4, false);

    return $encrypted;
}

// -------------------------
// Encryption Helpers
// -------------------------
function ezhp_encrypt_api_key($api_key)
{
    $encryption_key = wp_salt('auth');
    $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('AES-256-CBC'));

    $encrypted = openssl_encrypt($api_key, 'AES-256-CBC', $encryption_key, OPENSSL_RAW_DATA, $iv);

    $encrypted_b64 = base64_encode($encrypted);
    $iv_b64 = base64_encode($iv);

    $final = $encrypted_b64 . '::' . $iv_b64;

    // Debug logs
    if (defined('WP_DEBUG') && WP_DEBUG) {
        //error_log('=== ezhp_encrypt_api_key ===');
        //error_log('API Key (input): ' . $api_key);
        //error_log('Encrypted (base64): ' . $encrypted_b64);
        //error_log('IV (base64): ' . $iv_b64);
        //error_log('Stored value: ' . $final);
    }

    return $final;
}

function ezhp_decrypt_api_key($data)
{
    $encryption_key = wp_salt('auth');

    if (defined('WP_DEBUG') && WP_DEBUG) {
        //error_log('=== ezhp_decrypt_api_key ===');
        //error_log('Stored value (raw): ' . $data);
    }

    if (empty($data) || strpos($data, '::') === false) {
        if (defined('WP_DEBUG') && WP_DEBUG) {
            //error_log('Failed: invalid encrypted API key format');
        }
        return false;
    }

    list($encrypted_b64, $iv_b64) = explode('::', $data, 2);

    $encrypted = base64_decode($encrypted_b64);
    $iv = base64_decode($iv_b64);

    if (defined('WP_DEBUG') && WP_DEBUG) {
        //error_log('Encrypted (decoded length): ' . strlen($encrypted));
        //error_log('IV (decoded length): ' . strlen($iv));
    }

    if ($encrypted === false || $iv === false) {
        if (defined('WP_DEBUG') && WP_DEBUG) {
            //error_log('Failed: base64_decode failed for encrypted data or IV');
        }
        return false;
    }

    $decrypted = openssl_decrypt($encrypted, 'AES-256-CBC', $encryption_key, OPENSSL_RAW_DATA, $iv);

    if ($decrypted === false) {
        if (defined('WP_DEBUG') && WP_DEBUG) {
            //error_log('Failed: openssl_decrypt returned false');
        }
    } else {
        if (defined('WP_DEBUG') && WP_DEBUG) {
            //error_log('Decryption succeeded: ' . $decrypted);
        }
    }

    return $decrypted;
}




function ezhp_get_voice_api_key()
{
    $enc = get_option('ezhp_voice_api_key');
    return $enc ? ezhp_decrypt_api_key($enc) : '';
}

// -------------------------
// AJAX Handler: Test Brilyi Connection
// -------------------------
add_action('wp_ajax_ezhp_test_brilyi_connection', function () {
    if (!current_user_can('manage_options')) {
        wp_send_json_error('Unauthorized');
    }

    $api_key = ezhp_get_voice_api_key();
    if (empty($api_key)) {
        wp_send_json_error('No API key configured. To get your API key register on the Brilyi platform.');
    }

    // Your real endpoint that requires x-api-key
    $endpoint = apply_filters(
        'ezhp_brilyi_test_endpoint',
        'https://dashboard.brilyi.com/api/agentsapi/GetAgentsForPlugin'
    );

    $resp = wp_remote_get($endpoint, [
        'headers' => [
            'Authorization' => $api_key,
            'Accept'    => 'application/json',
        ],
        'timeout' => 15,
    ]);

    if (is_wp_error($resp)) {
        $msg = 'Request failed: ' . $resp->get_error_message();
        $msg .= ' — There was a problem connecting to the API. Please regenerate your API key in the Brilyi Dashboard and then copy and paste it into the API field and save the settings and try again. Alternatively, if the issue persists, you can generate the script tag in the Web Agent settings of your agent and copy and paste that to the page you want it displayed on.';
        wp_send_json_error($msg);
    }

    $code = wp_remote_retrieve_response_code($resp);
    $body = wp_remote_retrieve_body($resp);

    if ($code === 200) {
        $agents = json_decode($body, true);
        if (is_array($agents)) {
            $count = count($agents);
            if ($count > 0) {
                wp_send_json_success("Connected to Brilyi. Found {$count} agent(s). First: " . esc_html($agents[0]['Name']));
            } else {
                wp_send_json_success("Connected to Brilyi. No agents found for this organization.");
            }
        } else {
            wp_send_json_success("Connected to Brilyi, but response was not in expected format.");
        }
    } else {
        $msg = "API returned status $code – " . $body;
        $msg .= ' — There was a problem connecting to the API. Please regenerate your API key in the Brilyi Dashboard and then copy and paste it into the API field and save the settings. Alternatively, if the issue persists, you can generate the script tag in the Web Agent settings of your agent and copy and paste that to the page you want it displayed on.';
        wp_send_json_error($msg);
    }
});


// -------------------------
// AJAX: Load Agents from Brilyi API
// -------------------------
add_action('wp_ajax_ezhp_load_agents', 'ezhp_load_agents');

function ezhp_load_agents()
{
    if (! current_user_can('manage_options')) {
        wp_send_json_error('Unauthorized', 403);
    }

    // ✅ Get the encrypted API key from the correct option
    $encrypted = get_option('ezhp_voice_api_key');
    if (empty($encrypted)) {
        wp_send_json_error('API key not set');
    }

    $api_key = ezhp_decrypt_api_key($encrypted);
    if (empty($api_key)) {
        wp_send_json_error('API key decryption failed');
    }

    $response = wp_remote_get('https://dashboard.brilyi.com/api/agentsapi/GetAgentsForPlugin', [
        'headers' => [
            'Authorization' => $api_key,
        ],
        'timeout' => 20,
    ]);

    if (is_wp_error($response)) {
        $msg = $response->get_error_message();
        $msg .= ' — There was a problem connecting to the API. Please regenerate your API key in the Brilyi Dashboard and then copy and paste it into the API field and save the settings and try again. Alternatively, if the issue persists, you can generate the script tag in the Web Agent settings of your agent and copy and paste that to the page you want it displayed on.';
        wp_send_json_error($msg);
    }

    $code = wp_remote_retrieve_response_code($response);
    $body = wp_remote_retrieve_body($response);

    if ($code !== 200) {
        $msg = "API returned $code: $body";
        $msg .= ' — There was a problem connecting to the API. Please regenerate your API key in the Brilyi Dashboard and then copy and paste it into the API field and save the settings and try again. Alternatively, if the issue persists, you can generate the script tag in the Web Agent settings of your agent and copy and paste that to the page you want it displayed on.';
        wp_send_json_error($msg);
    }

    $agents = json_decode($body, true);
    if (!is_array($agents)) {
        $msg = 'Invalid response from API — There was a problem connecting to the API. Please regenerate your API key in the Brilyi Dashboard and then copy and paste it into the API field and save the settings and try again. Alternatively, if the issue persists, you can generate the script tag in the Web Agent settings of your agent and copy and paste that to the page you want it displayed on.';
        wp_send_json_error($msg);
    }

    wp_send_json_success($agents);
}


// -------------------------
// AJAX: Generate Voice Agent Shortcode
// -------------------------
add_action('wp_ajax_ezhp_generate_voice_shortcode', function () {
    if (! current_user_can('manage_options')) {
        wp_send_json_error('Unauthorized', 403);
    }

    // Verify nonce for security
    check_ajax_referer('ezhp_generate_voice_shortcode', 'security');

    $agent_id = isset($_POST['agent_id'])
        ? sanitize_text_field(wp_unslash($_POST['agent_id']))
        : '';
    if (empty($agent_id)) {
        wp_send_json_error('Missing agentId');
    }

    // Special case: Demo agent works without API key
    if ($agent_id === '03A262CA-8DAA-4620-A9B2-90A133EDA393') {
        $script_url = 'https://dashboard.brilyi.com/cdn/voice-widget.v4.js';
        
        // Store script URL instead of raw HTML
        update_option("ezhp_agent_widget_{$agent_id}", $script_url, false);
        
        // Register this agent ID
        ezhp_register_agent_widget($agent_id);

        $shortcode = '[ezhp_voice_agent_widget agent_id="' . esc_attr($agent_id) . '"]';
        wp_send_json_success([
            'shortcode' => $shortcode,
            'script'    => $script_url,
        ]);
    }

    // Otherwise require API key
    $api_key = ezhp_get_voice_api_key();
    if (empty($api_key)) {
        wp_send_json_error('No API key configured');
    }

    // Fetch widget script from Brilyi API
    $url = "https://dashboard.brilyi.com/api/agentsapi/widgetforplugin/{$agent_id}";
    $resp = wp_remote_get($url, [
        'headers' => [
            'Authorization' => $api_key,
            'Accept'        => 'text/html',
        ],
        'timeout' => 20,
    ]);

    if (is_wp_error($resp)) {
        $msg = 'Request failed: ' . $resp->get_error_message();
        $msg .= ' — There was a problem connecting to the API. Please regenerate your API key in the Brilyi Dashboard and then copy and paste it into the API field and save the settings and try again. Alternatively, if the issue persists, you can generate the script tag in the Web Agent settings of your agent and copy and paste that to the page you want it displayed on.';
        wp_send_json_error($msg);
    }

    $code = wp_remote_retrieve_response_code($resp);
    $body = wp_remote_retrieve_body($resp);

    if ($code !== 200 || empty($body)) {
        $msg = "API returned $code: $body";
        $msg .= ' — There was a problem connecting to the API. Please regenerate your API key in the Brilyi Dashboard and then copy and paste it into the API field and save the settings and try again. Alternatively, if the issue persists, you can generate the script tag in the Web Agent settings of your agent and copy and paste that to the page you want it displayed on.';
        wp_send_json_error($msg);
    }

    // Save script locally
    update_option("ezhp_agent_widget_{$agent_id}", $body, false);
    
    // Register this agent ID
    ezhp_register_agent_widget($agent_id);

    // Return shortcode to user
    $shortcode = '[ezhp_voice_agent_widget agent_id="' . esc_attr($agent_id) . '"]';
    wp_send_json_success([
        'shortcode' => $shortcode,
        'script'    => $body,
    ]);
});


// -------------------------
// Helper: Get all agent widget IDs
// -------------------------
function ezhp_get_agent_widget_ids()
{
    // Try to get from cache first
    $agent_ids = wp_cache_get('ezhp_agent_widget_ids', 'ezhp_voice');
    
    if (false === $agent_ids) {
        // Cache miss - get from our stored list
        $agent_ids = get_option('ezhp_agent_widget_ids', array());
        
        // Cache the results for 1 hour
        wp_cache_set('ezhp_agent_widget_ids', $agent_ids, 'ezhp_voice', HOUR_IN_SECONDS);
    }
    
    return $agent_ids;
}

// -------------------------
// Helper: Register an agent widget ID
// -------------------------
function ezhp_register_agent_widget($agent_id)
{
    $agent_ids = get_option('ezhp_agent_widget_ids', array());
    
    if (!in_array($agent_id, $agent_ids, true)) {
        $agent_ids[] = $agent_id;
        update_option('ezhp_agent_widget_ids', $agent_ids, false);
    }
    
    // Clear cache when agent is added
    wp_cache_delete('ezhp_agent_widget_ids', 'ezhp_voice');
}

// -------------------------
// Enqueue Voice Agent Scripts (Demo Agent Only)
// -------------------------
function ezhp_enqueue_voice_agent_scripts()
{
    $agent_ids = ezhp_get_agent_widget_ids();

    if (empty($agent_ids)) {
        return;
    }

    // Only process demo agent - non-demo agents output script tags directly via shortcode
    $demo_agent_id = '03A262CA-8DAA-4620-A9B2-90A133EDA393';
    
    if (!in_array($demo_agent_id, $agent_ids, true)) {
        return;
    }

    $script_data = get_option("ezhp_agent_widget_{$demo_agent_id}", '');
    
    if (empty($script_data)) {
        return;
    }

    // Enqueue demo agent script
    wp_enqueue_script(
        "ezhp-voice-widget-{$demo_agent_id}",
        'https://dashboard.brilyi.com/cdn/voice-widget.v4.js',
        array(),
        EZHP_PLUGIN_VERSION,
        true
    );
    
    // Add data-agent-id attribute
    add_filter('script_loader_tag', function($tag, $handle) use ($demo_agent_id) {
        if ($handle === "ezhp-voice-widget-{$demo_agent_id}") {
            $tag = str_replace(' src=', ' data-agent-id="' . esc_attr($demo_agent_id) . '" defer src=', $tag);
        }
        return $tag;
    }, 10, 2);
}


// add_action('wp_enqueue_scripts', function() {
//     $agent_ids = ezhp_get_agent_widget_ids();
//     $demo_agent_id = '03A262CA-8DAA-4620-A9B2-90A133EDA393';

//     // Only enqueue the demo agent if:
//     // 1. The demo agent is registered, AND
//     // 2. No other (non-demo) agents are registered
//     if (in_array($demo_agent_id, $agent_ids, true)) {
//         $non_demo_agents = array_filter($agent_ids, function($id) use ($demo_agent_id) {
//             return $id !== $demo_agent_id;
//         });

//         if (empty($non_demo_agents)) {
//             ezhp_enqueue_voice_agent_scripts();
//         }
//     }
// });

add_action('wp_footer', function() {
    global $ezhp_voice_agent_shortcode_used;

    // Only load if shortcode has appeared on the page
    if (!$ezhp_voice_agent_shortcode_used) {
        return;
    }

    // Now run your existing enqueue logic
    $agent_ids = ezhp_get_agent_widget_ids();
    $demo_agent_id = '03A262CA-8DAA-4620-A9B2-90A133EDA393';

    if (in_array($demo_agent_id, $agent_ids, true)) {
        $non_demo_agents = array_filter($agent_ids, function($id) use ($demo_agent_id) {
            return $id !== $demo_agent_id;
        });

        if (empty($non_demo_agents)) {
            ezhp_enqueue_voice_agent_scripts();
        }
    }
});


// -------------------------
// Shortcode: Voice Agent Widget
// -------------------------
function ezhp_voice_agent_widget_shortcode($atts)
{

    global $ezhp_voice_agent_shortcode_used;
$ezhp_voice_agent_shortcode_used = true;

    $atts = shortcode_atts([
        'agent_id' => '',
    ], $atts);

    $agent_id = sanitize_text_field($atts['agent_id']);
    if (empty($agent_id)) {
        return '<!-- No agent_id provided -->';
    }

    $script = get_option("ezhp_agent_widget_{$agent_id}", '');
    if (empty($script)) {
        return '<!-- No saved widget found for agent ' . esc_html($agent_id) . ' -->';
    }

    // For demo agent - keep existing working behavior
    if ($agent_id === '03A262CA-8DAA-4620-A9B2-90A133EDA393') {
        return '<div id="ezhp-voice-widget-' . esc_attr($agent_id) . '"></div>';
    }

    // For non-demo agents - output the script tag exactly as returned from API
    // Use wp_kses to allow only script tags with specific attributes for security
    $allowed_html = array(
        'script' => array(
            'src' => array(),
            'data-backend' => array(),
            'data-agent-id' => array(),
            'data-button-text' => array(),
            'data-vars' => array(),
            'defer' => array(),
            'async' => array(),
            'type' => array(),
        ),
    );
    
    return wp_kses($script, $allowed_html);
}

add_shortcode('ezhp_voice_agent_widget', 'ezhp_voice_agent_widget_shortcode');