<?php

/**
 * Fired during plugin activation
 *
 * @link       https://mediahubster.in
 * @since      1.0.0
 *
 * @package    Subs_Sys
 * @subpackage Subs_Sys/includes
 */

// If this file is called directly, abort.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Fired during plugin activation.
 *
 * This class defines all code necessary to run during the plugin's activation.
 *
 * @since      1.0.0
 * @package    Subs_Sys
 * @subpackage Subs_Sys/includes
 * @author     Joe Youngblood <support@subscriptionplugin.com>
 */
class Subs_Sys_Activator {

	/**
	 * Short Description. (use period)
	 *
	 * Long Description.
	 *
	 * @since    1.0.0
	 */
	public static function activate() {
		// Create database tables if needed.
		self::create_tables();

		// Set default options.
		self::set_default_options();

		// Flush rewrite rules.
		flush_rewrite_rules();
	}

	/**
	 * Create database tables for the plugin.
	 *
	 * @since    1.0.0
	 */
	private static function create_tables() {
		global $wpdb;

		$table_name = $wpdb->prefix . 'subs_sys_subscriptions';

		$charset_collate = $wpdb->get_charset_collate();

		$sql = "CREATE TABLE $table_name (
			id mediumint(9) NOT NULL AUTO_INCREMENT,
			user_id bigint(20) NOT NULL,
			subscription_type varchar(50) NOT NULL,
			status varchar(20) DEFAULT 'active',
			start_date datetime DEFAULT CURRENT_TIMESTAMP,
			end_date datetime NULL,
			created_at datetime DEFAULT CURRENT_TIMESTAMP,
			updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
			PRIMARY KEY  (id),
			KEY user_id (user_id),
			KEY status (status)
		) $charset_collate;";

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

	/**
	 * Set default plugin options.
	 *
	 * @since    1.0.0
	 */
	private static function set_default_options() {
		$default_options = array(
			'subs_sys_version'      => SUBS_SYS_VERSION,
			'enable_subscriptions'  => 1,
			'subs_sys_enable_login' => 1,
			'subs_sys_default_role' => 'subscriber',
		);

		foreach ( $default_options as $option_name => $option_value ) {
			if ( false === get_option( $option_name ) ) {
				add_option( $option_name, $option_value );
			}
		}
	}
}
