<?php
/**
 * Installation: custom table for tracking rule-managed product assignments.
 *
 * @package SmartCategories
 */

defined( 'ABSPATH' ) || exit;

/**
 * Class SCWC_Install
 */
class SCWC_Install {

	/**
	 * Option key storing the installed DB schema version.
	 */
	const DB_VERSION_OPTION = 'scwc_db_version';

	/**
	 * Current DB schema version.
	 */
	const DB_VERSION = '1.1.0';

	/**
	 * Assignments table name (without prefix).
	 */
	const TABLE = 'scwc_assignments';

	/**
	 * Fully-qualified assignments table name.
	 *
	 * @return string
	 */
	public static function table_name() {
		global $wpdb;
		return $wpdb->prefix . self::TABLE;
	}

	/**
	 * Activation hook.
	 */
	public static function activate() {
		self::create_tables();
		update_option( self::DB_VERSION_OPTION, self::DB_VERSION );
		add_option( 'scwc_activated_at', time(), '', false );
	}

	/**
	 * Deactivation hook. We intentionally keep data and unschedule background work.
	 */
	public static function deactivate() {
		if ( function_exists( 'as_unschedule_all_actions' ) ) {
			// Use literal hook names to avoid depending on the Scheduler class
			// being loaded during the deactivation request.
			as_unschedule_all_actions( 'scwc_process_term_page' );
			as_unschedule_all_actions( 'scwc_process_term' );
			as_unschedule_all_actions( 'scwc_daily_refresh' );
			as_unschedule_all_actions( 'scwc_aggregate_sales' );
		}
	}

	/**
	 * Create / upgrade DB tables. Safe to call repeatedly (dbDelta).
	 */
	public static function create_tables() {
		global $wpdb;

		require_once ABSPATH . 'wp-admin/includes/upgrade.php';

		$table           = self::table_name();
		$charset_collate = $wpdb->get_charset_collate();

		$sql = "CREATE TABLE {$table} (
			id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
			term_id BIGINT UNSIGNED NOT NULL,
			product_id BIGINT UNSIGNED NOT NULL,
			created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
			PRIMARY KEY  (id),
			UNIQUE KEY term_product (term_id, product_id),
			KEY term_id (term_id),
			KEY product_id (product_id)
		) {$charset_collate};";

		dbDelta( $sql );

	}

	/**
	 * Ensure schema is current; run from boot to self-heal after manual upgrades.
	 */
	public static function maybe_upgrade() {
		if ( get_option( self::DB_VERSION_OPTION ) !== self::DB_VERSION ) {
			self::create_tables();
			update_option( self::DB_VERSION_OPTION, self::DB_VERSION );
		}
		// Backfill for installs that predate the review engine.
		add_option( 'scwc_activated_at', time(), '', false );
	}
}
