<?php
/**
 * KooKoa Folders
 *
 * @package KookoaWPF
 * @license GPL-2.0-or-later
 */

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

/**
 * Database operations: activation, deactivation, upgrades, and legacy cleanup.
 *
 * @since 1.0.0
 */
class KookoaWPF_Database {

	/**
	 * Plugin activation
	 */
	public static function activate(): void {
		self::set_default_options();
		update_option( 'kookoawpf_db_version', KOOKOAWPF_VERSION );
		// Track first-install timestamp the first time activate() runs.
		// Used by dashboard notices to delay calls-to-action a few days
		// after install (e.g. trial invitation). add_option() is a no-op
		// if the option already exists, so re-activating doesn't reset it.
		add_option( 'kookoawpf_install_time', time() );
		flush_rewrite_rules();
	}

	/**
	 * Plugin deactivation
	 */
	public static function deactivate(): void {
		flush_rewrite_rules();
	}

	/**
	 * Set default plugin options
	 */
	private static function set_default_options(): void {
		$defaults = array(
			'kookoawpf_enabled_post_types'    => array( 'attachment' ),
			'kookoawpf_show_item_count'       => 'yes',
			'kookoawpf_show_breadcrumb'       => 'yes',
			'kookoawpf_show_subfolder_cards'  => 'yes',
			'kookoawpf_sidebar_width'         => 350,
			'kookoawpf_folder_color'          => '#39FF14',
			'kookoawpf_tree_font_size'        => 'default',
			'kookoawpf_force_english'         => 'yes',
			'kookoawpf_show_metadata_tooltip' => 'yes',
			'kookoawpf_show_folder_stats'     => 'yes',
			'kookoawpf_allowed_roles'         => array( 'administrator' ),
		);

		foreach ( $defaults as $key => $value ) {
			if ( get_option( $key ) === false ) {
				add_option( $key, $value );
			}
		}
	}

	/**
	 * Run upgrade routines if needed
	 */
	public static function maybe_upgrade(): void {
		$db_version = get_option( 'kookoawpf_db_version', '0' );

		if ( version_compare( $db_version, KOOKOAWPF_VERSION, '<' ) ) {
			self::set_default_options();
			update_option( 'kookoawpf_db_version', KOOKOAWPF_VERSION );
		}
	}
}
