<?php
/**
 * Installation Handler
 *
 * @package FKWCSQ\Install
 */

namespace FKWCSQ\Includes;

use FKWCSQ\Includes\Modules\Connection\MiddleWare;
use FKWCSQ\Includes\Traits\Instance;

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

/**
 * Handles plugin installation and updates
 */
class Install {
	use Instance;

	/**
	 * Private constructor to prevent direct instantiation
	 */
	private function __construct() {
		$this->init_hooks();
	}

	/**
	 * Initialize hooks
	 */
	private function init_hooks() {
		register_activation_hook( \FKWCSQ\Square::$plugin_file, array( $this, 'install' ) );
		register_deactivation_hook( \FKWCSQ\Square::$plugin_file, array( $this, 'deactivate' ) );
		add_action( 'plugins_loaded', array( $this, 'check_version' ), 10 );
		add_action( 'fkwcsq_updated', array( $this, 'maybe_register_webhook_key' ) );
	}

	/**
	 * Check plugin version and run updates if needed
	 */
	public function check_version() {
		$stored_version = get_option( 'fkwcsq_version' );
		if ( ! defined( 'IFRAME_REQUEST' ) && $stored_version !== FKWCSQ_VERSION ) {
			$this->install();
			if ( ! empty( $stored_version ) ) {
				do_action( 'fkwcsq_updated' );
			}
		}
	}

	/**
	 * Install plugin
	 */
	public function install() {
		if ( ! is_blog_installed() ) {
			return;
		}

		// Check if we are not already running this routine
		if ( 'yes' === get_transient( 'fkwcsq_installing' ) ) {
			return;
		}

		// Set transient to prevent multiple installations
		set_transient( 'fkwcsq_installing', 'yes', MINUTE_IN_SECONDS * 10 );

		// Create options
		$this->create_options();

		// Update version
		$this->update_version();

		delete_transient( 'fkwcsq_installing' );

		do_action( 'fkwcsq_installed' );
	}

	/**
	 * Deactivate plugin
	 */
	public function deactivate() {
		// Clear any scheduled hooks
		wp_clear_scheduled_hook( 'fkwcsq_daily_cron' );
	}


	/**
	 * On plugin update, generate and register a webhook auth key for any connected site
	 * that doesn't have one yet (existing installs upgrading from pre-key versions).
	 */
	public function maybe_register_webhook_key() {
		if ( get_option( 'fkwcsq_webhook_auth_key', '' ) ) {
			return;
		}

		$middleware = MiddleWare::get_instance();
		if ( ! $middleware->is_connected() ) {
			return;
		}

		$middleware->generate_and_register_webhook_key();
	}

	/**
	 * Create default options
	 */
	private function create_options() {
		// Add default options
		add_option( 'fkwcsq_version', FKWCSQ_VERSION );
	}

	/**
	 * Update plugin version
	 */
	private function update_version() {
		update_option( 'fkwcsq_version', FKWCSQ_VERSION );
	}
}
