<?php
/**
 * Plugin activator.
 *
 * @package GoValid_QR
 */

defined( 'ABSPATH' ) || exit;

class GoValid_QR_Activator {

	/**
	 * Run on plugin activation.
	 */
	public static function activate(): void {
		// Schedule daily cache cleanup.
		if ( ! wp_next_scheduled( 'govalid_qr_cache_cleanup' ) ) {
			wp_schedule_event( time(), 'daily', 'govalid_qr_cache_cleanup' );
		}

		// Create cache directory.
		$upload_dir = wp_upload_dir();
		$cache_dir  = $upload_dir['basedir'] . '/govalid-qr-cache';
		if ( ! file_exists( $cache_dir ) ) {
			wp_mkdir_p( $cache_dir );
		}

		// Create / update custom database tables.
		self::maybe_create_tables();

		// Register verify rewrite rule and flush.
		$page_id = (int) get_option( 'govalid_qr_verify_page_id', 0 );
		if ( $page_id && 'publish' === get_post_status( $page_id ) ) {
			add_rewrite_rule(
				'^v/(.+)/?$',
				'index.php?page_id=' . $page_id . '&govalid_verify_token=$matches[1]',
				'top'
			);
		}
		flush_rewrite_rules( false );

		// Store activation version.
		update_option( 'govalid_qr_version', GOVALID_QR_VERSION );
	}

	/**
	 * Create or update plugin database tables when schema version changes.
	 */
	public static function maybe_create_tables(): void {
		$installed_db_version = get_option( 'govalid_qr_db_version', '0' );
		$current_db_version   = '1.0.0'; // Bump when schema changes.

		if ( version_compare( $installed_db_version, $current_db_version, '>=' ) ) {
			return;
		}

		require_once GOVALID_QR_PLUGIN_DIR . 'includes/class-govalid-form-model.php';
		GoValid_Form_Model::create_tables();

		update_option( 'govalid_qr_db_version', $current_db_version );
	}
}
