<?php
/**
 * Plugin activation.
 *
 * @package JOCBM
 */

namespace JOCBM;

use JOCBM\Database\Schema;
use JOCBM\Database\Seeder;

defined( 'ABSPATH' ) || exit;

/**
 * Class Activator
 */
final class Activator {

	/**
	 * Run on plugin activation.
	 */
	public static function activate(): void {
		Schema::install();
		Seeder::seed();
		self::ensure_upload_dir();

		$is_first_install = false === get_option( 'jocbm_installed', false );

		update_option( 'jocbm_db_version', JOCBM_DB_VERSION );
		update_option( 'jocbm_version', JOCBM_VERSION );
		update_option( 'jocbm_seed_version', JOCBM_SEED_VERSION );

		if ( $is_first_install ) {
			// Brand-new install — show Welcome once.
			add_option( 'jocbm_welcome_seen', false );
			add_option( 'jocbm_installed', 1 );
		} else {
			// Reactivation — never reset welcome; returning users go to dashboard.
			if ( ! get_option( 'jocbm_welcome_seen', false ) && self::site_has_prior_use() ) {
				update_option( 'jocbm_welcome_seen', true );
			}
		}

		// Default on for new installs and upgrades that never set the option.
		add_option( 'jocbm_frontend_editor', 1 );

		set_transient( 'jocbm_activation_redirect', 1, 120 );

		flush_rewrite_rules();
	}

	/**
	 * Whether the site already has Blockora Morph content (returning user).
	 */
	private static function site_has_prior_use(): bool {
		global $wpdb;

		$user = Schema::table( 'user_blocks' );
		if ( $user && Schema::count_rows( 'user_blocks' ) > 0 ) {
			return true;
		}

		$content = Schema::table( 'user_contents' );
		if ( $content && Schema::count_rows( 'user_contents' ) > 0 ) {
			return true;
		}

		return false;
	}

	/**
	 * Ensure uploads/joc-blockora-morph exists.
	 */
	private static function ensure_upload_dir(): void {
		$upload_dir = wp_upload_dir();
		$dir        = trailingslashit( $upload_dir['basedir'] ) . 'joc-blockora-morph';

		if ( ! is_dir( $dir ) ) {
			wp_mkdir_p( $dir );
		}

		$index = trailingslashit( $dir ) . 'index.php';
		if ( ! file_exists( $index ) ) {
			file_put_contents( $index, "<?php\n// Silence is golden.\n" );
		}
	}
}
