<?php
namespace Bdp\Modules\Security;


use ZipArchive;



class Security
{
    public const required_security_plugins = [
        'wps_hide_login' => ['downloadUrl' => 'https://downloads.wordpress.org/plugin/wps-hide-login.1.9.10.zip'],
        'limit-login-attempts-reloaded' => ['downloadUrl' => 'https://downloads.wordpress.org/plugin/limit-login-attempts-reloaded.2.25.27.zip']];


    public const delete_plugins = [
        'akismet/akismet.php',
        'hello.php'
    ];

    public static function setup()
    {
        self::deletePlugins();
        foreach (self::required_security_plugins as $pluginSlug => $pluginData) {
            if (!is_dir(WP_PLUGIN_DIR . '/' . $pluginSlug)) {
                self::installSecurityPlugin($pluginSlug, $pluginData['downloadUrl']);
            }
        }

        $loginUrl = get_option('whl_page', 'bdp_login');
        update_option('whl_page', $loginUrl);

    }

    public static function deletePlugins() {
        deactivate_plugins(self::delete_plugins);
        delete_plugins(self::delete_plugins);
    }


    public static function installSecurityPlugin(string $pluginSlug, string $downloadUrl) : bool
    {
        $ch = curl_init();
        $source = $downloadUrl;
        curl_setopt($ch, CURLOPT_URL, $source);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec ($ch);
        curl_close ($ch);

        $destination = WP_PLUGIN_DIR . '/' . $pluginSlug . '.zip';
        $file = fopen($destination, "w+");
        fputs($file, $data);
        fclose($file);

        $zip = new ZipArchive();
        $zip->open($destination);
        $zip->extractTo(WP_PLUGIN_DIR);
        $zip->close();
        unlink($destination);

        $pluginInfos = get_plugins( '/'.$pluginSlug );
        $installfile = $pluginSlug . '/';
        if( ! empty( $pluginInfos ) ) {
            foreach ($pluginInfos as $file => $info) :
                $installfile .= $file;
            endforeach;
        }



        $result = activate_plugin($installfile);

        return $result === null;
    }
}