<?php
 /**
 * =============================================================================
 * Plugin Name:     Blue Raven
 * Plugin URI:      https://enterrahost.com/plugins/blue-raven
 * Description:     Blue Raven is a fast, flexible WordPress plugin packed with free tools for SEO, site verification, analytics tag injection, and a powerful visual mail form builder with Bot protection. Manage meta, schema, robots.txt, and IndexNow with ease. Upgrade to unlock advanced features like WooCommerce product creation and optimization, uptime, domain and SSL monitoring, performance tracking, and site health alerts — all designed to help your site grow smarter.
 *                  
 * Version:         1.0.1
 * Author:          EnterraHost
 * Author URI:      https://enterrahost.com
 * License:         GPL-2.0-or-later
 * License URI:     https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain:     blue-raven
 * Domain Path:     /languages
 *  
 * Copyright:       (c) 2025 EnterraHost
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * =============================================================================
 * 
 * || INDEX:
 * ||   - REQUIRE
 * ||   - BLUE RAVEN MENU
 * ||   - MAIN PAGE
 * ||   - ABOUT PAGE
 * ||   - INSTALLER
 * ||   - LOAD JS
 * ||   - SITE CRON
 * ||   - HANDLE BLUE RAVEN CALLBACK
 * ||   - EXTRA ACTIONS
 * ||   - BLUE RAVEN FORM 
 * ||   - BLUE RAVEN PLUGIN LINKS 
 * || 
 * =============================================================================
 */

/*
============================================================
    REQUIRE
============================================================
*/

if (!defined('WPINC')) { die; }
if ( ! defined( 'ABSPATH' ) ) exit;

define( 'BLUERAVEN_PLUGIN_FILE', __FILE__ );
define( 'BLUERAVEN_PLUGIN_DIR', plugin_dir_path( __FILE__ ));
define( 'BLUERAVEN_PLUGIN_URL', plugin_dir_url( __FILE__ ));

require_once BLUERAVEN_PLUGIN_DIR . 'include.php';

/*
============================================================
    BLUE RAVEN MENU
============================================================
*/

add_action('admin_menu', 'blue_raven_add_admin_menu');

function blue_raven_add_admin_menu() {
    
    ## ============ Main menu item ============ ##
    
    add_menu_page(
        'Blue Raven',                                                           // Page title
        'Blue Raven',                                                           // Menu title
        'manage_options',                                                       // Capability
        'blue-raven',                                                           // Menu slug
        'blue_raven_render_admin_page',                                         // Callback
        'dashicons-hammer',                                                     // Icon
        30                                                                      // Position
    );

    ## ============ Submenu item (Settings) ============ ##
    
    add_submenu_page(
        'blue-raven',                                                           // Parent slug
        'Blue Raven Settings',                                                  // Page title
        'Settings',                                                             // Submenu title
        'manage_options',                                                       // Capability
        'blue-raven-settings',                                                  // Submenu slug
        'blue_raven_render_settings_page'                                       // Callback
    );
    
    ## ============ Submenu item (About) ============ ##
    
    add_submenu_page(
        'blue-raven',                                                           // Parent slug
        'About',                                                                // Page title
        'About',                                                                // Submenu title
        'manage_options',                                                       // Capability
        'blue-raven-about',                                                     // Submenu slug
        'blue_raven_render_about_page'                                          // Callback
    );
}

/*
============================================================
    MAIN PAGE
============================================================
*/

/**
 * Renders the Blue Raven admin page.
 * 
 * Checks capabilities, includes required files, and renders the admin interface.
 * 
 * @since 1.0.0
 * @throws Exception If any error occurs during rendering.
 */
function blue_raven_render_admin_page() {
    try {
    
    ## =========== Check user capabilities =========== ##
    
        if (!current_user_can('manage_options')) { wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'blue-raven')); }
        
     ## =========== Include the admin header class if not already loaded And Render the header =========== ##

        if (!class_exists('Blue_Raven_Admin_Header')) { require_once BLUERAVEN_PLUGIN_DIR . 'templates/class-admin-header.php'; }
        
        $header = new Blue_Raven_Admin_Header();
        $header->render();
        
        echo '<div class="enterra-admin wrap" id="blue-raven-view-container"></div>';
    
        include_once BLUERAVEN_PLUGIN_DIR . "/includes/third-party/class-blue-raven-woo-exporter.php";
        
    } catch (Exception $e) {
        BlueRaven_SendError("ERROR", "blue-raven/blue-raven.php", "blue_raven_render_admin_page ERROR:", $e->getMessage());
        wp_die(esc_html__('An error occurred while rendering the admin page. Please check the error logs.', 'blue-raven'));
    }
}

/*
============================================================
    Settings Page (with Tabs)
============================================================
*/

function blue_raven_render_settings_page() {
    try {
    
    ## =========== Check user capabilities =========== ##
    
        if (!current_user_can('manage_options')) { wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'blue-raven')); }
        
     ## =========== Include the admin settings class if not already loaded And Render the header =========== ##

        if (!class_exists('Blue_Raven_Admin_Settings_Header')) { require_once BLUERAVEN_PLUGIN_DIR . 'templates/class-admin-settings-header.php'; }
        
        $settings = new Blue_Raven_Admin_Settings_Header();
        $settings->render();
        
        echo '<div class="enterra-admin wrap" id="blue-raven-view-container"></div>';
        
    } catch (Exception $e) {
        BlueRaven_SendError("ERROR", "blue-raven/blue-raven.php", "blue_raven_render_settings_page ERROR:", $e->getMessage());
        wp_die(esc_html__('An error occurred while rendering the Settings page. Please check the error logs.', 'blue-raven'));
    }
}

/*
============================================================
    ABOUT PAGE
============================================================
*/

/**
 * Renders the Blue Raven About admin page.
 *
 * Displays plugin information, version details, and other about page content.
 * Verifies user capabilities before rendering and handles errors gracefully.
 *
 * @since 1.0.0
 * @throws Exception If any error occurs during rendering.
 * @return void
 */
function blue_raven_render_about_page() {
    try {
        if (!current_user_can('manage_options')) wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'blue-raven'),esc_html__('Access Denied', 'blue-raven'),array('response' => 403));
        
    ## =========== Include the admin About class if not already loaded And Render the About Page =========== ##

        echo '<div class="enterra-admin wrap" id="blue-raven-view-container">';
        
        if (!class_exists('Blue_Raven_Admin_About')) {require_once BLUERAVEN_PLUGIN_DIR . 'templates/class-admin-about.php';}
        
        $about_page = new Blue_Raven_Admin_About();
        $about_page->render();
        
        echo '</div>';

    } catch (Exception $e) {
        BlueRaven_SendError("ERROR", "blue-raven/blue-raven.php", "blue_raven_render_about_page ERROR :", $e->getMessage());
        
    ## =========== Display user-friendly error message =========== ##

        wp_die(esc_html__('An error occurred while rendering the about page. Please try again or contact support.', 'blue-raven'),esc_html__('Rendering Error', 'blue-raven'),array('response' => 500));
    }
}

/*
============================================================
    INSTALLER
============================================================
*/

/**
 * Handles plugin activation requirements and setup.
 *
 * Checks for required PHP extensions and executes the installation routine.
 * Provides user-friendly error messages if activation fails.
 *
 * @since 1.0.0
 * @return void
 */
register_activation_hook(__FILE__, 'blue_raven_activation');

function blue_raven_activation() {
    
    ## =========== Check for required MySQL extensions & Log the error if BlueRaven_SendError function exists =========== ##
    
    if (!extension_loaded('mysqli') && !extension_loaded('pdo_mysql')) {
        if (function_exists('BlueRaven_SendError')) BlueRaven_SendError("ERROR", "blue-raven/blue-raven.php", "BLUE RAVEN", "My Plugin: Missing required MySQL PHP extensions");
        error_log('My Plugin: Missing required MySQL PHP extensions');
        wp_die(sprintf('<h1>%s</h1><p>%s</p>',esc_html__('Plugin Activation Failed', 'blue-raven'),esc_html__('This plugin requires either the "mysqli" or "pdo_mysql" PHP extension. Please contact your hosting provider to enable one of these extensions.', 'blue-raven')),esc_html__('Plugin Activation Failed', 'blue-raven'),['back_link' => true,'response'  => 500]);
    }
    
    ## =========== Run installer =========== ##
    
    try {
        $installer_path = BLUERAVEN_PLUGIN_DIR . 'includes/installer.php';
        
        if (!file_exists($installer_path)) { throw new Exception(__('Installer file not found.', 'blue-raven'));}

        require_once $installer_path;

        if (!class_exists('BlueRaven_Installer')) { throw new Exception(__('Installer class not found.', 'blue-raven'));}

        $installer = new BlueRaven_Installer();
        $installer->run();

        add_option('blue_raven_activated', time());

    } catch (Exception $e){
        if (function_exists('BlueRaven_SendError')) BlueRaven_SendError("ERROR", "blue-raven/blue-raven.php", "Installation error", $e->getMessage());
        error_log('My Plugin Activation Error: ' . $e->getMessage());
        wp_die(sprintf('<h1>%s</h1><div class="error"><p>%s</p></div>',esc_html__('Plugin Installation Error', 'blue-raven'),esc_html($e->getMessage())),esc_html__('Installation Failed', 'blue-raven'),['back_link' => true,'response'  => 500]);
    }
}

/*
============================================================
    LOAD JS
============================================================
*/

    ## ============ Load JS based on the plugin pages ============ ##
    
add_action('admin_enqueue_scripts', 'blue_raven_enqueue_all_assets');

function blue_raven_enqueue_all_assets($hook) {
    if (strpos($hook, 'blue-raven') === false) return;
    $plugin_url  = BLUERAVEN_PLUGIN_URL;
    $plugin_path = BLUERAVEN_PLUGIN_DIR;
    wp_enqueue_style('blue-raven-admin',$plugin_url . 'assets/css/admin.css',[],filemtime($plugin_path . 'assets/css/admin.css'));
}

/*
============================================================
   SITE CRON
============================================================
*/

require_once BLUERAVEN_PLUGIN_DIR . 'includes/routines/admin-cron-site-map.php';

    ## =========== SITE MAP =========== ##
    
register_activation_hook(__FILE__, function() {
    $cron = new BlueRaven_Site_Map_Cron();
    $cron->activate(); 
});

register_deactivation_hook(__FILE__, function() {
    $cron = new BlueRaven_Site_Map_Cron();
    $cron->deactivate(); 
});

global $wpdb;
$table_name = "{$wpdb->prefix}BlueRavenValues";

if ($wpdb->get_var("SHOW TABLES LIKE '{$table_name}'") === $table_name) {
    $sitemap = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$table_name} WHERE setting LIKE %s", '%site-map%'));
    if (!empty($sitemap) && isset($sitemap[0]->enabled) && $sitemap[0]->enabled) add_filter('wp_sitemaps_enabled', '__return_false');
}
/*
============================================================
   EXTRA ACTIONS
============================================================
*/

function BlueRaven_createTextEditor($text, $name){include_once BLUERAVEN_PLUGIN_DIR . "templates/extras/class-blue-raven-text-editor.php";(new Blue_Raven_Text_Editor())->create($text, $name);}
add_action('admin_enqueue_scripts', function() { wp_enqueue_media(); });

/*
============================================================
    BLUE RAVEN FORM 
============================================================
*/

    ## =========== Blue Raven Form JS =========== ##
    
add_action('wp_enqueue_scripts', 'blue_raven_enqueue_scripts');

function blue_raven_enqueue_scripts() {
    wp_enqueue_script('blue-raven-form',BLUERAVEN_PLUGIN_URL . 'assets/js/blue-raven-form.js',['jquery'],null,true);
    wp_localize_script('blue-raven-form', 'BlueRavenAjax', ['ajax_url' => admin_url('admin-ajax.php'),'nonce'    => wp_create_nonce('blue_raven_nonce'),]);
}

    ## =========== Blue Raven blue_raven_handle_submission =========== ##
    
add_action('wp_ajax_blue_raven_submit_form', 'blue_raven_handle_submission');
add_action('wp_ajax_nopriv_blue_raven_submit_form', 'blue_raven_handle_submission');

function blue_raven_handle_submission() {
    if (!check_ajax_referer('blue_raven_nonce', 'nonce', false)) {
        BlueRaven_SendError("ERROR", "blue-raven/blue-raven.php", "blue_raven_handle_submission", "Invalid nonce");
        wp_send_json_error('Security check failed');
        return;
    }

    $raw_data = isset($_POST) ? $_POST : array();
    $sanitized_data = array();
    foreach ($raw_data as $key => $value) {
        if (is_array($value)) {
            $sanitized_data[$key] = array_map(function($v) {
                if (strpos($v, "\n") !== false || strpos($v, "\r") !== false) {
                    return sanitize_textarea_field($v);
                }
                return sanitize_text_field($v);
            }, $value);
        } else {
            if (strpos($value, "\n") !== false || strpos($value, "\r") !== false) {
                $sanitized_data[$key] = sanitize_textarea_field($value);
            } else {
                $sanitized_data[$key] = sanitize_text_field($value);
            }
        }
    }

    // Include form submission handler
    require_once BLUERAVEN_PLUGIN_DIR . 'includes/form-submission.php';
    $result = BlueRaven_submitForm($sanitized_data);

    if ($result) {
        wp_send_json_success('Form submitted successfully!');
    } else {
        wp_send_json_error('Failed to submit form');
    }
}

/*
============================================================
    BLUE RAVEN UNINSTALL 
============================================================
*/

register_uninstall_hook(__FILE__, 'blue_raven_uninstall');
function blue_raven_uninstall() {include BLUERAVEN_PLUGIN_DIR . 'uninstaller.php';}

/*
============================================================
     BLUE RAVEN PLUGIN LINKS 
============================================================
*/
add_filter('plugin_row_meta', 'blue_raven_plugin_row_meta', 10, 2);
function blue_raven_plugin_row_meta($links, $file) {
    if ($file === plugin_basename(__FILE__)) {
        $new_links = array(
            sprintf(
                '<a href="%s" target="_blank" rel="noopener noreferrer">%s</a>',
                esc_url('https://portal.enterrahost.com/knowledgebase/1/Blue-Raven'),
                esc_html__('Knowledgebase', 'blue-raven')
            ),
            sprintf(
                '<a href="%s" target="_blank" rel="noopener noreferrer">%s</a>',
                esc_url('https://enterrahost.com/community/'),
                esc_html__('Community Support', 'blue-raven')
            ),
            sprintf(
                '<a href="%s" target="_blank" rel="noopener noreferrer">%s</a>',
                esc_url('https://portal.enterrahost.com/login'),
                esc_html__('Premium Support', 'blue-raven')
            ),
                sprintf(
                '<a href="%s" target="_blank" rel="noopener noreferrer">%s</a>',
                esc_url('https://portal.enterrahost.com/store/blue-raven-wordpress-plugin'),
                esc_html__('Go Premium', 'blue-raven')
            )
        );
        return array_merge($links, $new_links);
    }

    return $links;
}

/*
============================================================
    BLUE RAVEN HELP FUNCTIONS 
============================================================
*/

function BlueRaven_buildHTML($nodes) {
    $html = '';

    foreach ($nodes as $node) {
        if (isset($node['tag'])) {
            $html .= '<' . $node['tag'];

            // Add attributes (no double escaping)
            if (isset($node['attributes'])) {
                foreach ($node['attributes'] as $attrName => $attrValue) {
                    $html .= ' ' . $attrName . '="' . $attrValue . '"';
                }
            }

            // Void elements
            $voidElements = ['input', 'img', 'br', 'hr', 'meta', 'link'];
            if (in_array($node['tag'], $voidElements)) {
                $html .= '>';
            } else {
                $html .= '>';

                // Recursive children
                if (isset($node['children'])) {
                    $html .= BlueRaven_buildHTML($node['children']);
                }

                $html .= '</' . $node['tag'] . '>';
            }
        } elseif (isset($node['text'])) {
            $html .= $node['text'];
        }
    }

    return $html;
}

/*
============================================================
    BLUE RAVEN PRO CHECK
============================================================
*/

add_action('admin_notices', 'blue_raven_check_pro_plugin_notice');

function blue_raven_check_pro_plugin_notice() {
    if ( ! current_user_can('manage_options') ) {return;}

    // Check if Blue Raven Pro is active
    include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
    if ( is_plugin_active( 'blue-raven-pro/blue-raven-pro.php' ) ) { 
        ?>
        <div class="notice notice-warning is-dismissible">
            <p>
                <strong>Blue Raven Pro is active.</strong><br>
                You can safely disable or uninstall <em>Blue Raven (non-pro)</em>. 
                Disable the uninstaller in <a href="<?php echo admin_url('admin.php?page=blue-raven-settings'); ?>">settings</a> if you want to keep your data.
            </p>
        </div>
        <?php
    }
}