<?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: Fix Global Settings Flag
 *
 * Reverts the "force global" decision for existing feeds.
 * Sets use_global_settings = 0 for all current feeds so they retain their custom configuration.
 * New feeds will still default to 1 (Global) via the schema default.
 *
 * @package Wisewand
 */

namespace Wisewand\Database\Migrations;

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

class Migration_015_Restore_Custom_Settings {

	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;
		}

		// Update all existing feeds to use Custom Settings (0)
		// This ensures that their existing configuration (Frequency, Author, etc.) is respected
		// and not overwritten by the new Global Defaults.
		$wpdb->query( 'START TRANSACTION' );

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

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

		$wpdb->query( 'COMMIT' );

		return true;
	}
}
