<?php
/**
 * Security Schema
 *
 * Creates security logging table.
 *
 * @package DonorCore\Security
 */

namespace DonorCore\Security;

defined( 'ABSPATH' ) || exit;

/**
 * Security Schema Class
 */
class Security_Schema {

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

		$sql = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}donorcore_security_log (
			id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
			event_type varchar(50) NOT NULL,
			reason varchar(100) NOT NULL,
			ip_address varchar(45) NOT NULL,
			user_agent text,
			metadata longtext,
			created_at datetime NOT NULL,
			PRIMARY KEY (id),
			KEY event_type (event_type),
			KEY ip_address (ip_address),
			KEY created_at (created_at)
		) $charset_collate;";

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

		// Also add ip_address column to donation_logs if not exists.
		$table = $wpdb->prefix . 'donorcore_donation_logs';
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Custom table schema check
		$column_exists = $wpdb->get_var(
			$wpdb->prepare(
				'SHOW COLUMNS FROM %i LIKE %s',
				$table,
				'ip_address'
			)
		);

		if ( ! $column_exists ) {
			// ALTER TABLE - Adding column to existing table
			// phpcs:ignore PluginCheck.Security.DirectDB.SchemaChange, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange
			$wpdb->query(
				// phpcs:ignore PluginCheck.Security.DirectDB.SchemaChange, WordPress.DB.DirectDatabaseQuery.SchemaChange
				$wpdb->prepare(
					// phpcs:ignore PluginCheck.Security.DirectDB.SchemaChange, WordPress.DB.DirectDatabaseQuery.SchemaChange
					'ALTER TABLE %i ADD COLUMN ip_address varchar(45) DEFAULT "" AFTER gateway',
					$table
				)
			);
		}
	}
}
