<?php
/**
 * Plugin activation and migration handler
 *
 * Handles plugin setup, data migrations, and version checks.
 *
 * @package BW_Schema
 * @since 3.0.0-babel
 */

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

class BW_Schema_Migration {

	const PREFIX = 'bw_schema_';
	const DB_VERSION = '1.0.0';
	const DB_VERSION_OPTION = 'bw_schema_db_version';

	/**
	 * Run activation routines
	 *
	 * Called when plugin is activated.
	 *
	 * @return void
	 */
	public static function activate() {
		// Create custom tables
		self::create_tables();

		// Set initial options
		self::initialize_options();

		// Mark as activated
		update_option( self::DB_VERSION_OPTION, self::DB_VERSION );
	}

	/**
	 * Run deactivation routines
	 *
	 * Called when plugin is deactivated.
	 *
	 * @return void
	 */
	public static function deactivate() {
		// Clear caches
		if ( class_exists( 'BW_Schema_Service_Cache' ) ) {
			BW_Schema_Service_Cache::clear_all();
		}

		// Plugin data is NOT deleted on deactivation (user might reactivate)
	}

	/**
	 * Run uninstall routines
	 *
	 * Called when plugin is deleted.
	 *
	 * @return void
	 */
	public static function uninstall() {
		// Only proceed if user has permission
		if ( ! current_user_can( 'delete_plugins' ) ) {
			return;
		}

		// Delete all plugin options
		self::delete_all_options();

		// Drop custom tables
		self::drop_tables();

		// Clear all transients
		wp_cache_flush();
	}

	/**
	 * Create custom database tables
	 *
	 * @return void
	 */
	private static function create_tables() {
		global $wpdb;

		$charset_collate = $wpdb->get_charset_collate();

		// Survey responses table
		$survey_table = $wpdb->prefix . 'bw_schema_survey_responses';

		if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $survey_table ) ) !== $survey_table ) {
			$sql = "CREATE TABLE $survey_table (
				id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
				target_post_id BIGINT UNSIGNED NULL,
				submitter_name VARCHAR(191) NOT NULL,
				submitter_email VARCHAR(191) NULL,
				submitter_ip VARCHAR(45) NOT NULL,
				status VARCHAR(32) NOT NULL DEFAULT 'new',
				raw_payload LONGTEXT NOT NULL,
				structured_payload LONGTEXT NULL,
				moderator_notes TEXT NULL,
				created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
				updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
				published_at DATETIME NULL,
				PRIMARY KEY (id),
				KEY target_post_id (target_post_id),
				KEY status (status),
				KEY created_at (created_at)
			) $charset_collate;";

			require_once ABSPATH . 'wp-admin/includes/upgrade.php';
			dbDelta( $sql );
		}
	}

	/**
	 * Drop custom database tables
	 *
	 * @return void
	 */
	private static function drop_tables() {
		global $wpdb;

		$survey_table = $wpdb->prefix . 'bw_schema_survey_responses';

		$wpdb->query( "DROP TABLE IF EXISTS $survey_table" ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
	}

	/**
	 * Initialize plugin options with defaults
	 *
	 * @return void
	 */
	private static function initialize_options() {
		// Only set defaults if not already configured
		if ( get_option( self::PREFIX . 'setup_complete' ) ) {
			return;
		}

		// Organization defaults
		if ( ! get_option( self::PREFIX . 'organization' ) ) {
			update_option( self::PREFIX . 'organization', array(
				'name'  => get_bloginfo( 'name' ),
				'url'   => home_url( '/' ),
				'email' => get_option( 'admin_email' ),
			));
		}

		// Feature toggles
		if ( ! get_option( self::PREFIX . 'enable_schema' ) ) {
			update_option( self::PREFIX . 'enable_schema', 'yes' );
		}

		if ( ! get_option( self::PREFIX . 'enable_cache' ) ) {
			update_option( self::PREFIX . 'enable_cache', 'yes' );
		}

		// Mark setup as complete for next time
		update_option( self::PREFIX . 'setup_complete', '1' );
	}

	/**
	 * Delete all plugin options
	 *
	 * Safely removes all plugin data from wp_options.
	 *
	 * @return void
	 */
	private static function delete_all_options() {
		global $wpdb;

		// Delete all options with our prefix
		$wpdb->query( $wpdb->prepare(
			"DELETE FROM $wpdb->options WHERE option_name LIKE %s",
			self::PREFIX . '%'
		) );

		// Also clean legacy options from the pre-rename era (BW Babel)
		$wpdb->query( $wpdb->prepare(
			"DELETE FROM $wpdb->options WHERE option_name LIKE %s",
			'bw_babel_%'
		) );

		// Delete all post meta with our prefix
		$wpdb->query( $wpdb->prepare(
			"DELETE FROM $wpdb->postmeta WHERE meta_key LIKE %s",
			'_' . self::PREFIX . '%'
		) );

		// Delete all user meta with our prefix
		$wpdb->query( $wpdb->prepare(
			"DELETE FROM $wpdb->usermeta WHERE meta_key LIKE %s",
			self::PREFIX . '%'
		) );
	}

	/**
	 * Check if migration is needed
	 *
	 * Compares stored DB version with current plugin version.
	 *
	 * @return bool True if migration is needed
	 */
	public static function needs_migration() {
		$current_version = get_option( self::DB_VERSION_OPTION, '0.0.0' );
		return version_compare( $current_version, self::DB_VERSION, '<' );
	}

	/**
	 * Run database migrations
	 *
	 * @return void
	 */
	public static function migrate() {
		$current_version = get_option( self::DB_VERSION_OPTION, '0.0.0' );

		// Version 1.0.0: Initial setup
		if ( version_compare( $current_version, '1.0.0', '<' ) ) {
			self::create_tables();
			self::initialize_options();
		}

		// Mark as migrated
		update_option( self::DB_VERSION_OPTION, self::DB_VERSION );
	}

	/**
	 * Get plugin status summary
	 *
	 * @return array Status information
	 */
	public static function get_status() {
		global $wpdb;

		$survey_table = $wpdb->prefix . 'bw_schema_survey_responses';
		$table_exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $survey_table ) ) === $survey_table;

		return array(
			'version'        => BW_SCHEMA_VERSION,
			'db_version'     => get_option( self::DB_VERSION_OPTION, 'unknown' ),
			'tables_created' => $table_exists,
			'setup_complete' => (bool) get_option( self::PREFIX . 'setup_complete' ),
			'needs_migration' => self::needs_migration(),
		);
	}

	/**
	 * Log migration action for debugging
	 *
	 * @param string $message Log message
	 * @param string $level Log level (info, warning, error)
	 * @return void
	 */
	private static function log( $message, $level = 'info' ) {
		if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
			error_log( '[BW Schema Migration] [' . strtoupper( $level ) . '] ' . $message );
		}
	}
}
