<?php
/**
 * Switchboard Database Migration Helper
 *
 * Lightweight helper for modules with custom database tables
 * Provides simple schema versioning and update detection
 *
 * Usage in module:
 * 1. Call check_db_version() in constructor
 * 2. Define get_db_schema() method
 * 3. Define migrate_to_X_X() methods for each version
 */

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

class Switchboard_DB_Migration {

    /**
     * Check if database needs update
     *
     * @param string $table_name Full table name (with prefix)
     * @param string $expected_version Current module DB version
     * @param array $expected_columns Array of column names
     * @return bool True if update needed
     */
    public static function needs_update($table_name, $expected_version, $expected_columns) {
        global $wpdb;

        // Get stored version
        $stored_version = get_option($table_name . '_version', '0');

        // Quick version check first
        if (version_compare($stored_version, $expected_version, '>=')) {
            return false; // Already up to date
        }

        // Check if table exists
        $table_exists = $wpdb->get_var($wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            "SHOW TABLES LIKE %s",
            $table_name
        ));

        if ($table_exists != $table_name) {
            return true; // Table doesn't exist, needs creation
        }

        // Check columns
        $actual_columns = $wpdb->get_col("DESCRIBE {$table_name}", 0); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter
        $missing_columns = array_diff($expected_columns, $actual_columns);

        return !empty($missing_columns); // Has missing columns
    }

    /**
     * Mark database as updated
     *
     * @param string $table_name Full table name (with prefix)
     * @param string $version New version number
     */
    public static function mark_updated($table_name, $version) {
        update_option($table_name . '_version', $version);
    }

    /**
     * Get current database version
     *
     * @param string $table_name Full table name (with prefix)
     * @return string Version number
     */
    public static function get_version($table_name) {
        return get_option($table_name . '_version', '0');
    }

    /**
     * Render update button in settings page
     *
     * @param string $module_slug Module identifier (e.g., 'temporary-login')
     * @param string $current_version Current DB version
     * @param string $new_version New DB version
     */
    public static function render_update_notice($module_slug, $current_version, $new_version) {
        ?>
        <div class="switchboard-db-update-notice" style="background: #fff3cd; border-left: 4px solid #ffc107; padding: 12px 16px; margin-bottom: 20px; display: flex; align-items: center; justify-content: space-between; border-radius: 4px;">
            <div style="display: flex; align-items: center; gap: 12px;">
                <span style="font-size: 20px;">⚠️</span>
                <span style="font-size: 13px; color: #856404;">
                    <strong>Database update required</strong>
                    <?php if ($current_version !== '0'): ?>
                        (v<?php echo esc_html($current_version); ?> → v<?php echo esc_html($new_version); ?>)
                    <?php endif; ?>
                </span>
            </div>
            <button type="button"
                    class="button button-primary switchboard-update-db-btn"
                    data-module="<?php echo esc_attr($module_slug); ?>"
                    style="font-size: 13px;">
                Update Database
            </button>
        </div>
        <script>
        jQuery(document).ready(function($) {
            $('.switchboard-update-db-btn').on('click', function() {
                var btn = $(this);
                var module = btn.data('module');

                if (!confirm('Update database for this module? This is safe and reversible.')) {
                    return;
                }

                btn.prop('disabled', true).text('Updating...');

                $.post(ajaxurl, {
                    action: 'switchboard_update_module_db',
                    module: module,
                    nonce: '<?php echo esc_attr(wp_create_nonce('switchboard_db_update')); ?>'
                })
                .done(function(response) {
                    if (response.success) {
                        btn.text('✓ Updated');
                        setTimeout(function() {
                            $('.switchboard-db-update-notice').slideUp(300, function() {
                                $(this).remove();
                            });
                        }, 1500);
                    } else {
                        alert('Error: ' + (response.data ? response.data.message : 'Unknown error'));
                        btn.prop('disabled', false).text('Update Database');
                    }
                })
                .fail(function() {
                    alert('Update failed. Please refresh and try again.');
                    btn.prop('disabled', false).text('Update Database');
                });
            });
        });
        </script>
        <?php
    }
}
