<?php
/**
 * Main plugin bootstrap.
 *
 * @package TonItaliaRegistration
 */

defined( 'ABSPATH' ) || exit;

/**
 * Class TON_Reg_Plugin
 */
class TON_Reg_Plugin {

	/**
	 * @var self|null
	 */
	private static $instance = null;

	/**
	 * @return self
	 */
	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * Constructor.
	 */
	private function __construct() {
		load_plugin_textdomain( 'ton-italia-registration', false, dirname( plugin_basename( TON_REG_PLUGIN_FILE ) ) . '/languages' );

		add_action( 'init', array( $this, 'init' ) );
		add_action( 'admin_init', array( $this, 'block_subscriber_admin' ) );
		add_filter( 'show_admin_bar', array( $this, 'hide_admin_bar_for_subscribers' ) );

		TON_Reg_Registration_Form::register();
		TON_Reg_Registration_Handler::register();

		if ( is_admin() ) {
			TON_Reg_Admin::register();
		}
	}

	/**
	 * Init hooks.
	 */
	public function init() {
		$this->maybe_upgrade();
	}

	/**
	 * Run DB / folder upgrades when plugin files are updated.
	 */
	private function maybe_upgrade() {
		$db_version = (string) get_option( 'ton_reg_db_version', '0' );

		if ( version_compare( $db_version, '1.1', '<' ) ) {
			TON_Reg_Database::create_table();
			TON_Reg_Documents::install_folders();
			$db_version = '1.1';
		}

		if ( version_compare( $db_version, '1.2', '<' ) ) {
			TON_Reg_Database::create_table();
			$db_version = '1.2';
		}

		update_option( 'ton_reg_db_version', $db_version );
	}

	/**
	 * Prevent subscribers from accessing wp-admin (except AJAX).
	 */
	public function block_subscriber_admin() {
		if ( ! is_user_logged_in() || wp_doing_ajax() ) {
			return;
		}

		$user = wp_get_current_user();
		if ( in_array( 'subscriber', (array) $user->roles, true ) && ! current_user_can( 'manage_options' ) ) {
			wp_safe_redirect( home_url() );
			exit;
		}
	}

	/**
	 * @param bool $show Whether to show admin bar.
	 * @return bool
	 */
	public function hide_admin_bar_for_subscribers( $show ) {
		if ( ! is_user_logged_in() ) {
			return $show;
		}
		$user = wp_get_current_user();
		if ( in_array( 'subscriber', (array) $user->roles, true ) && ! current_user_can( 'manage_options' ) ) {
			return false;
		}
		return $show;
	}
}
