<?php
/**
 * Activity Log Database Table
 * 
 * Creates and manages the activity log database table.
 * 
 * @package WooNooW\Core\ActivityLog
 */

namespace WooNooW\Core\ActivityLog;

class ActivityLogTable {
	
	/**
	 * Table name (without prefix)
	 */
	const TABLE_NAME = 'woonoow_activity_log';
	
	/**
	 * Database version
	 */
	const DB_VERSION = '1.0.0';
	
	/**
	 * Get full table name with prefix
	 * 
	 * @return string
	 */
	public static function get_table_name() {
		global $wpdb;
		return $wpdb->prefix . self::TABLE_NAME;
	}
	
	/**
	 * Create or update table
	 */
	public static function create_table() {
		global $wpdb;
		
		$table_name = self::get_table_name();
		$charset_collate = $wpdb->get_charset_collate();
		
		$sql = "CREATE TABLE IF NOT EXISTS {$table_name} (
			id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
			user_id BIGINT UNSIGNED NOT NULL,
			user_name VARCHAR(255) NOT NULL,
			action VARCHAR(50) NOT NULL,
			object_type VARCHAR(50) NOT NULL,
			object_id BIGINT UNSIGNED NOT NULL,
			object_name VARCHAR(255),
			description TEXT,
			metadata LONGTEXT,
			ip_address VARCHAR(45),
			user_agent TEXT,
			created_at DATETIME NOT NULL,
			
			INDEX idx_user_id (user_id),
			INDEX idx_action (action),
			INDEX idx_object (object_type, object_id),
			INDEX idx_created_at (created_at)
		) {$charset_collate};";
		
		require_once ABSPATH . 'wp-admin/includes/upgrade.php';
		dbDelta($sql);
		
		// Store version
		update_option('woonoow_activity_log_db_version', self::DB_VERSION);
	}
	
	/**
	 * Check if table exists
	 * 
	 * @return bool
	 */
	public static function table_exists() {
		global $wpdb;
		$table_name = self::get_table_name();
		return $wpdb->get_var("SHOW TABLES LIKE '{$table_name}'") === $table_name;
	}
	
	/**
	 * Drop table (for uninstall)
	 */
	public static function drop_table() {
		global $wpdb;
		$table_name = self::get_table_name();
		$wpdb->query("DROP TABLE IF EXISTS {$table_name}");
		delete_option('woonoow_activity_log_db_version');
	}
}
