<?php
/**
 * Add status column to members table
 *
 * Run this file once to add the status column
 *
 * @package KarateClubManager
 */

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

/**
 * Add status column to macm_members table
 */
function macm_add_member_status_column() {
	global $wpdb;

	// Check if migration was already attempted via option.
	$migration_done = get_option( 'macm_status_column_added', false );
	if ( $migration_done ) {
		return false;
	}

	// Check if column already exists with caching.
	$cache_key     = 'macm_status_column_exists';
	$column_exists = wp_cache_get( $cache_key, 'macm' );

	if ( false === $column_exists ) {
		$column_exists = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT * FROM INFORMATION_SCHEMA.COLUMNS
				WHERE TABLE_SCHEMA = %s
				AND TABLE_NAME = %s
				AND COLUMN_NAME = 'status'",
				DB_NAME,
				$wpdb->prefix . 'macm_members'
			)
		);
		wp_cache_set( $cache_key, $column_exists, 'macm', 300 );
	}

	if ( empty( $column_exists ) ) {
		// Add status column using dbDelta-style approach.
		require_once ABSPATH . 'wp-admin/includes/upgrade.php';

		// Use query for ALTER TABLE (dbDelta doesn't support ALTER).
		$result = $wpdb->query(
			"ALTER TABLE {$wpdb->prefix}macm_members
			ADD COLUMN status varchar(20) NOT NULL DEFAULT 'active' AFTER updated_at,
			ADD KEY status (status)"
		);

		// Mark migration as complete.
		update_option( 'macm_status_column_added', true );
		wp_cache_delete( $cache_key, 'macm' );

		return ( false !== $result );
	} else {
		// Column exists, mark as done.
		update_option( 'macm_status_column_added', true );
		return false;
	}
}

// Run the migration.
macm_add_member_status_column();
