<?php
/**
 * Handles plugin activation, deactivation, and DB table creation.
 *
 * @package Smart_Product_Sort
 */

defined( 'ABSPATH' ) || exit;

/**
 * Class SPSORT_Install
 */
class SPSORT_Install {

	/**
	 * DB table name (without prefix).
	 */
	const TABLE = 'spsort_sort_rules';

	/**
	 * Run on plugin activation.
	 *
	 * @return void
	 */
	public static function activate() {
		self::create_tables();
		self::seed_defaults();
		update_option( 'spsort_version', SPSORT_VERSION );
		flush_rewrite_rules();
	}

	/**
	 * Run on plugin deactivation.
	 *
	 * @return void
	 */
	public static function deactivate() {
		flush_rewrite_rules();
	}

	/**
	 * Create custom DB tables via dbDelta.
	 *
	 * @return void
	 */
	private static function create_tables() {
		global $wpdb;

		$table           = $wpdb->prefix . self::TABLE;
		$charset_collate = $wpdb->get_charset_collate();

		/*
		 * dbDelta() requires the full SQL string with the table name inline;
		 * $wpdb->prepare( '%i' ) cannot be used here because dbDelta parses
		 * the raw CREATE TABLE statement. The table name is built from
		 * $wpdb->prefix (trusted) + a class constant.
		 */
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		$sql = "CREATE TABLE {$table} (
			id          BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
			rule_name   VARCHAR(100)        NOT NULL,
			sort_by     VARCHAR(50)         NOT NULL DEFAULT 'date',
			sort_order  VARCHAR(4)          NOT NULL DEFAULT 'DESC',
			category_id BIGINT(20) UNSIGNED          DEFAULT NULL,
			is_active   TINYINT(1)          NOT NULL DEFAULT 1,
			priority    INT(11)             NOT NULL DEFAULT 10,
			created_at  DATETIME            NOT NULL DEFAULT CURRENT_TIMESTAMP,
			updated_at  DATETIME            NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
			PRIMARY KEY  (id),
			KEY category_id (category_id),
			KEY is_active   (is_active)
		) {$charset_collate};";

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

	/**
	 * Seed a default global sort rule on fresh installs.
	 *
	 * @return void
	 */
	private static function seed_defaults() {
		global $wpdb;

		$table = $wpdb->prefix . self::TABLE;

		// Activation-only query — no caching needed; runs once on install.
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$count = (int) $wpdb->get_var(
			$wpdb->prepare( 'SELECT COUNT(*) FROM %i', $table )
		);

		if ( 0 === $count ) {
			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
			$wpdb->insert(
				$table,
				array(
					'rule_name'  => 'Default - Newest First',
					'sort_by'    => 'date',
					'sort_order' => 'DESC',
					'is_active'  => 1,
					'priority'   => 10,
				),
				array( '%s', '%s', '%s', '%d', '%d' )
			);
		}
	}
}
