<?php
/*
Plugin Name: Brain Pod AI Writer
Description: Bulk article generator, Article generator within the WordPress Editor, and an AI chat bot.
Version: 1.1.4
Author: Brain Pod AI
Author URI: https://brainpod.ai
License: GPLv3
*/

// Enqueue plugin styles

if ( ! defined( 'ABSPATH' ) ) exit;

function brainpod_ai_custom_section_plugin_enqueue_styles() {
    wp_enqueue_style('custom-section-plugin-styles', plugins_url('styles.css', __FILE__));
    wp_enqueue_style('tagify', plugins_url('assets/tagify/tagify.css', __FILE__), array(), '4.9.0');
    wp_enqueue_script('tagify', plugins_url('assets/tagify/tagify.js', __FILE__), array(), '4.9.0', true);
    wp_enqueue_script('tagify-polyfills',plugins_url('assets/tagify/tagify.polyfills.min.js', __FILE__), array('tagify'), '4.9.0', true);
    wp_enqueue_script('custom-section-plugin-scripts', plugins_url('assets/js/scripts.js', __FILE__), array('tagify', 'tagify-polyfills', 'jquery'), '1.0', true);
    wp_enqueue_script('my-chatbot-script', plugin_dir_url(__FILE__) . 'assets/js/chat.js?v=1.2.0', array('jquery'), '1.0.0', true);

    wp_localize_script('my-chatbot-script', 'widgetData', array(
        'chatWidgetURL' => plugin_dir_url(__FILE__) . 'chat-widget.php',
        'apiKey' => esc_js(get_option('brain_pod_ai_writer_api_key')),
        'hoy3lrg_js' => plugin_dir_url(__FILE__) . 'assets/js/hoy3lrg.js',
        'chat_widget_js' => plugin_dir_url(__FILE__) . 'assets/js/chat-widget-js.js?v=1.1.1',
        'jquer_min_js' => includes_url() . 'js/jquery/jquery.min.js',
        'reset_css' => plugin_dir_url(__FILE__) . 'assets/css/reset.min.css',
        'fontawesome_css' => plugin_dir_url(__FILE__) . 'assets/fontawesome/css/all.min.css',
        'chat_widget_css' => plugin_dir_url(__FILE__) . 'assets/css/chat-widget-css.css?v=1.0.0',
        'Blue_purple_colorful_smart_brain_logo' => plugin_dir_url(__FILE__) . 'assets/images/Blue_purple_colorful_smart_brain_logo.png',
    ));
    wp_enqueue_style('widget-styles', plugins_url('assets/css/widget.css', __FILE__));
}
add_action('admin_enqueue_scripts', 'brainpod_ai_custom_section_plugin_enqueue_styles');

function brain_pod_ai_writer_render_settings_page() {
    ?>
    <div class="wrap">
        <h1>Brain Pod AI Writer Settings</h1>

        <!-- API Key Form -->
        <form method="post" action="options.php">
            <?php
            settings_fields('brain_pod_ai_writer_options_group');
            do_settings_sections('brain_pod_ai_writer');
            ?>
            <table class="form-table">
                <tr>
                    <th scope="row">API Key:</th>
                    <td>
                        <input type="text" name="brain_pod_ai_writer_api_key" value="<?php echo esc_attr(get_option('brain_pod_ai_writer_api_key')); ?>" size="50">
                    </td>
                </tr>
            </table>
            <?php submit_button(); ?>
        </form>
    </div>
    <?php
}


function brain_pod_ai_writer_render_bulk_articles_page() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'generated_articles';

    $articles = $wpdb->get_results("SELECT * FROM $table_name");

    ?>
    <div class="wrap">
        <h1>Brain Pod AI Writer Bulk Articles</h1>
        <hr>

        <!-- Bulk Article Form -->
        <form method="post" action="<?php echo esc_url( admin_url('admin-post.php') ); ?>" enctype="multipart/form-data" id="bulk-article-form">
            <input type="hidden" name="action" value="brain_pod_ai_writer_bulk_articles_form">
            <input type="text" name="app_password" value="<?php echo esc_attr(get_option('brain_pod_ai_writer_app_password')); ?>" hidden>
            <input type="text" name="username" value="<?php echo esc_attr(wp_get_current_user()->user_login); ?>" hidden>

            <table class="form-table">
                <tr valign="top">
                    <th scope="row">Project Name:</th>
                    <td>
                        <input type="text" name="project_name" placeholder="Project name" required>
                    </td>
                </tr>
                <tr valign="top">
                    <th scope="row">Keywords:</th>
                    <td style="padding-bottom: 0px">
                        <input type="radio" id="input-keywords" name="keywords-source" value="input" checked>
                        <label for="input-keywords" style="margin-right: 10px">Input keywords:</label>
                        <input type="radio" id="upload-csv" name="keywords-source" value="upload">
                        <label for="upload-csv">Upload CSV:</label>
                    </td>
                </tr>
                <tr valign="top">
                    <th scope="row"></th>
                    <td style="padding-top: 0px">
                        <input type="text" id="brain-pod-ai-writer-keywords" class="brain-pod-ai-writer-keywords" placeholder="Enter Keywords" name="brain_pod_ai_writer_keywords" size="50">
                        <input type="file" id="brain-pod-ai-writer-keywords-csv" name="brain_pod_ai_writer_keywords_csv" style="display: none;">
                    </td>
                </tr>
                <tr valign="top">
                    <th scope="row">Status:</th>
                    <td>
                        <select name="brain_pod_ai_writer_status">
                            <?php
                            $statuses = get_post_statuses();
                            foreach ($statuses as $status => $status_name) {
                            ?>
                                <option value='<?php echo esc_attr($status) ?>'><?php echo esc_attr($status_name) ?></option>
                            <?php
                            }
                            ?>
                        </select>
                    </td>
                </tr>
                <tr valign="top">
                    <th scope="row">Category:</th>
                    <td>
                        <input type="text" name="category" placeholder="Category" required>
                    </td>
                </tr>
                <tr valign="top">
                    <th scope="row">Tags:</th>
                    <td>
                        <input type="text" id="tags-input" name="tags" value='' placeholder="Tags" required>
                    </td>
                </tr>
                <tr valign="top">
                    <th scope="row">
                        <p id="keywords-detected">Number of keywords detected: <span id="keyword-count">0</span></p>
                        <p id="tokens-needed">Tokens needed for this project: <span id="token-count">0</span></p>
                        <?php submit_button('Create Bulk Article Project'); ?>
                    </th>
                </tr>
            </table>
            
        </form>
    </div>
    <script>
jQuery(document).ready(function($) {
    var taginput = document.querySelector('#tags-input');
    var tagify = new Tagify(taginput);

    $('input[name="keywords-source"]').on('change', function() {
        if ($('#input-keywords').is(':checked')) {
            $('.brain-pod-ai-writer-keywords').show();
            $('#brain-pod-ai-writer-keywords-csv').hide();
        } else {
            $('#brain-pod-ai-writer-keywords-csv').show();
            $('.brain-pod-ai-writer-keywords').hide();
        }
    });
    
    $('#bulk-article-form').submit(function(e) {
        e.preventDefault();

        var formData = new FormData(this);
        var keywordsSourceInput = $('input[name="keywords-source"]:checked').val();
        var keywordsTextInput = $('#brain-pod-ai-writer-keywords');
        var keywordsFileInput = $('#brain-pod-ai-writer-keywords-csv');
        var keywords = [];

        function handleTextInput() {
            var keywordsJson = keywordsTextInput.val();
            var keywordsObjectsArray = JSON.parse(keywordsJson);
            return keywordsObjectsArray.map(function(item) {
                return item.value;
            });
        }

        function handleFileInput(callback) {
            var file = keywordsFileInput[0].files[0];
            if (file) {
                var reader = new FileReader();
                reader.onload = function(e) {
                    var contents = e.target.result;
                    var keywordsArray = contents.split('\n').map(function(item) {
                        return item.trim();
                    });
                    callback(keywordsArray);
                };
                reader.readAsText(file);
            } else {
                callback([]);  // if no file, callback with an empty array
            }
        }

        function proceedAfterKeywordsSet() {
            var tags = JSON.parse(formData.get('tags'));
            var tagsArray = tags.map(function(item) {
                return item.value;
            });

            var data = {
                "keywords": keywords,
                "article_name": formData.get('project_name'),
                "is_wordpress": true,
                "wp_tags": tagsArray,
                "wp_category": formData.get('category'),
                "wp_status": formData.get('brain_pod_ai_writer_status'),
                "wp_username": formData.get('username'),
                "wp_app_password": formData.get('app_password'),
                "site_url": "<?php echo esc_url(get_site_url()); ?>"
            };

            var apiKey = "<?php echo esc_js(get_option('brain_pod_ai_writer_api_key')); ?>";
            $.ajax({
                url: "https://start.brainpod.ai/api/wp-plugin/bulk-article",
                type: 'POST',
                data: JSON.stringify(data),
                processData: false,
                contentType: 'application/json',
                headers: {
                    "Authorization": "Bearer " + apiKey
                },
                success: function(responseData) {
                    console.log(responseData);

                    var message = 'Oops, ' + responseData.message;
                    var confirmAddCredits = confirm(message);

                    if (confirmAddCredits) {
                        $('#bulk-article-form')[0].reset();
                        tagify.removeAllTags();
                    }
                },
                error: function(xhr, status, error) {
                    console.log('An error occurred: ', error);
                    var errorMessage = xhr && xhr.responseJSON && xhr.responseJSON.message ? xhr.responseJSON.message : error;
                    alert(errorMessage);
                }
            });
        }

        if (keywordsSourceInput == 'input') {
            keywords = handleTextInput();
            proceedAfterKeywordsSet();
        } else if (keywordsSourceInput == 'upload') {
            handleFileInput(function(keywordsArray) {
                keywords = keywordsArray;
                proceedAfterKeywordsSet();
            });
        }
    });

});

</script>
<style type="text/css">
    .form-table{
        background: white;
        padding: 5px;
        border-radius: 10px;
    }
    .form-table th {
        padding: 20px 10px 20px 15px;
    }
    .form-table .tagify{
        border: 1px solid #8c8f94;
        border-radius: 5px;
        min-width: 50%;
    }
    .form-table input[type="text"]{
        border: 1px solid #8c8f94;
        border-radius: 5px;
        min-width: 50%;
        height: 37px;
    }
</style>


    <?php
}

function brain_pod_ai_writer_add_menu() {
    add_menu_page(
        'Brain Pod AI', // Page title`
        'Brain Pod AI', // Menu title
        'manage_options', // Capability
        'brain-pod-ai-writer', // Menu slug
        'brain_pod_ai_writer_render_settings_page', // Function to render the page
        'dashicons-text', // Icon
        100 // Position
    );

    add_submenu_page(
        'brain-pod-ai-writer', // Parent menu slug
        'Bulk Articles', // Page title
        'Bulk Articles', // Menu title
        'manage_options', // Capability
        'brain-pod-ai-writer-bulk-articles', // Menu slug
        'brain_pod_ai_writer_render_bulk_articles_page' // Function to render the page
    );
}
add_action('admin_menu', 'brain_pod_ai_writer_add_menu');

function brain_pod_ai_writer_settings_init() {
    register_setting('brain_pod_ai_writer_options_group', 'brain_pod_ai_writer_api_key');
    register_setting('brain_pod_ai_writer_options_group', 'brain_pod_ai_writer_app_password'); // Register the new setting

    add_settings_section(
        'brain_pod_ai_writer_settings_section',
        'Settings',
        '',
        'brain_pod_ai_writer'
    );
}
add_action('admin_init', 'brain_pod_ai_writer_settings_init');


// localize script
function brain_pod_ai_writer_localize_scripts() {
    wp_localize_script('custom-section-plugin-scripts', 'brainPodAIWriter', array(
        'apiKey' => get_option('brain_pod_ai_writer_api_key'),
        'ajaxUrl' => admin_url('admin-ajax.php')
    ));
}

add_action('admin_enqueue_scripts', 'brain_pod_ai_writer_localize_scripts', 11);
// Register the custom meta box
function brain_pod_ai_custom_section_plugin_register_meta_box() {
    add_meta_box(
        'custom-section-plugin-meta-box',
        'Brain Pod AI Writer',
        'brain_pod_ai_custom_section_plugin_render_meta_box',
        'post',
        'normal',
        'high'
    );
}

add_action('add_meta_boxes', 'brain_pod_ai_custom_section_plugin_register_meta_box');

// Render the custom meta box
function brain_pod_ai_custom_section_plugin_render_meta_box($post) {
    $custom_title = get_post_meta($post->ID, '_brain_pod_ai_writer_title', true);
    $custom_headings = get_post_meta($post->ID, '_brain_pod_ai_writer_headings', true);
    $custom_length = get_post_meta($post->ID, '_brain_pod_ai_writer_length', true);

    wp_nonce_field('brain_pod_ai_writer_nonce', 'brain_pod_ai_writer_nonce_field');
    $csrf_token = 'your_generated_csrf_token_here';

    $html = '<input type="hidden" id="brain-pod-ai-writer-csrf-token" value="' . esc_attr($csrf_token) . '">';
    $html .= '<div class="brain-pod-ai-writer">';
    $html .= '<label for="brain-pod-ai-writer-headings" hidden>Headings (Enter up to 10):</label>';
    $html .= '<input hidden type="text" id="brain-pod-ai-writer-headings" name="brain_pod_ai_writer_headings" value="' . esc_attr($custom_headings) . '">';

    $html .= '<label hidden for="brain-pod-ai-writer-length">Length:</label>';
    $html .= '<select hidden id="brain-pod-ai-writer-length" name="brain_pod_ai_writer_length">';
    $html .= '<option value="short" ' . selected($custom_length, 'short', false) . '>Short</option>';
    $html .= '<option value="normal" ' . selected($custom_length, 'normal', false) . '>Normal</option>';
    $html .= '<option value="long" ' . selected($custom_length, 'long', false) . '>Long</option>';
    $html .= '</select>';
    $html .= '<button type="button" class="button button-primary" id="brain-pod-ai-writer-generate">Generate</button>';
    $html .= '</div>';

    $html .= '<div id="brain-pod-ai-writer-loading" hidden>Writing your Content...</div>';

    $allowed_html = array(
        'select' => array(
            'class' => true, // Allows the class attribute
            'id' => true, // Allows the id attribute
            'name' => true, // Allows the name attribute
            'disabled' => false, // Allows the disabled attribute
            'hidden'=>true
        ),
        'option' => array(
            'value' => true,
            'selected' => true,
        ),
        'label' => array(
            'hidden'=>true,
            'id'=>true,
            'class'=>true,
            'for'=>true
        ),
        'div' => array(
            'class'=>true,
            'id'=>true,
            'style'=>true,
            'hidden'=>true,
        ),
        'span' => array(
            'class'=>true,
            'id'=>true,
            'style'=>true,
        ),
        'button' => array(
            'class'=>true,
            'name' => true, // Allows the name attribute
            'id'=>true,
            'type'=>true
        ),
        'input' => array(
            'class'=>true,
            'name' => true, // Allows the name attribute
            'id'=>true,
            'style'=>true,
            'hidden'=>true,
            'type'=>true
        ),
    );

    echo wp_kses($html, $allowed_html);

    // printf($html,
    //     esc_attr($csrf_token),
    //     esc_attr($custom_headings),
    //     selected($custom_length, 'short', false),
    //     selected($custom_length, 'normal', false),
    //     selected($custom_length, 'long', false)
    // );
}
