<?php
/**
 * Main plugin runtime.
 *
 * @package KGV\VereinManager
 */

namespace KGV\VereinManager;

use KGV\VereinManager\Admin\Admin;

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

class Plugin {

	const DAILY_OPTIMIZE_HOOK = 'kgvvm_daily_optimize_tables';

	/**
	 * Singleton instance.
	 *
	 * @var Plugin|null
	 */
	private static $instance = null;

	/**
	 * Admin controller.
	 *
	 * @var Admin|null
	 */
	private $admin = null;

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

		return self::$instance;
	}

	/**
	 * Bootstrap runtime hooks.
	 *
	 * @return void
	 */
	public function run() {
		load_plugin_textdomain( KGVVM_TEXT_DOMAIN, false, dirname( plugin_basename( KGVVM_PLUGIN_FILE ) ) . '/languages' );
		add_action( self::DAILY_OPTIMIZE_HOOK, array( $this, 'run_daily_table_optimization' ) );
		self::ensure_daily_optimization_schedule();

		$default_settings = array(
			'allow_multiple_member_parcels' => 1,
			'water_usage_alert_threshold'   => 25,
			'power_usage_alert_threshold'   => 1000,
			'power_unit'                    => 'kwh',
			'pdf_club_name'                 => get_bloginfo( 'name' ),
			'pdf_logo_url'                  => '',
			'pdf_contact_block'             => '',
			'pdf_intro_text'                => __( 'Diese Jahresabrechnung wurde automatisch mit der KGV Vereinsverwaltung erstellt.', KGVVM_TEXT_DOMAIN ),
			'pdf_footer_text'               => __( 'Bitte prüfen Sie die Angaben und melden Sie Rückfragen an den Vorstand.', KGVVM_TEXT_DOMAIN ),
		);
		$settings         = get_option( 'kgvvm_settings', array() );
		update_option( 'kgvvm_settings', wp_parse_args( $settings, $default_settings ), false );

		if ( KGVVM_VERSION !== get_option( 'kgvvm_plugin_version', '' ) ) {
			Schema::create_tables();
			Roles::add_roles_and_caps();
			update_option( 'kgvvm_plugin_version', KGVVM_VERSION, false );
		}

		if ( is_admin() ) {
			$this->admin = new Admin();
			$this->admin->register_hooks();
		}
	}

	/**
	 * Ensure the daily optimize event is scheduled.
	 *
	 * @return void
	 */
	public static function ensure_daily_optimization_schedule() {
		if ( ! wp_next_scheduled( self::DAILY_OPTIMIZE_HOOK ) ) {
			wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', self::DAILY_OPTIMIZE_HOOK );
		}
	}

	/**
	 * Remove the daily optimize event.
	 *
	 * @return void
	 */
	public static function clear_daily_optimization_schedule() {
		wp_clear_scheduled_hook( self::DAILY_OPTIMIZE_HOOK );
	}

	/**
	 * Optimize plugin tables from the scheduled task.
	 *
	 * @return void
	 */
	public function run_daily_table_optimization() {
		Schema::optimize_tables();
		update_option( 'kgvvm_last_table_optimize', current_time( 'mysql' ), false );
	}
}
