<?php
/**
 * Activation and upgrade routines.
 *
 * @package Vist360
 */

namespace Vist360\Core;

defined( 'ABSPATH' ) || exit;

use Vist360\Domain\TourPostType;

/**
 * Creates the analytics table and handles versioned upgrades.
 */
class Installer {

	const DB_VERSION        = '1.0.0';
	const DB_VERSION_OPTION = 'vist360_db_version';

	/**
	 * Plugin activation callback.
	 */
	public static function activate() {
		self::create_tables();
		update_option( self::DB_VERSION_OPTION, self::DB_VERSION );

		( new TourPostType() )->register_post_type();
		flush_rewrite_rules();
	}

	/**
	 * Run upgrades when the stored schema version is outdated.
	 */
	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 );
		}
	}

	/**
	 * Create or update the analytics events table.
	 */
	private static function create_tables() {
		global $wpdb;

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

		$table           = $wpdb->prefix . 'vist360_events';
		$charset_collate = $wpdb->get_charset_collate();

		dbDelta(
			"CREATE TABLE {$table} (
				id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
				tour_id bigint(20) unsigned NOT NULL,
				event_type varchar(32) NOT NULL,
				scene_index smallint(5) unsigned NOT NULL DEFAULT 0,
				visitor_hash char(32) NOT NULL DEFAULT '',
				created_at datetime NOT NULL,
				PRIMARY KEY  (id),
				KEY tour_id (tour_id),
				KEY event_type (event_type),
				KEY created_at (created_at)
			) {$charset_collate};"
		);
	}
}
