<?php
/**
 * Plugin Name: Moon Static HTML Pages
 * Description: Generates static HTML for pages and serves them on request.
 * Version: 1.0.0
 * Author: Moon Technolabs
 * Author URI: https://profiles.wordpress.org/moontechnolabs/
 * Requires at least: 5.0
 * Tested up to: 7.0
 * License: GPL2
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: moon-static-html-pages
 */

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

/**
 * Constants.
 */
define( 'WPSH_VERSION', '1.0.0' );
define( 'WPSH_PATH', plugin_dir_path( __FILE__ ) );
define( 'WPSH_URL', plugin_dir_url( __FILE__ ) );

/**
 * Autoloader (Simple).
 */
require_once WPSH_PATH . 'includes/class-wpsh-helper.php';
require_once WPSH_PATH . 'includes/class-wpsh-htaccess.php';
require_once WPSH_PATH . 'includes/class-wpsh-logger.php';
require_once WPSH_PATH . 'includes/class-wpsh-core.php';
require_once WPSH_PATH . 'includes/class-wpsh-cron.php';
require_once WPSH_PATH . 'admin/class-wpsh-admin.php';
require_once WPSH_PATH . 'admin/class-wpsh-ajax.php';
require_once WPSH_PATH . 'admin/class-wpsh-meta.php';

/**
 * Initialize the plugin.
 */
function wpsh_init_plugin() {
	// core engine.
	$core = new WPSH_Core();
	$core->init();

	// cron processor.
	$cron = new WPSH_Cron();
	$cron->init();

	// meta boxes.
	$meta = new WPSH_Meta();
	$meta->init();

	// admin interface.
	$admin = new WPSH_Admin();
	$admin->init();

	if ( is_admin() ) {
		// ajax handlers.
		$ajax = new WPSH_Ajax();
		$ajax->init();
	}
}
add_action( 'plugins_loaded', 'wpsh_init_plugin' );

/**
 * Activation Hook.
 */
register_activation_hook( __FILE__, 'wpsh_plugin_activate' );
function wpsh_plugin_activate() {
	$dir = WPSH_Helper::get_dir();
	if ( ! file_exists( $dir ) ) {
		wp_mkdir_p( $dir );
	}

	require_once WPSH_PATH . 'includes/class-wpsh-cron.php';
	$cron = new WPSH_Cron();
	$cron->schedule_events();
}

/**
 * Deactivation Hook.
 */
register_deactivation_hook( __FILE__, 'wpsh_plugin_deactivate' );
function wpsh_plugin_deactivate() {
	require_once WPSH_PATH . 'includes/class-wpsh-cron.php';
	$cron = new WPSH_Cron();
	$cron->clear_events();

	$htaccess_path = ABSPATH . '.htaccess';
	
	global $wp_filesystem;
	if ( empty( $wp_filesystem ) ) {
		require_once ABSPATH . 'wp-admin/includes/file.php';
		WP_Filesystem();
	}

	if ( $wp_filesystem->exists( $htaccess_path ) && $wp_filesystem->is_writable( $htaccess_path ) ) {
		$content = $wp_filesystem->get_contents( $htaccess_path );
		$marker_suffix = ( is_multisite() && function_exists( 'get_current_blog_id' ) ) ? ' - Site ' . get_current_blog_id() : '';
		$marker_start = '# BEGIN Moon Static HTML Pages' . $marker_suffix;
		$marker_end = '# END Moon Static HTML Pages' . $marker_suffix;

		if ( strpos( $content, $marker_start ) !== false ) {
			$content = preg_replace( '/' . preg_quote( $marker_start, '/' ) . '.*?' . preg_quote( $marker_end, '/' ) . '/s', '', $content );
			$wp_filesystem->put_contents( $htaccess_path, trim( $content ) );
		}
	}
}