<?php
/**
 * Plugin bootstrap.
 *
 * @package CatalogFrameImageStudio
 */

namespace CatalogFrame_Image_Studio;

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

/**
 * Coordinates admin UI and REST API registration.
 */
final class Plugin {
	const VERSION_OPTION = 'cfis_plugin_version';

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

	/**
	 * Admin controller.
	 *
	 * @var Admin
	 */
	private $admin;

	/**
	 * REST controller.
	 *
	 * @var Rest_Controller
	 */
	private $rest_controller;

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

		return self::$instance;
	}

	/**
	 * Initializes hooks.
	 *
	 * @return void
	 */
	public function init() {
		$this->maybe_upgrade();

		$this->admin           = new Admin();
		$this->rest_controller = new Rest_Controller( new Product_Mapper() );

		$this->admin->init();
		$this->rest_controller->init();
	}

	/**
	 * Applies small, one-time data migrations when the plugin version changes.
	 *
	 * Version 1.0.1 moved credentials into WordPress core's Connectors API, so
	 * the plugin must not retain the encrypted key used by earlier releases.
	 *
	 * @return void
	 */
	private function maybe_upgrade() {
		if ( CFIS_VERSION === get_option( self::VERSION_OPTION, '' ) ) {
			return;
		}

		delete_option( 'cfis_openai_api_key' );
		update_option( self::VERSION_OPTION, CFIS_VERSION, false );
	}

	/**
	 * Adds the custom capability to administrators and shop managers.
	 *
	 * @return void
	 */
	public static function activate() {
		foreach ( array( 'administrator', 'shop_manager' ) as $role_name ) {
			$role = get_role( $role_name );
			if ( $role ) {
				$role->add_cap( CFIS_MANAGE_CAPABILITY );
				$role->add_cap( 'upload_files' );
			}
		}
	}

	/**
	 * Deactivation intentionally keeps settings and generated media.
	 *
	 * @return void
	 */
	public static function deactivate() {
		// Jobs are browser-run in this version, so there are no scheduled actions to unschedule.
	}
}
