<?php
/**
 * Activation tasks for the WordPress.org free build.
 *
 * @package CF7MasterPro\Core
 */

namespace CF7MasterPro\Core;

defined( 'ABSPATH' ) || exit;

/**
 * Database setup and defaults.
 */
class Activator {

	/**
	 * Activation entry point.
	 */
	public static function activate() {
		self::create_tables();
		self::set_default_options();
		self::add_capabilities();
		set_transient( 'cf7mp_activation_redirect', true, 30 );
	}

	/**
	 * Create free-build tables only.
	 */
	private static function create_tables() {
		global $wpdb;
		$charset_collate = $wpdb->get_charset_collate();
		$prefix          = $wpdb->prefix . CF7MP_DB_PREFIX;

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

		$sql_submissions = "CREATE TABLE {$prefix}submissions (
			id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
			form_id BIGINT(20) UNSIGNED NOT NULL,
			form_data LONGTEXT NOT NULL,
			ip_address VARCHAR(45) DEFAULT '',
			user_agent TEXT,
			referer TEXT,
			utm_source VARCHAR(255) DEFAULT '',
			utm_medium VARCHAR(255) DEFAULT '',
			utm_campaign VARCHAR(255) DEFAULT '',
			category VARCHAR(64) DEFAULT '',
			priority VARCHAR(16) DEFAULT '',
			status VARCHAR(20) DEFAULT 'new',
			created_at DATETIME NOT NULL,
			PRIMARY KEY (id),
			KEY form_id (form_id),
			KEY created_at (created_at),
			KEY status (status),
			KEY category (category),
			KEY priority (priority)
		) {$charset_collate};";

		$sql_form_settings = "CREATE TABLE {$prefix}form_settings (
			id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
			form_id BIGINT(20) UNSIGNED NOT NULL,
			settings LONGTEXT NOT NULL,
			updated_at DATETIME NOT NULL,
			PRIMARY KEY (id),
			UNIQUE KEY form_id (form_id)
		) {$charset_collate};";

		dbDelta( $sql_submissions );
		dbDelta( $sql_form_settings );

		update_option( 'cf7mp_db_version', CF7MP_VERSION );
	}

	/**
	 * Set defaults.
	 */
	private static function set_default_options() {
		$defaults = array(
			'data_retention' => 365,
		);
		add_option( 'cf7mp_settings', $defaults );
	}

	/**
	 * Add capabilities.
	 */
	private static function add_capabilities() {
		$role = get_role( 'administrator' );
		if ( $role ) {
			$role->add_cap( 'manage_cf7mp' );
			$role->add_cap( 'view_cf7mp_submissions' );
		}
	}
}
