<?php
/**
 * Fired during plugin activation.
 *
 * @package PrivexPasswordProtect
 */

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

/**
 * Class PPMSTR_Activator
 */
class PPMSTR_Activator {

	/**
	 * Run activation tasks.
	 */
	public static function activate() {

		// Load settings class if not already loaded.
		if ( ! class_exists( 'PPMSTR_Settings' ) ) {
			require_once PPMSTR_PLUGIN_DIR . 'admin/class-ppmstr-settings.php';
		}

		$defaults = PPMSTR_Settings::defaults();

		if ( false === get_option( 'ppmstr_settings' ) ) {
			add_option( 'ppmstr_settings', $defaults );
		}

		// Create or update database tables.
		self::create_tables();

		// Store version for future upgrade routines.
		update_option( 'ppmstr_version', PPMSTR_VERSION );
	}

	/**
	 * Create custom database tables.
	 */
	private static function create_tables() {
		global $wpdb;

		$table_name = $wpdb->prefix . 'ppmstr_access_logs';
		$charset_collate = $wpdb->get_charset_collate();

		$sql = "CREATE TABLE $table_name (
			id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
			type varchar(20) NOT NULL,
			target_id bigint(20) NOT NULL DEFAULT 0,
			status varchar(20) NOT NULL,
			ip_address varchar(64) DEFAULT '' NOT NULL,
			user_agent text,
			created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
			PRIMARY KEY  (id),
			KEY type (type),
			KEY status (status),
			KEY created_at (created_at)
		) $charset_collate;";

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