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

namespace FKWCSQ\Includes;

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 );
	}

	/**
	 * Check plugin version and run updates if needed
	 */
	public function check_version() {
		if ( ! defined( 'IFRAME_REQUEST' ) && get_option( 'fkwcsq_version' ) !== FKWCSQ_VERSION ) {
			$this->install();
			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' );
	}


	/**
	 * 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 );
	}
}
