<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
class SmallPict_Core {

	protected $api_client;
	protected $transport;
	protected $settings;
	protected $optimizer;

	public function run() {
		$this->load_dependencies();
		$this->define_admin_hooks();
		$this->define_public_hooks();
	}

	private function load_dependencies() {
		// Core Dependencies
		require_once SMALLPICT_PATH . 'includes/class-settings.php';
		require_once SMALLPICT_PATH . 'includes/class-smallpict-api.php';
		require_once SMALLPICT_PATH . 'includes/class-presigned-transport.php';
		require_once SMALLPICT_PATH . 'includes/class-image-processor.php';
		require_once SMALLPICT_PATH . 'includes/class-quota-manager.php';

		// Optional/Legacy Integrations
		if ( file_exists( SMALLPICT_PATH . 'includes/free/class-basic-optimizer.php' ) ) {
			require_once SMALLPICT_PATH . 'includes/free/class-basic-optimizer.php';
		}

		if ( file_exists( SMALLPICT_PATH . 'includes/pro/class-pro-feature.php' ) ) {
			require_once SMALLPICT_PATH . 'includes/pro/class-pro-feature.php';
		}

		// Initialize Components
		// Token retrieval from Freemius or settings
		$token = null;
		if ( function_exists( 'smallpict_fs' ) && smallpict_fs()->get_user() ) {
			// Logic to get token/session would go here
			// For now, we instantiate client blank
		}

		$this->api_client = new SmallPict_API_Client( $token );
		$this->transport  = new SmallPict_Presigned_Transport();
		$this->settings   = new SmallPict_Settings();

		// Inject API and Transport into Processor
		$this->optimizer = new SmallPict_Image_Processor( $this->api_client, $this->transport );
	}

	private function define_admin_hooks() {
		add_action( 'admin_menu', array( $this->settings, 'add_admin_menu' ) );
		add_action( 'admin_init', array( $this->settings, 'register_settings' ) );

		add_action(
			'admin_enqueue_scripts',
			function ( $hook ) {
				if ( strpos( $hook, 'smallpict' ) === false ) {
					return;
				}

				wp_enqueue_script( 'smallpict-admin-js', SMALLPICT_URL . 'assets/admin.js', array( 'jquery' ), SMALLPICT_VERSION, true );
				wp_localize_script(
					'smallpict-admin-js',
					'smallpict_ajax',
					array(
						'url'   => admin_url( 'admin-ajax.php' ),
						'nonce' => wp_create_nonce( 'smallpict_nonce' ),
					)
				);
			}
		);

		// REMOVED LEGACY AJAX ACTIONS
	}

	private function define_public_hooks() {
		add_filter( 'wp_handle_upload', array( $this->optimizer, 'handle_upload' ), 10, 2 );
	}
}
