<?php
#[AllowDynamicProperties]
class SupsysticTablesPro_Loader
{
    /**
     * @var string
     */
    protected $prefix;

    /**
     * @var string
     */
    protected $path;


    public function load()
    {
        spl_autoload_register(array($this, 'loadPHPOffice'), true, false);
        add_action('st_plugin_loaded', array($this, 'register'));
        if (is_admin()) {
          add_action('admin_notices', array($this, 'notActiveNotice'));
          add_action('st_before_menu_page_create', array($this, 'setCapability'));
        }
    }

    public function register(RscDtgs_Environment $plugin)
    {
		remove_action('admin_notices', array($this, 'notActiveNotice'));
        $this->config = $plugin->getConfig();
        $config = $this->config;

        $config->add('pro_modules_prefix', $this->prefix);
        $config->add('pro_modules_path', $this->path);
        $config->add('plugin_product_code', 'table_generator_pro');
        $config->add('plugin_version_pro', $this->version);

        if (property_exists($this, 'capability')) {
            $menu = $config->get('plugin_menu');
            $menu['capability'] = $this->capability;
            $config->set('plugin_menu', $menu);
        }

        define('S_YOUR_SECRET_HASH_' . $config->get('plugin_product_code'), 'awd3q@Fsfe%$3fwfsvfxaxAwedawd@#ERQt');

        $loader = $plugin->getLoader();
        $loader->add($this->prefix, $this->path);

        $resolver = $plugin->getResolver();
        $modules = $resolver->getModulesList();
        if (is_dir($dir = $this->path . '/' . $this->prefix . '/License')) {
            $className = $this->prefix . '_' . basename($dir) . '_Module';

            if (!class_exists($className)) {
                if ($plugin->isPluginPage()) {
                    wp_die ('Cannot locate license module.');
                }

                return;
            }

            $license = new $className($plugin, $dir, $this->prefix);
            $modules->add('license', $license);
        }

        if ($license->isLegal()) {
            // Get list of the PRO modules.
            $nodes = glob($this->path . '/' . $this->prefix . '/*');

            if ($nodes === false || count($nodes) === 0) {
                return;
            }

            // If we need to replace free module - replace it.
            foreach ($nodes as $node) {
                $node = str_replace('\\', '/', $node);

                if (is_dir($node) && file_exists($module = $node . '/Module.php')) {
                    $className = $this->prefix . '_' . basename($node) . '_Module';
                    $name = strtolower(basename(dirname($module)));
                    $free = $modules[$name];
                    $location = $free instanceof RscDtgs_Mvc_Module ? $free->getLocation() : $node;
                    $modules[$name] = new $className($plugin, $location, $this->prefix);
                }
            }

            // Replace old list of the modules with new.
            $resolver->setModulesList($modules);
            $config->add('is_pro', true);
        }

        $updater = new SupsysticTablesUpdater();
        $updater->setDirectory(basename(dirname(__FILE__)));
        $updater->setEnvironment($plugin);
        $updater->setFile('index.php');
        $updater->setProductCode($config->get('plugin_product_code'));

        $updater->subscribe();
    }

	public function notActiveNotice() {
		$installUrl = add_query_arg(
			array(
				's' => 'Data+Tables+Generator+by+Supsystic',
				'tab' => 'search',
				'type' => 'term',
			),
			admin_url( 'plugin-install.php' )
		);
		$installWpUrl = 'https://wordpress.org/plugins/data-tables-generator-by-supsystic/';
		include dirname(__FILE__) . '/resources/notice.php';
	}

    /**
     * Returns Prefix.
     * @return string
     */
    public function getPrefix()
    {
        return $this->prefix;
    }

    /**
     * Sets Prefix.
     * @param string $prefix
     */
    public function setPrefix($prefix)
    {
        $this->prefix = $prefix;
    }

    /**
     * Returns Path.
     * @return string
     */
    public function getPath()
    {
        return $this->path;
    }

    /**
     * Sets Path.
     * @param string $path
     */
    public function setPath($path)
    {
        $this->path = $path;
    }

    public function setProVersion($version)
    {
        $this->version = $version;
    }

	public function setCapability($menu) {
		$alowedRoles = array();
		$settings = get_option('supsystic_tbl_settings');
		if ($settings && isset($settings['access_roles'])) {
			$alowedRoles = $settings['access_roles'];
		}
		$current_user = wp_get_current_user();
		if ($current_user) {
			foreach ($current_user->roles as $role) {
				if (in_array($role, $alowedRoles)) {
					$menu->setCapability('read');

				}
			}
		}
	}
  public function loadPHPOffice($class) {
      $isPHPOfficeClass = false;

      switch (true) {
        case stristr($class,'PhpSpreadsheet'):
            $isPHPOfficeClass = true;
            break;
        case stristr($class,'SimpleCache'):
            $isPHPOfficeClass = true;
            break;
        case stristr($class,'ZipStream'):
            $isPHPOfficeClass = true;
            break;
        case stristr($class,'Enum'):
            $isPHPOfficeClass = true;
            break;
      }

      if (!$isPHPOfficeClass) {
        return false;
      }

      if ($pos = strpos($class, '\\') !== false) {
          $path = str_replace('\\', DIRECTORY_SEPARATOR, substr($class, 0, $pos)) . DIRECTORY_SEPARATOR;
          $name = substr($class, $pos + 1);
      } else {
          $path = null;
          $name = $class;
      }

      switch (true) {
        case stristr($class,'PhpSpreadsheet'):
            $path = str_replace('pOffice','PHPOffice', $name) . '.php';
            break;
        case stristr($class,'SimpleCache'):
            $name = explode('\\', $name);
            $path = 'PHPOfficeDependencies\psr\simple-cache\\' . $name[count($name) - 1] . '.php';
            break;
        case stristr($class,'ZipStream'):
            $name = explode('\\', $name);
            if ($name[count($name) - 2] == 'Option' || $name[count($name) - 2] == 'Exception') {
              $path = 'PHPOfficeDependencies\maennchen\zipstream-php\\' . $name[count($name) - 2] . '\\' . $name[count($name) - 1] . '.php';
            } else {
              $path = 'PHPOfficeDependencies\maennchen\zipstream-php\\' . $name[count($name) - 1] . '.php';
            }
            break;
        case stristr($class,'Enum'):
            $name = explode('\\', $name);
            $path = 'PHPOfficeDependencies\myclabs\php-enum\\' . $name[count($name) - 1] . '.php';
            break;
      }

      if ($pos = strpos($path, '\\') !== false) {
          $path = str_replace('\\', DIRECTORY_SEPARATOR, $path);
      }

      $dir = plugin_dir_path( __FILE__ ).'vendor';
      $file = $dir . DIRECTORY_SEPARATOR . $path;

      if (file_exists($file)) {
          if (!class_exists($class, false)) {
            require_once $file;
          }
      }

  }


}
