<?php
/**
 * ==========================
 * 🔐 IGNY8 FILE RULE HEADER
 * ==========================
 * @file         : db-migration.php
 * @location     : /core/db/db-migration.php
 * @type         : Function Library
 * @scope        : Global
 * @allowed      : Database migrations, schema updates, version tracking
 * @reusability  : Globally Reusable
 * @notes        : Database migration system for schema updates
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

/**
 * ========================================================================
 * MIGRATION SYSTEM TEMPLATE
 * ========================================================================
 */

/**
 * Get current database version
 */
function igny8_get_db_version() {
    return get_option('igny8_db_version', '0.1');
}

/**
 * Set database version
 */
function igny8_set_db_version($version) {
    update_option('igny8_db_version', $version);
}

/**
 * Check if migration is needed
 */
function igny8_is_migration_needed($target_version = null) {
    if (!$target_version) {
        $target_version = '0.1'; // Current version
    }
    
    $current_version = igny8_get_db_version();
    return version_compare($current_version, $target_version, '<');
}

/**
 * Run all pending migrations
 */
function igny8_run_migrations() {
    $current_version = igny8_get_db_version();
    $target_version = '0.1';
    
    if (!igny8_is_migration_needed($target_version)) {
        return true; // No migration needed
    }
    
    // Example migration structure:
    // if (version_compare($current_version, '2.7.0', '<')) {
    //     igny8_migration_270();
    // }
    
    // if (version_compare($current_version, '2.7.1', '<')) {
    //     igny8_migration_271();
    // }
    
    // Update to latest version
    igny8_set_db_version($target_version);
    return true;
}

/**
 * ========================================================================
 * MIGRATION FUNCTIONS TEMPLATE
 * ========================================================================
 */

/**
 * Example migration function template
 * 
 * @param string $from_version Version migrating from
 * @param string $to_version Version migrating to
 */
function igny8_migration_template($from_version, $to_version) {
    global $wpdb;
    
    try {
        // Example: Add new column
        // $table_name = $wpdb->prefix . 'igny8_example_table';
        // $column_exists = $wpdb->get_var("SHOW COLUMNS FROM `$table_name` LIKE 'new_column'");
        // if (!$column_exists) {
        //     $wpdb->query("ALTER TABLE `$table_name` ADD COLUMN `new_column` VARCHAR(255) DEFAULT NULL");
        // }
        
        // Example: Create new table
        // $sql = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}igny8_new_table (
        //     id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        //     name VARCHAR(255) NOT NULL,
        //     created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        //     PRIMARY KEY (id)
        // ) {$wpdb->get_charset_collate()};";
        // dbDelta($sql);
        
        // Example: Migrate data
        // $wpdb->query("UPDATE {$wpdb->prefix}igny8_table SET old_field = new_field WHERE condition");
        
        error_log("Igny8 Migration: Successfully migrated from $from_version to $to_version");
        return true;
        
    } catch (Exception $e) {
        error_log("Igny8 Migration Error: " . $e->getMessage());
        return false;
    }
}

/**
 * ========================================================================
 * MIGRATION UTILITIES
 * ========================================================================
 */

/**
 * Backup table before migration
 */
function igny8_backup_table($table_name, $suffix = null) {
    global $wpdb;
    
    if (!$suffix) {
        $suffix = '_backup_' . date('Y_m_d_H_i_s');
    }
    
    $backup_table = $table_name . $suffix;
    
    try {
        $wpdb->query("CREATE TABLE `$backup_table` LIKE `$table_name`");
        $wpdb->query("INSERT INTO `$backup_table` SELECT * FROM `$table_name`");
        return $backup_table;
    } catch (Exception $e) {
        error_log("Igny8 Migration: Failed to backup table $table_name - " . $e->getMessage());
        return false;
    }
}

/**
 * Restore table from backup
 */
function igny8_restore_table($table_name, $backup_table) {
    global $wpdb;
    
    try {
        $wpdb->query("DROP TABLE IF EXISTS `$table_name`");
        $wpdb->query("CREATE TABLE `$table_name` LIKE `$backup_table`");
        $wpdb->query("INSERT INTO `$table_name` SELECT * FROM `$backup_table`");
        return true;
    } catch (Exception $e) {
        error_log("Igny8 Migration: Failed to restore table $table_name - " . $e->getMessage());
        return false;
    }
}

/**
 * Check if table exists
 */
function igny8_table_exists($table_name) {
    global $wpdb;
    return $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
}

/**
 * Check if column exists in table
 */
function igny8_column_exists($table_name, $column_name) {
    global $wpdb;
    $result = $wpdb->get_var("SHOW COLUMNS FROM `$table_name` LIKE '$column_name'");
    return !empty($result);
}

/**
 * Get table structure
 */
function igny8_get_table_structure($table_name) {
    global $wpdb;
    return $wpdb->get_results("DESCRIBE `$table_name`", ARRAY_A);
}

/**
 * ========================================================================
 * AUTO-MIGRATION ON PLUGIN UPDATE
 * ========================================================================
 */

/**
 * Auto-run migrations on plugin update
 */
function igny8_auto_run_migrations() {
    if (current_user_can('manage_options') && igny8_is_migration_needed()) {
        igny8_run_migrations();
    }
}

// Hook to auto-run migrations on admin_init
add_action('admin_init', 'igny8_auto_run_migrations');

/**
 * ========================================================================
 * MIGRATION STATUS & LOGGING
 * ========================================================================
 */

/**
 * Log migration event
 */
function igny8_log_migration($from_version, $to_version, $status = 'success', $message = '') {
    $log_entry = [
        'timestamp' => current_time('mysql'),
        'from_version' => $from_version,
        'to_version' => $to_version,
        'status' => $status,
        'message' => $message,
        'user_id' => get_current_user_id()
    ];
    
    // Store in options (you could also use the logs table)
    $migration_logs = get_option('igny8_migration_logs', []);
    $migration_logs[] = $log_entry;
    
    // Keep only last 50 migration logs
    if (count($migration_logs) > 50) {
        $migration_logs = array_slice($migration_logs, -50);
    }
    
    update_option('igny8_migration_logs', $migration_logs);
}

/**
 * Get migration logs
 */
function igny8_get_migration_logs($limit = 10) {
    $logs = get_option('igny8_migration_logs', []);
    return array_slice(array_reverse($logs), 0, $limit);
}

/**
 * Clear migration logs
 */
function igny8_clear_migration_logs() {
    delete_option('igny8_migration_logs');
}
