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

class Hundred_Prints_Activator {

	/**
	 * Run on plugin activation.
	 */
	public static function activate() {
		require_once HUNDRED_PRINTS_PATH . 'helpers/settings.php';

		// 1. Create DB tables
		self::create_tables();

		// 2. Set default settings
		self::set_default_settings();

		// 3. Set redirect transient for welcome screen
		set_transient( '100prints_welcome', true, 30 );

		if ( ! wp_next_scheduled( 'hundred_prints_prune_generation_logs' ) ) {
			wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', 'hundred_prints_prune_generation_logs' );
		}
	}

	/**
	 * Create custom DB tables.
	 */
	private static function create_tables() {
		global $wpdb;
		$charset_collate = $wpdb->get_charset_collate();

		$table = $wpdb->prefix . '100p_generation_history';
		$sql = "CREATE TABLE $table (
			id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
			generation_uuid varchar(36) NOT NULL,
			template_id varchar(255) NOT NULL,
			template_name varchar(255) NOT NULL DEFAULT '',
			user_id bigint(20) unsigned NULL,
			visitor_ip varchar(45) NULL,
			variables_json longtext NULL,
			output_format varchar(10) NOT NULL DEFAULT 'pdf',
			render_quality varchar(20) NOT NULL DEFAULT 'high',
			status varchar(20) NOT NULL DEFAULT 'success',
			page_id bigint(20) unsigned NULL DEFAULT 0,
			created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
			PRIMARY KEY  (id),
			UNIQUE KEY idx_uuid (generation_uuid),
			KEY idx_template_id (template_id),
			KEY idx_status (status),
			KEY idx_created (created_at)
		) $charset_collate;\n";

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

	/**
	 * Set default options for settings.
	 */
	private static function set_default_settings() {
		if ( ! get_option( '100p_settings' ) ) {
			update_option( '100p_settings', hundred_prints_default_settings() );
		}
	}
}
