<?php // namespace wpmemory_BillMore {
if (!defined("ABSPATH")) {
    exit();
} // Exit if accessed directly
/*
$plugin_path = trailingslashit( dirname( plugin_basename( __FILE__ ) ) ); 
$parts = explode('/', rtrim($plugin_path, '/')); // Divide a string em partes usando '/' como delimitador
$plugin_slug = reset($parts); // Obtém o primeiro elemento da lista
$plugin_url = plugins_url() .'/'. $plugin_slug;
*/
// >>>>>>>>>>>>>>>>  conferir e
// ver se tudo scaped e sanitized...
if (function_exists("is_multisite") and is_multisite()) {
    return;
}

// debug4();
/*
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>.
// a chamada...
// more...
function scd_bill_more()
{
    global $scd_is_admin;
    if ($scd_is_admin && function_exists('current_user_can') && current_user_can("manage_options")) {
        $declared_classes = get_declared_classes();
        foreach ($declared_classes as $class_name) {
            if (strpos($class_name, "bill_required_PluginInstaller") !== false) {
                return;
            }
        }
        $file_path = dirname(__FILE__) . "/includes/required-tools/class_bill_more3.php";
        if (file_exists($file_path)) {
            require_once $file_path;
        } else {
            error_log('Site Checkup Dependency: Unable to load class_bill_more3.php at ' . $file_path);
        }
    }
}
add_action("init", "scd_bill_more", 5);
// >>>>>>>>>>>>>>>>>>>>>>>
*/

// -----------------------------

function scd_check_dependency()
{
    if (!function_exists('is_plugin_active')) {
        $plugin_file = ABSPATH . 'wp-admin/includes/plugin.php';
        if (file_exists($plugin_file)) {
            // debug4($plugin_file);
            include_once $plugin_file;
        } else {
            add_action('admin_notices', 'scd_show_fallback_notice');
            error_log('Site Checkup Dependency: Unable to load plugin.php');
            return;
        }
    }

    if (!is_plugin_active('site-checkup/site-checkup.php')) {
        add_action('admin_notices', 'scd_show_admin_notice');
    }
}

function scd_show_admin_notice()
{



    $translations = [
        'en' => [ // Adicionando inglês como padrão
            'Plugin Site Checkup is required.' => 'Plugin Site Checkup is required.',
            'Please, click to install now.' => 'Please, click to install now.'
        ],
        'fr' => [
            'Plugin Site Checkup is required.' => 'Le plugin Site Checkup est requis.',
            'Please, click to install now.' => 'Veuillez cliquer pour installer maintenant.'
        ],
        'pt' => [
            'Plugin Site Checkup is required.' => 'O plugin Site Checkup é necessário.',
            'Please, click to install now.' => 'Por favor, clique para instalar agora.'
        ],
        'de' => [
            'Plugin Site Checkup is required.' => 'Das Plugin Site Checkup ist erforderlich.',
            'Please, click to install now.' => 'Bitte klicken Sie, um jetzt zu installieren.'
        ],
        'es' => [
            'Plugin Site Checkup is required.' => 'El complemento Site Checkup es necesario.',
            'Please, click to install now.' => 'Por favor, haga clic para instalar ahora.'
        ],
        'nl' => [
            'Plugin Site Checkup is required.' => 'De plugin Site Checkup is vereist.',
            'Please, click to install now.' => 'Klik alstublieft om nu te installeren.'
        ],
        'it' => [
            'Plugin Site Checkup is required.' => 'Il plugin Site Checkup è richiesto.',
            'Please, click to install now.' => 'Per favore, clicca per installare ora.'
        ],
    ];

    // Detect the language (you can replace this with a real detection method)
    $lang = substr(get_locale(), 0, 2); // 'fr', 'pt', 'de', 'es', 'nl', 'it'

    // Default to English if the language is not supported
    if (!isset($translations[$lang])) {
        $lang = 'en';
    }

    // Display the translated messages




?>
    <div class="notice notice-error">
        <br>
        <p>
            <?php
            echo esc_attr($translations[$lang]['Plugin Site Checkup is required.']);
            echo ' ' . scd_generate_install_link('site-checkup', $translations[$lang]['Please, click to install now.']);
            ?>
        </p>
        <br>
    </div>
<?php
}

function scd_show_fallback_notice()
{
?>
    <div class="notice notice-error">
        <p><?php esc_html_e('Unable to verify Site Checkup status due to server configuration issues.', 'site-checkup-dependency'); ?></p>
    </div>
<?php
}

add_action('admin_init', 'scd_check_dependency');


/*
function scd_load_textdomain()
{
    load_plugin_textdomain(
        'site-checkup-dependency',
        false,
        dirname(plugin_basename(__FILE__)) . '/languages/'
    );
}
add_action('plugins_loaded', 'scd_load_textdomain');
*/
/*
function scd_bill_more()
{
    if (function_exists('current_user_can') && current_user_can("manage_options")) {
        $declared_classes = get_declared_classes();
        foreach ($declared_classes as $class_name) {
            if (strpos($class_name, "bill_required_PluginInstaller") !== false) {
                return;
            }
        }
        $file_path = dirname(__FILE__) . "/includes/required-tools/class_bill_more3.php";
        if (file_exists($file_path)) {
            require_once $file_path;
        } else {
            error_log('Site Checkup Dependency: Unable to load class_bill_more3.php at ' . $file_path);
        }
    }
}
add_action("init", "scd_bill_more", 5);
*/

/*
function scd_check_wordpress_logged_in_cookie()
{
    if (!isset($_COOKIE) || !is_array($_COOKIE)) {
        return false;
    }
    foreach ($_COOKIE as $key => $value) {
        if (strpos($key, 'wordpress_logged_in_') === 0) {
            return true;
        }
    }
    return false;
}
*/

function scd_generate_install_link($slug, $link_text = 'Install Plugin')
{
    $allowed_slugs = [
        "database-backup",
        "bigdump-restore",
        "easy-update-urls",
        "hide-site-title",
        "s3cloud",
        "toolsfors3",
        "antihacker",
        "stopbadbots",
        "wptools",
        "recaptcha-for-all",
        "wp-memory",
        "disable-wp-sitemap",
        "restore_classic_widgets",
        "antibots",
        "site-checkup"
    ];

    if (!in_array($slug, $allowed_slugs)) {
        return '<span>' . esc_html__('Slug inválido', 'scd') . '</span>';
    }

    $nonce = wp_create_nonce('bill_install_plugin_class');
    $link = sprintf(
        '<a href="#" class="bill-install-now-24" id="%s" data-slug="%s">%s</a>' .
            '<span class="spinner" style="display:none; margin-left: 5px;"></span>' .
            '<input type="hidden" id="nonce_install" value="%s">' .
            '<input type="hidden" id="main_slug" value="%s">',
        esc_attr($slug),
        esc_attr($slug),
        esc_html($link_text),
        esc_attr($nonce),
        esc_attr($slug)
    );

    return $link;
}

// ----------------------------------



class bill_required_PluginInstaller
{
    public function __construct()
    {
        add_action("admin_enqueue_scripts", [$this, "enqueue_scripts"]);
        // Adiciona o gancho para ação wp_ajax
        add_action("wp_ajax_bill_install_plugin3", array($this, "bill_install_plugin3"));
    }

    public function enqueue_scripts()
    {
        $plugin_root_url = trailingslashit(plugins_url(basename(dirname(__DIR__, 2))));

        wp_register_script(
            'scd-more3',
            trailingslashit(plugin_dir_url(__FILE__)) . "more3.js",
            ["jquery"],
            filemtime(dirname(__FILE__) . "/more3.js"),
            true
        );
        wp_enqueue_script('scd-more3');

        /*

        wp_register_script(
            "bill-js-toast24",
            $plugin_root_url . "assets/js/jquery.toast.js",
            ["jquery"],
            filemtime(dirname(__DIR__, 2) . "/assets/js/jquery.toast.js"),
            true
        );
        wp_enqueue_script("bill-js-toast24");
        */

        wp_enqueue_script('jquery');
    }



    public function bill_install_plugin3()
    {
        if (isset($_POST["nonce"])) {
            $nonce = sanitize_text_field($_POST["nonce"]);
            if (!wp_verify_nonce($nonce, "bill_install_plugin_class") && !wp_verify_nonce($nonce, "bill_install")) {
                wp_die("invalid nonce");
            }
        } else {
            wp_die("invalid nonce!");
        }
        if (!current_user_can('administrator')) {
            wp_die("invalid user!");
        }
        if (isset($_POST["slug"])) {
            $slug = sanitize_text_field($_POST["slug"]);
        } else {
            echo "Fail error (-5)";
            wp_die();
        }
        $allowed_slugs = [
            "database-backup",
            "bigdump-restore",
            "easy-update-urls",
            "hide-site-title",
            "s3cloud",
            "toolsfors3",
            "antihacker",
            "stopbadbots",
            "wptools",
            "recaptcha-for-all",
            "wp-memory",
            "disable-wp-sitemap",
            "restore_classic_widgets",
            "antibots",
            "site-checkup"
        ];
        if (!in_array($slug, $allowed_slugs)) {
            wp_die("wrong slug");
        }
        $api = plugins_api("plugin_information", [
            "slug" => $slug,
            "fields" => ["sections" => false],
        ]);
        if (is_wp_error($api)) {
            echo "Fail error (-1)";
            wp_die();
        }
        if (isset($api->download_link)) {
            $source = $api->download_link;
        } else {
            echo "Fail error (-2)";
            wp_die();
        }
        $skin = new \bill_required_install_QuietSkin(["api" => $api]);
        $upgrader = new \Plugin_Upgrader($skin);
        try {
            $result = $upgrader->install($source);
            if (is_wp_error($result)) {
                echo "Fail error (-3): " . $result->get_error_message();
                wp_die();
            }
            if ($result === false) {
                echo "Fail error (-6)";
                wp_die();
            }
            // Verifica se o plugin foi realmente instalado e obtém o caminho do arquivo principal
            $all_plugins = get_plugins();
            $plugin_installed = false;
            $plugin_file = '';
            foreach ($all_plugins as $key => $value) {
                if (strpos($key, $slug . '/') === 0) {
                    $plugin_installed = true;
                    $plugin_file = $key; // ex.: "site-checkup/site-checkup.php"
                    break;
                }
            }
            if (!$plugin_installed) {
                echo "Fail error (-7)";
                wp_die();
            }

            // Ativa o plugin
            $activation_result = activate_plugin($plugin_file);
            if (is_wp_error($activation_result)) {
                echo "Fail error (-8): " . $activation_result->get_error_message();
                wp_die();
            }
        } catch (\Exception $e) {
            echo "Fail error (-4): " . $e->getMessage();
            wp_die();
        }
        wp_die("OK");
    }
}
$plugin_installer = new  bill_required_PluginInstaller();
require_once ABSPATH . "wp-admin/includes/plugin-install.php";
require_once ABSPATH . "wp-admin/includes/class-wp-upgrader.php";
require_once ABSPATH . "wp-admin/includes/plugin.php"; // Necessário para activate_plugin()

class  bill_required_install_QuietSkin extends \WP_Upgrader_Skin
{
    public function __construct()
    {
        parent::__construct();
    }
    public function feedback($string, ...$args)
    {
        // no output
    }
    public function header()
    {
        // no output
    }
    public function footer()
    {
        // no output
    }
}
$quiet_skin = new  bill_required_install_QuietSkin();
