<?php

declare(strict_types=1);

namespace Signocore\Multilanguage\Application;

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

final class Installer
{
	public static function activate(): void
	{
		if (version_compare(PHP_VERSION, '8.0', '<')) {
			deactivate_plugins(Constants::$pluginBase);
			wp_die(
				__('Signocore Multilanguage requires PHP 8.0 or higher.', 'signocore-multilanguage'),
				__('Plugin Activation Error', 'signocore-multilanguage'),
				['back_link' => true]
			);
		}

		Migrator::load()->migrate();

		self::setDefaultOptions();

		flush_rewrite_rules();

		set_transient(Constants::OPTION_PREFIX . 'activation_redirect', 1, 30);

		do_action('signocore_ml_activated');
	}

	public static function deactivate(): void
	{
		flush_rewrite_rules();

		self::clearTransients();

		do_action('signocore_ml_deactivated');
	}

	private static function setDefaultOptions(): void
	{
		add_option(Constants::OPTION_PREFIX . 'url_strategy', Constants::URL_STRATEGY_DIRECTORY);
		add_option(Constants::OPTION_PREFIX . 'hide_default_language_prefix', '1');
		add_option(Constants::OPTION_PREFIX . 'cookie_duration', '365');
		add_option(Constants::OPTION_PREFIX . 'translatable_post_types', ['post', 'page']);
		add_option(Constants::OPTION_PREFIX . 'translatable_taxonomies', ['category', 'post_tag']);
		add_option(Constants::OPTION_PREFIX . 'switcher_style', 'dropdown');
		add_option(Constants::OPTION_PREFIX . 'switcher_show_flags', '1');
		add_option(Constants::OPTION_PREFIX . 'switcher_show_names', '1');
		add_option(Constants::OPTION_PREFIX . 'installed_at', time());
		add_option(Constants::OPTION_PREFIX . 'version', Constants::$pluginVersion);
	}

	private static function clearTransients(): void
	{
		global $wpdb;

		$wpdb->query(
			$wpdb->prepare(
				"DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s",
				$wpdb->esc_like('_transient_' . Constants::TRANSIENT_PREFIX) . '%',
				$wpdb->esc_like('_transient_timeout_' . Constants::TRANSIENT_PREFIX) . '%'
			)
		);

		$wpdb->query(
			$wpdb->prepare(
				"DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s",
				$wpdb->esc_like('_site_transient_' . Constants::TRANSIENT_PREFIX) . '%',
				$wpdb->esc_like('_site_transient_timeout_' . Constants::TRANSIENT_PREFIX) . '%'
			)
		);
	}
}
