<?php

/**
 * Plugin Name: Changeloger
 * Description: A Gutenberg block to display changelog
 * Author: spider-themes
 * Author URI: https://spider-themes.net/
 * Requires at least: 6.0
 * Tested up to: 7.0
 * Requires PHP: 7.4
 * Version: 1.8.3
 * License: GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text domain: changeloger
 * Domain Path: /languages
 *
 * @package Changeloger
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

if ( function_exists( 'cha_fs' ) ) {
	cha_fs()->set_basename( false, __FILE__ );
} else {
    /**
     * Create a helper function for easy SDK access.
     *
     * @return Freemius
     */
    function cha_fs() {
        global $cha_fs;

		if ( ! isset( $cha_fs ) ) {
			// Include Freemius SDK.
			include_once __DIR__ . '/vendor/autoload.php';

			$cha_fs = fs_dynamic_init(
				array(
					'id'                  => '18274',
					'slug'                => 'changeloger',
					'premium_slug'        => 'changeloger-pro',
					'type'                => 'plugin',
					'public_key'          => 'pk_776f0d8257af65cd6c37c2b92c97b',
					'premium_suffix'      => 'pro',
					'is_premium'          => false,
					'has_addons'          => false,
					'has_paid_plans'      => true,
					'is_org_compliant'    => true,
					'menu'                => [
						'slug'       => 'changeloger',
						'first-path' => 'admin.php?page=changeloger-setup',
						'contact'    => false,
						'support'    => false,
					],
					'parallel_activation' => array(
						'enabled'                  => true,
						'premium_version_basename' => 'changeloger-pro/changeloger-pro.php',
					),
				)
			);
		}

		return $cha_fs;
	}

	cha_fs()->add_filter( 'hide_freemius_powered_by', '__return_true' );
	do_action( 'cha_fs_loaded' );
}

/**
 * Check if the pro plugin and plan is active
 *
 * Following EazyDocs pattern: checks both license AND pro class existence
 *
 * @return bool
 */
if ( ! function_exists( 'cha_is_premium' ) ) {
	function cha_is_premium() {
		return function_exists( 'cha_fs' )
			&& cha_fs()->can_use_premium_code__premium_only()
			&& class_exists( 'Changeloger_Pro' );
	}
}

if ( ! class_exists( 'CHANGELOGER_BLOCKS_CLASS' ) ) {
	final class CHANGELOGER_BLOCKS_CLASS {

		private $enqueue_assets;
		private $register_blocks;

		/**
		 * Class constructor
		 *
		 * Initializes core includes, hooks, and sets up block registration and assets.
		 *
		 * @return void
		 */
		public function __construct() {
			$this->define_constants();

			$this->core_includes();

			$this->register_blocks = new Changeloger_Block_Register();
			add_action( 'init', array( $this->register_blocks, 'changeloger_create_block_init' ) );

			$this->enqueue_assets = new Changeloger_Block_Assets();
			// Add migration filter for block name change from 'block/changeloger' to 'cha/changeloger'.
			add_filter( 'content_save_pre', array( $this, 'migrate_block_name' ) );
			add_filter( 'the_post', array( $this, 'migrate_block_name_in_post' ) );
			if ( ! cha_is_premium() ) {
				add_action( 'init', array( $this, 'disable_premium_cron' ) );
			}
		}

        /**
         * Define the plugin constants
         *
         * @return void
         */
        private function define_constants(): void {
            define( 'CHANGELOGER_VERSION', '1.8.3' );
            define( 'CHANGELOGER_URL', plugin_dir_url( __FILE__ ) );
            define( 'CHANGELOGER_ASSETS', CHANGELOGER_URL . 'assets/' );
            define( 'CHANGELOGER_PLUGIN_FILE', __FILE__ );
        }

        /**
         * Disable premium cron jobs if not on premium version
         *
         * @return void
         */
        public function disable_premium_cron(): void {
            $cron_timestamp = wp_next_scheduled( 'cha_daily_version_check' );
            if ( $cron_timestamp ) {
                wp_unschedule_event( $cron_timestamp, 'cha_daily_version_check' );
                wp_clear_scheduled_hook( 'cha_daily_version_check' );
            }
        }

		/**
		 * Migrate old block name 'block/changeloger' to new name 'cha/changeloger' in post content.
		 * This hook runs when content is about to be saved.
		 *
		 * @param  string $content The post content.
		 * @return string The migrated post content.
		 */
		public function migrate_block_name( $content ): string {
			if ( ! is_string( $content ) || empty( $content ) ) {
				return $content;
			}

			// Replace old block comment with new block name.
			// Pattern: <!-- wp:block/changeloger ... --> becomes <!-- wp:cha/changeloger ... -->
			return str_replace(
				'<!-- wp:block/changeloger',
				'<!-- wp:cha/changeloger',
				$content
			);
		}

		/**
		 * Migrate old block name in post object when loaded from database.
		 * This ensures the block editor sees the new name even for posts with old blocks.
		 *
		 * @param  WP_Post $post The post object.
		 * @return WP_Post The post object with migrated content.
		 */
		public function migrate_block_name_in_post( $post ) {
			if ( ! isset( $post->post_content ) || empty( $post->post_content ) ) {
				return $post;
			}

			// Apply the same migration to the post_content.
			$post->post_content = $this->migrate_block_name( $post->post_content );

			return $post;
		}

        /**
         * Initialize the plugin
         *
         * @return self
         */
        public static function init(): self {
            static $instance = false;
            if ( ! $instance ) {
                $instance = new self();
            }

			return $instance;
		}

        /**
         * Includes core files required for functionality.
         *
         * @return void
         */
        public function core_includes(): void {
            require_once __DIR__ . '/includes/enqueue-assets.php';
            require_once __DIR__ . '/includes/register-blocks.php';

            require_once __DIR__ . '/includes/post-types.php';
            Changeloger_Post_Types::init();

            require_once __DIR__ . '/includes/rest-api.php';
            Changeloger_REST_API::init();

            require_once __DIR__ . '/includes/meta.php';
            Changeloger_Release_Meta::init();

            require_once __DIR__ . '/includes/frontend.php';
            Changeloger_Frontend::init();

            require_once __DIR__ . '/admin/class-changeloger-admin.php';
            Changeloger_Admin::get_instance();

            require_once __DIR__ . '/includes/class-changeloger-demo-importer.php';

			// Load CSF files on after_setup_theme hook (following EazyDocs pattern)
			add_action( 'after_setup_theme', array( $this, 'load_csf_files' ), 20 );

			// Remote Notice Integration.
			// Initialize on plugins_loaded to ensure cron callback is registered during WP-Cron execution.
			include_once __DIR__ . '/includes/class-remote-notice-client.php';

			add_action( 'plugins_loaded', function() {
				if ( class_exists( 'Noticepilot_Remote_Notice_Client' ) ) {
					Noticepilot_Remote_Notice_Client::init( 'Changeloger', [
						'api_url'        => 'https://manage.spider-themes.net/wp-json/noticepilot/v1/content/changeloger',
						'plugin_version' => CHANGELOGER_VERSION,
						'is_pro'         => cha_is_premium(),
					]);
				}
			});
		}

		/**
		 * Load CSF framework and settings files
		 * This must be called on after_setup_theme hook for proper timing
		 *
		 * @return void
		 */
		public function load_csf_files(): void {
			// Load CSF Framework (loads setup.class.php which initializes CSF)
			if ( file_exists( __DIR__ . '/libs/codestar-framework/classes/setup.class.php' ) ) {
				include_once __DIR__ . '/libs/codestar-framework/classes/setup.class.php';
			}

			// Load settings options file (calls CSF::createOptions and CSF::createSection).
			include_once __DIR__ . '/includes/options/settings-options.php';
		}
	}
}

/**
 * Plugin activation hook
 */
register_activation_hook(
	__FILE__,
	function () {
		if ( function_exists( 'cha_schedule_version_check_cron' ) ) {
			cha_schedule_version_check_cron();
		}

		// Create default feedback categories on activation.
		if ( class_exists( 'Changeloger_Post_Types' ) ) {
			// First register the taxonomy so we can add terms to it.
			Changeloger_Post_Types::register_taxonomies();
			Changeloger_Post_Types::create_default_feedback_categories();
		}

		// Set transient to redirect to setup wizard after activation.
		set_transient( 'changeloger_activation_redirect', true, 30 );
	}
);

/**
 * Plugin deactivation hook
 */
register_deactivation_hook(
	__FILE__,
	function () {
		if ( class_exists( 'Noticepilot_Remote_Notice_Client' ) ) {
			Noticepilot_Remote_Notice_Client::disable( 'Changeloger' );
		}
	}
);

/**
 * Kickoff
 */
CHANGELOGER_BLOCKS_CLASS::init();

if ( ! defined( 'CHANGELOGER_PATH' ) ) {
	define( 'CHANGELOGER_PATH', plugin_dir_path( __FILE__ ) );
}
