<?php
/**
 * Activation / deactivation.
 *
 * @package Form_Flight_Recorder
 */

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

/**
 * Install routines.
 */
class Ffrd_Install {

	/**
	 * Activate: events table, crons, defaults.
	 */
	public static function activate() {
		global $wpdb;

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

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

		dbDelta(
			"CREATE TABLE {$table} (
				id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
				event_type VARCHAR(32) NOT NULL,
				object_ref VARCHAR(191) NOT NULL DEFAULT '',
				severity VARCHAR(10) NOT NULL DEFAULT 'info',
				data LONGTEXT NULL,
				created_at DATETIME NOT NULL,
				PRIMARY KEY  (id),
				KEY type_time (event_type, created_at),
				KEY time (created_at)
			) {$charset_collate};"
		);

		if ( ! wp_next_scheduled( 'ffrd_tick_hourly' ) ) {
			wp_schedule_event( time() + HOUR_IN_SECONDS, 'hourly', 'ffrd_tick_hourly' );
		}
		if ( ! wp_next_scheduled( 'ffrd_tick_daily' ) ) {
			wp_schedule_event( time() + DAY_IN_SECONDS, 'daily', 'ffrd_tick_daily' );
		}

		if ( false === get_option( 'ffrd_installed_at', false ) ) {
			add_option( 'ffrd_installed_at', time() );
		}
	}

	/**
	 * Deactivate: clear crons (data stays).
	 */
	public static function deactivate() {
		wp_clear_scheduled_hook( 'ffrd_tick_hourly' );
		wp_clear_scheduled_hook( 'ffrd_tick_daily' );
	}
}
