<?php
namespace WPVOID\StockBeacon;

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

class Activator {
	private const DB_VERSION = '1.0.0';

	/**
	 * Upgrade the schema on normal plugin load because activation hooks do not run on updates.
	 */
	public static function maybe_upgrade(): void {
		$installed_version = (string) get_option( 'stockbeacon_db_version', '' );
		if ( version_compare( $installed_version, self::DB_VERSION, '<' ) ) {
			self::activate();
		}
	}

	public static function activate(): void {
		global $wpdb;
		require_once ABSPATH . 'wp-admin/includes/upgrade.php';

		$charset       = $wpdb->get_charset_collate();
		$subscriptions = $wpdb->prefix . 'stockbeacon_subscriptions';
		$logs          = $wpdb->prefix . 'stockbeacon_logs';

		$sql_subscriptions = 'CREATE TABLE ' . $subscriptions . " (
			id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
			product_id BIGINT(20) UNSIGNED NOT NULL,
			variation_id BIGINT(20) UNSIGNED DEFAULT 0,
			email VARCHAR(200) NOT NULL,
			user_id BIGINT(20) UNSIGNED DEFAULT 0,
			status VARCHAR(20) NOT NULL DEFAULT 'active',
			opt_in_token VARCHAR(64) DEFAULT NULL,
			unsubscribe_token_hash CHAR(64) DEFAULT NULL,
			opted_in_at DATETIME DEFAULT NULL,
			notified_at DATETIME DEFAULT NULL,
			purchased_at DATETIME DEFAULT NULL,
			ip_address VARCHAR(45) DEFAULT '',
			locale VARCHAR(10) DEFAULT 'en_US',
			consent TINYINT(1) DEFAULT 0,
			created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
			PRIMARY KEY (id),
			UNIQUE KEY email_product (email, product_id, variation_id),
			KEY product_id (product_id),
			KEY variation_id (variation_id),
			KEY status (status),
			KEY email (email),
			KEY opt_in_token (opt_in_token),
			KEY unsubscribe_token_hash (unsubscribe_token_hash)
		) " . $charset . ';';

		$sql_logs = 'CREATE TABLE ' . $logs . " (
			id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
			subscription_id BIGINT(20) UNSIGNED NOT NULL,
			event_type VARCHAR(20) NOT NULL,
			metadata_json TEXT NULL,
			created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
			PRIMARY KEY (id),
			KEY subscription_id (subscription_id),
			KEY event_type (event_type),
			KEY created_at (created_at)
		) " . $charset . ';';

		dbDelta( $sql_subscriptions );
		dbDelta( $sql_logs );

		if ( ! get_option( 'stockbeacon_settings' ) ) {
			update_option( 'stockbeacon_settings', Settings::defaults() );
		}
		update_option( 'stockbeacon_db_version', self::DB_VERSION );
	}

	public static function uninstall_cleanup(): void {
		global $wpdb;
		$settings = Settings::get();
		if ( empty( $settings['delete_data_on_uninstall'] ) ) {
			return;
		}

		// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Uninstall opt-in cleanup drops the plugin-owned tables; names are built from the trusted WordPress prefix.
		$wpdb->query( 'DROP TABLE IF EXISTS ' . $wpdb->prefix . 'stockbeacon_subscriptions' );
		$wpdb->query( 'DROP TABLE IF EXISTS ' . $wpdb->prefix . 'stockbeacon_logs' );
		// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter

		$option_patterns = array(
			$wpdb->esc_like( 'stockbeacon_' ) . '%',
			$wpdb->esc_like( '_transient_stockbeacon_' ) . '%',
			$wpdb->esc_like( '_transient_timeout_stockbeacon_' ) . '%',
		);
		foreach ( $option_patterns as $option_pattern ) {
			// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Uninstall opt-in cleanup of plugin options; only the core options table name is interpolated.
			$wpdb->query(
				$wpdb->prepare(
					"DELETE FROM {$wpdb->options} WHERE option_name LIKE %s",
					$option_pattern
				)
			);
			// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		}

		$meta_like = $wpdb->esc_like( '_stockbeacon_' ) . '%';
		// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Uninstall opt-in cleanup of plugin post meta; only the core postmeta table name is interpolated.
		$wpdb->query(
			$wpdb->prepare(
				"DELETE FROM {$wpdb->postmeta} WHERE meta_key LIKE %s",
				$meta_like
			)
		);
		// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
	}
}
