<?php
/**
 * This file is part of the Wisewand WordPress plugin.
 *
 * @package Wisewand
 * @license GPL-2.0-or-later
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 */

/**
 * Migration 14: Add Global Settings Flag
 *
 * Adds use_global_settings column to wisewand_rss_feeds table.
 *
 * @package Wisewand
 * @since 1.6.37
 */

namespace Wisewand\Database\Migrations;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Migration_014_Add_Global_Settings_Flag {

	/**
	 * Run the migration.
	 *
	 * @return bool True on success, false on failure.
	 */
	public static function run() {
		global $wpdb;

		$table_name = $wpdb->prefix . 'wisewand_rss_feeds';

		// Check if table exists
		if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table_name ) ) !== $table_name ) {
			return true; // Table doesn't exist, nothing to do
		}

		// Check if column exists
		$column_exists = $wpdb->get_results( $wpdb->prepare( "SHOW COLUMNS FROM `{$table_name}` LIKE %s", 'use_global_settings' ) );

		if ( empty( $column_exists ) ) {
			// Add column
			$wpdb->query( "ALTER TABLE `{$table_name}` ADD COLUMN `use_global_settings` tinyint(1) DEFAULT 1 AFTER `wisewand_project_id`" );

			if ( $wpdb->last_error ) {
				if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
					error_log( 'Wisewand Migration 14 Error: ' . $wpdb->last_error );
				}
				return false;
			}

			// Set all existing feeds to use global settings (Retroactive default)
			$wpdb->query( 'START TRANSACTION' );

			$wpdb->query( "UPDATE `{$table_name}` SET `use_global_settings` = 1" );

			if ( $wpdb->last_error ) {
				$wpdb->query( 'ROLLBACK' );
				if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
					error_log( 'Wisewand Migration 014: ' . $wpdb->last_error );
				}
				return false;
			}

			$wpdb->query( 'COMMIT' );
		}

		return true;
	}
}
