<?php

class SupsysticTablesPro_Core_Module extends SupsysticTables_Core_Module
{
    public function onInit()
    {
        parent::onInit();
        $this->update();
    }

    public function update() {
        if (!is_admin()) {
            return;
        }

        $environment = $this->getEnvironment();
        $config = $environment->getConfig();
        $oldVersion = get_option('st_plugin_version_pro');

        if (version_compare($config->get('plugin_version_pro'), $oldVersion, '<=')) {
            return;
        }

        $core = $this->getModelsFactory()->get('core');
        $updatesDirectory = dirname(__FILE__) . '/updates';
        $updates = array_diff(scandir($updatesDirectory), array('..', '.'));

        foreach($updates as $filename) {
            $version = str_replace('.sql', '', $filename);

			// The Queries for altering the existing tables (ALTER...) must be in separate file for correct execution.
			// See data-tables-generator-by-supsystic/src/SupsysticTables/Core/Model/Core::update()
			// Maybe we need to fix it later...
            if (version_compare($config->get('plugin_version_pro'), $version, '>=')
				&& version_compare($oldVersion, $version, '<')
            ) {
                try {
                    $core->updateFromFile($updatesDirectory . '/' . $filename);
                } catch (Exception $e) {
                    if (!$environment->isPluginPage()) {
                        return;
                    }
                    wp_die(sprintf('Failed to update plugin database. Reason: %s', $e->getMessage()));
                }
            }
        }

        update_option('st_plugin_version_pro', $config->get('plugin_version_pro'));
    }

	public function afterUiLoaded(SupsysticTables_Ui_Module $ui)
	{
		parent::afterUiLoaded($ui);

		$environment = $this->getEnvironment();
		$location = untrailingslashit(plugin_dir_url(__FILE__));
		$pluginVersion = $environment->getConfig()->get('plugin_version');
		$hookName = 'admin_enqueue_scripts';
		$dynamicHookName = is_admin() ? $hookName : 'wp_enqueue_scripts';

		// Scripts
		$ui->add(
			$ui->createScript('core.pro.js')	// Core PRO script with common functions in supsystic.Tables namespace
				->setHookName($dynamicHookName)
				->setExternalSource($location . '/assets/js/core.pro.js')
				->addDependency('tables-core')
				->setVersion($pluginVersion)
		);
	}
}
