<?php

namespace Merkulove\Unity;

use Merkulove\Readabler\Unity\Activator;
use Merkulove\Readabler\Unity\EnvatoItem;
use Merkulove\Readabler\Unity\Plugin;
use Merkulove\Readabler\Unity\Task;

class Actions {
	private static ?Actions $instance = null;

	private function __construct() {

		// Hook our function into the cron hook
		if ( Task::is_use_cron() ) {
			add_action( Plugin::const('cron_hook'), [ $this, 'check_updates' ] );
		} else {
			add_action( Plugin::const('cron_hook') . '_on_demand', [ $this, 'check_updates' ] );
		}

		// Hook into admin_init to handle form submissions
		add_action( 'admin_init', [ $this, 'submit_pid_activation' ] );

		// Re-create transient if it was erased by other plugins
		add_action( 'admin_init', [ $this, 'recreate_transients' ] );

		// Trigger background check when plugins page is loaded
		add_action('load-plugins.php', [$this, 'load_plugins' ]);

	}

	/**
	 * Load plugins page action to trigger background checks.
	 * @return void
	 */
	public function load_plugins(): void {

		if ( EnvatoItem::id() && Activator::status()) {
			EnvatoItem::get_remote_plugin_info();
		}

	}

	/**
	 * Cron function to perform scheduled tasks.
	 * @return void
	 */
	public function check_updates(): void {

		// Trigger before cron hook
		do_action( Plugin::const('cron_hook') . '_before' );

		// If the last finished cron job was recent, do nothing
		if (Task::is_finished_recently()) {
			return;
		}

		// Check and get Envato item ID if not already set
		if ( ! EnvatoItem::id() ) {
			EnvatoItem::get_remote_plugin_id();
		}

		// Check and get Envato item info if not already set
		if ( EnvatoItem::id() && empty(EnvatoItem::plugin_info())) {
			EnvatoItem::get_remote_plugin_info();
		}

		// Check the activation status if we have Envato item ID
		if ( EnvatoItem::id() ) {
			$purchase_code = Plugin::get_purchase_code();
			Activator::remote_validation($purchase_code);
		}

		// Update the timestamp of the last finished cron job
		Task::set_finished_at();

		// Trigger after cron hook
		do_action( Plugin::const('cron_hook') . '_after' );
	}

	/**
	 * Recreate transients if they were deleted by other plugins.
	 * @return void
	 */
	public function recreate_transients(): void {

		// Get actual purchase code
		$purchase_code = Plugin::get_purchase_code();
		if (empty($purchase_code)) {
			return;
		}

		// If transient exists, do nothing
		if (Activator::is_exists($purchase_code)) {
			return;
		}

		// Run cron function to recreate transient
		$this->check_updates();

	}

	/**
	 * Handle form submission for purchase code activation.
	 * @return void
	 */
	public function submit_pid_activation(): void
	{
		// Only proceed if in the admin area
		if ( !is_admin() ) {
			return;
		}

		// Check if we are on the activation settings page
		$isUpdateSettings = isset($_POST['action']) && $_POST['action'] === 'update';
		if (!$isUpdateSettings) {
			return;
		}

		// Check if the form was submitted
		$isSubmit = isset($_POST['submit']);
		if (!$isSubmit){
			return;
		}

		// Check if we are on the correct settings page
		$options_group = 'ReadablerActivationOptionsGroup';
		$isActivationPage = isset($_POST['option_page']) && $_POST['option_page'] === $options_group;
		if (!$isActivationPage) {
			return;
		}

		// Check if the purchase code field is set and not empty
		$isPurchaseCodeSet = isset($_POST['envato_purchase_code_' . EnvatoItem::id()]) && !empty($_POST['envato_purchase_code_' . EnvatoItem::id()]);
		if (!$isPurchaseCodeSet) {
			return;
		}

		// Sanitize the purchase code
		$purchase_code = sanitize_text_field($_POST['envato_purchase_code_' . EnvatoItem::id()]);

		// Verify nonce
		check_admin_referer( $options_group . '-options' );

		// Remove all existing activation transients
		Activator::flush_activations();

		// Run remote validation
		Activator::remote_validation( $purchase_code, true );

		// Refresh plugin info from Envato
		EnvatoItem::get_remote_plugin_info();

		// Refresh changelog
		EnvatoItem::get_remote_plugin_changelog();

	}

	public static function get_instance(): Actions {
		if ( self::$instance === null ) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	private function __clone() {
	}

	public function __wakeup() {
	}
}
