<?php
function cybreed_settings_module_init() {
    // Register setting for storing the display options
    function cybreed_display_register_settings() {
        register_setting(
            'cybreed-display-settings-group',
            'cybreed_display_options',
            array(
                'type'              => 'array',
                'sanitize_callback' => 'cybreed_sanitize_display_options',
            )
        );
    }
    add_action('admin_init', 'cybreed_display_register_settings');

    function cybreed_sanitize_display_options($options) {
        if (!is_array($options)) {
            return array();
        }

        // Sanitize each option within the array
        foreach ($options as $key => $value) {
            $options[$key] = is_array($value) ? array_map('sanitize_text_field', $value) : sanitize_text_field($value);
        }

        return $options;
    }
    
    function render_cybreed_settings_page() {
        $access_token = get_option('cybreed_access_token', '');
        $user_id = get_option('cybreed_user_id', '');
        $selected_organisation_id = get_option('cybreed_selected_organisation_id', '');
        $selected_chat_id = get_option('cybreed_selected_chat_id', '');
        $display_options = get_option('cybreed_display_options', []);
        
        // Ensure specific_pages and excluded_pages are always arrays
        $specific_pages = isset($display_options['specific_pages']) && is_array($display_options['specific_pages'])
            ? $display_options['specific_pages']
            : [];
        $excluded_pages = isset($display_options['excluded_pages']) && is_array($display_options['excluded_pages'])
            ? $display_options['excluded_pages']
            : [];
        
        // Retrieve the single page ID option
        $selected_single_page = get_option('cybreed_single_page_id', 0);

        // Get organizations and chats
        $organisations = fetch_organisations($access_token, $user_id);
        $chats = !empty($selected_organisation_id) ? fetch_chats($selected_organisation_id, $access_token) : array();

        // Fetch all pages for display settings
        $pages = get_pages();

        if (!$access_token) {
            ?>
            <div class="cybreed-dashboard-wrapper">
                <div id="cybreed-logo">
                    <?php 
                    $logo_id = attachment_url_to_postid(plugins_url('assets/images/logo.svg', dirname(__DIR__, 2) . '/cybreed.php'));
                    if ($logo_id) {
                        echo wp_get_attachment_image($logo_id, 'full', false, array('alt' => 'CyBreed'));
                    } else {
                        // Fallback if image is not in media library
                        echo '<img src="' . esc_url(plugins_url('assets/images/logo.svg', dirname(__DIR__, 2) . '/cybreed.php')) . '" alt="' . esc_attr('CyBreed') . '" />';
                    }
                    ?>
                </div>
                <div class="cybreed-dashboard-inner-wrapper">
                    <h1 class="cybreed-dashboard-header">Settings</h1>
                    <h2 class="cybreed-dashboard-subheader">Please log in to access settings</h2>
                </div>
            </div>
            <?php
        } else {
            ?>
            <div class="cybreed-dashboard-wrapper">
                <div id="cybreed-logo">
                    <?php 
                    $logo_id = attachment_url_to_postid(plugins_url('assets/images/logo.svg', dirname(__DIR__, 2) . '/cybreed.php'));
                    if ($logo_id) {
                        echo wp_get_attachment_image($logo_id, 'full', false, array('alt' => 'CyBreed'));
                    } else {
                        // Fallback if image is not in media library
                        echo '<img src="' . esc_url(plugins_url('assets/images/logo.svg', dirname(__DIR__, 2) . '/cybreed.php')) . '" alt="' . esc_attr('CyBreed') . '" />';
                    }
                    ?>
                </div>
                
                <div class="cybreed-dashboard-inner-wrapper settings-panel">
                    <h1 class="cybreed-dashboard-header">Settings</h1>
                    <h2 class="cybreed-dashboard-subheader">Configure your Cybreed chat widget</h2>
                    <form class="cybreed-settings-form">
                    <?php wp_nonce_field('cybreed_settings_action', 'cybreed_settings_nonce'); ?>
                    <div class="cybreed-auth-container">
                        <div class="cybreed-auth-card">
                            <h3>Organization</h3>
                                <select name="organisation_id" style="width: 100%; margin-bottom: 1rem;">
                                    <option value="" <?php selected($selected_organisation_id, ''); ?>>Select an Organization</option>
                                    <?php
                                    foreach ($organisations as $organisation):
                                        echo '<option value="' . esc_attr($organisation['uuid']) . '"' . 
                                             selected($selected_organisation_id, $organisation['uuid'], false) . '>' . 
                                             esc_html($organisation['name']) . '</option>';
                                    endforeach;
                                    ?>
                                </select>
                                
                            <h3>Chat Selection</h3>
                            <select name="chat_id" style="width: 100%; margin-bottom: 1rem;">
                                <option value="" <?php selected($selected_chat_id, ''); ?>>Select a Chat</option>
                                <?php if ($chats): foreach ($chats as $chat):
                                    echo '<option value="' . esc_attr($chat['uuid']) . '"' . 
                                         selected($selected_chat_id, $chat['uuid'], false) . '>' . 
                                         esc_html($chat['name']) . '</option>';
                                endforeach; endif; ?>
                            </select>

                            <h3>Display Settings</h3>
                                <select name="display_type" id="cybreed_display_type" style="width: 100%; margin-bottom: 1rem;">
                                    <option value="all" <?php selected($display_options['display_type'] ?? '', 'all'); ?>>All Pages</option>
                                    <option value="specific" <?php selected($display_options['display_type'] ?? '', 'specific'); ?>>Specific Pages</option>
                                    <option value="exclude" <?php selected($display_options['display_type'] ?? '', 'exclude'); ?>>Exclude Pages</option>
                                    <option value="single" <?php selected($display_options['display_type'] ?? '', 'single'); ?>>Single Page</option>
                                </select>

                                <div class="display-specific" style="display: none;">
                                    <div class="cybreed-checkbox-list">
                                        <?php foreach ($pages as $page): ?>
                                            <label class="cybreed-checkbox-item">
                                                <input type="checkbox" name="specific_pages[]" value="<?php echo esc_attr($page->ID); ?>"
                                                    <?php echo in_array($page->ID, $specific_pages) ? 'checked' : ''; ?>>
                                                <span><?php echo esc_html($page->post_title); ?></span>
                                            </label>
                                        <?php endforeach; ?>
                                    </div>
                                </div>

                                <div class="display-exclude" style="display: none;">
                                    <div class="cybreed-checkbox-list">
                                        <?php foreach ($pages as $page): ?>
                                            <label class="cybreed-checkbox-item">
                                                <input type="checkbox" name="excluded_pages[]" value="<?php echo esc_attr($page->ID); ?>"
                                                    <?php echo in_array($page->ID, $excluded_pages) ? 'checked' : ''; ?>>
                                                <span><?php echo esc_html($page->post_title); ?></span>
                                            </label>
                                        <?php endforeach; ?>
                                    </div>
                                </div>

                                <div class="display-single" style="display: none;">
                                    <select name="cybreed_single_page_id" style="width: 100%; margin-bottom: 1rem;">
                                        <option value="0" <?php selected($selected_single_page, 0); ?>>None</option>
                                        <?php foreach ($pages as $page): ?>
                                            <option value="<?php echo esc_attr($page->ID); ?>" 
                                                <?php selected($selected_single_page, $page->ID); ?>>
                                                <?php echo esc_html($page->post_title); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                        </div>
                    </div>
                    <div style="text-align: center; margin-top: 2rem;">
                        <button type="submit" class="cybreed-button">Save Settings</button>
                    </div>
                    </form>
                </div>
            </div>
            <?php
        }

        // Add JavaScript for display settings
        ?><script type="text/javascript">
        jQuery(document).ready(function($) {
            function toggleDisplayFields() {
                const displayType = $('#cybreed_display_type').val();
                $('.display-specific').toggle(displayType === 'specific');
                $('.display-exclude').toggle(displayType === 'exclude');
                $('.display-single').toggle(displayType === 'single');
            }

            $('#cybreed_display_type').on('change', toggleDisplayFields);
            toggleDisplayFields(); // Initialize on page load

            // Add "Select All" functionality for checkboxes
            function addSelectAllButton(containerSelector, labelText) {
                const container = $(containerSelector);
                if (container.length) {
                    const selectAllBtn = $('<button>', {
                        type: 'button',
                        class: 'cybreed-select-all',
                        text: 'Select All'
                    });

                    const clearAllBtn = $('<button>', {
                        type: 'button',
                        class: 'cybreed-clear-all',
                        text: 'Clear All'
                    });

                    const buttonContainer = $('<div>', {
                        class: 'cybreed-checkbox-buttons'
                    }).append(selectAllBtn).append(clearAllBtn);

                    container.find('.cybreed-checkbox-list').before(buttonContainer);

                    selectAllBtn.on('click', function() {
                        container.find('input[type="checkbox"]').prop('checked', true);
                    });

                    clearAllBtn.on('click', function() {
                        container.find('input[type="checkbox"]').prop('checked', false);
                    });
                }
            }

            addSelectAllButton('.display-specific', 'Specific Pages');
            addSelectAllButton('.display-exclude', 'Excluded Pages');
        });
        </script><?php
    }
}

// AJAX handler for fetching chats
function cybreed_handle_fetch_chats() {
    check_ajax_referer('cybreed_settings_action', 'nonce');
    
    $access_token = get_option('cybreed_access_token', '');
    $organisation_id = isset($_POST['organisation_id']) ? sanitize_text_field(wp_unslash($_POST['organisation_id'])) : '';
    
    if (empty($organisation_id)) {
        wp_send_json([
            'success' => false,
            'message' => 'Please select an organization.'
        ]);
    }
    
    // Fetch updated chats list
    $chats = fetch_chats($organisation_id, $access_token);
    
    if (empty($chats)) {
        $chats = array();
        wp_send_json(['success' => true, 'chats' => []]);
    }
    
    wp_send_json([
        'success' => true,
        'message' => 'Organization updated successfully',
        'chats' => $chats
    ]);
}
add_action('wp_ajax_cybreed_fetch_chats', 'cybreed_handle_fetch_chats');

// AJAX handler for chat update
function cybreed_handle_chat_update() {
    check_ajax_referer('cybreed_chat_action', 'nonce');
    
    $chat_id = isset($_POST['chat_id']) ? sanitize_text_field(wp_unslash($_POST['chat_id'])) : '';
    
    if (empty($chat_id)) {
        wp_send_json([
            'success' => false,
            'message' => 'Please select a chat.'
        ]);
    }
    
    update_option('cybreed_selected_chat_id', $chat_id);
    
    wp_send_json([
        'success' => true,
        'message' => 'Chat updated successfully'
    ]);
}
add_action('wp_ajax_cybreed_update_chat', 'cybreed_handle_chat_update');

// AJAX handler for display settings update
function cybreed_handle_display_update() {
    check_ajax_referer('cybreed_display_action', 'nonce');
    
    $display_type = isset($_POST['display_type']) ? sanitize_text_field(wp_unslash($_POST['display_type'])) : '';
    $specific_pages = isset($_POST['specific_pages']) ? array_map('intval', $_POST['specific_pages']) : [];
    $excluded_pages = isset($_POST['excluded_pages']) ? array_map('intval', $_POST['excluded_pages']) : [];
    $selected_single_page = isset($_POST['cybreed_single_page_id']) ? intval($_POST['cybreed_single_page_id']) : 0;
    
    $display_options = [
        'display_type' => $display_type,
        'specific_pages' => $specific_pages,
        'excluded_pages' => $excluded_pages,
    ];
    
    update_option('cybreed_display_options', $display_options);
    update_option('cybreed_single_page_id', $selected_single_page);
    
    wp_send_json([
        'success' => true,
        'message' => 'Display settings updated successfully'
    ]);
}
add_action('wp_ajax_cybreed_update_display', 'cybreed_handle_display_update');

// AJAX handler for saving all settings at once
function cybreed_handle_save_all_settings() {
    check_ajax_referer('cybreed_settings_action', 'nonce');
    
    $organisation_id = isset($_POST['organisation_id']) ? sanitize_text_field(wp_unslash($_POST['organisation_id'])) : '';
    $chat_id = isset($_POST['chat_id']) ? sanitize_text_field(wp_unslash($_POST['chat_id'])) : '';
    $display_type = isset($_POST['display_type']) ? sanitize_text_field(wp_unslash($_POST['display_type'])) : '';
    $specific_pages = isset($_POST['specific_pages']) ? array_map('intval', (array)$_POST['specific_pages']) : [];
    $excluded_pages = isset($_POST['excluded_pages']) ? array_map('intval', (array)$_POST['excluded_pages']) : [];
    $selected_single_page = isset($_POST['cybreed_single_page_id']) ? intval($_POST['cybreed_single_page_id']) : 0;
    
    // Save organization and get chats
    $chats = null;
    if ($organisation_id) {
        update_option('cybreed_selected_organisation_id', $organisation_id);
        $access_token = get_option('cybreed_access_token', '');
        $chats = fetch_chats($organisation_id, $access_token);
    }
    
    // Save chat selection
    if ($chat_id) {
        update_option('cybreed_selected_chat_id', $chat_id);
    }
    
    // Save display settings
    $display_options = [
        'display_type' => $display_type,
        'specific_pages' => $specific_pages,
        'excluded_pages' => $excluded_pages,
    ];
    update_option('cybreed_display_options', $display_options);
    update_option('cybreed_single_page_id', $selected_single_page);
    
    wp_send_json([
        'success' => true,
        'message' => 'All settings saved successfully',
        'chats' => $chats
    ]);
}
add_action('wp_ajax_cybreed_save_all_settings', 'cybreed_handle_save_all_settings');

// Function to enqueue scripts based on display settings
function cybreed_enqueue_scripts_based_on_settings() {
    $display_options = get_option('cybreed_display_options', []);
    
    // Ensure specific_pages and excluded_pages are arrays
    $specific_pages = isset($display_options['specific_pages']) && is_array($display_options['specific_pages'])
        ? $display_options['specific_pages']
        : [];
    $excluded_pages = isset($display_options['excluded_pages']) && is_array($display_options['excluded_pages'])
        ? $display_options['excluded_pages']
        : [];

    $should_display = false;
    $current_page_id = get_the_ID();
    $display_type = isset($display_options['display_type']) ? $display_options['display_type'] : 'all';
    $selected_single_page = get_option('cybreed_single_page_id', 0);
    
    // Only check the condition for the selected display type
    switch ($display_type) {
        case 'all':
            $should_display = true;
            break;
        case 'specific':
            $should_display = !empty($specific_pages) && in_array($current_page_id, $specific_pages);
            break;
        case 'exclude':
            $should_display = !empty($excluded_pages) ? !in_array($current_page_id, $excluded_pages) : true;
            break;
        case 'single':
            $should_display = ($current_page_id == $selected_single_page);
            break;
        default:
            $should_display = true;  // Default to showing on all pages if type is not recognized
    }

    if ($should_display) {
        $chat_id = get_option('cybreed_selected_chat_id', '');
        if (!empty($chat_id)) {
            $script_url = "https://widget.cybreed.ai/cybreed.iife.js?chatVariable={$chat_id}";
            wp_enqueue_script(
                'cybreed-widget',
                $script_url,
                [],
                '1.0.3',
                array(
                    'in_footer' => true,
                    'strategy'  => 'async'
                )
            );
        }
    }
}
add_action('wp_enqueue_scripts', 'cybreed_enqueue_scripts_based_on_settings');