<?php
/**
 * @package Splitit_WooCommerce_Plugin
 */

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

require_once dirname( __DIR__ ) . '/classes/class-splitit-flexfields-payment-plugin-log.php';

function splitit_flexfields_payment_plugin_remove_user_id_fk_from_splitit_log_table() {
	global $wpdb;

	$log_data = array(
		'user_id' => null,
		'method'  => __( 'splitit_flexfields_payment_plugin_remove_user_id_fk_from_splitit_log_table() Splitit', 'splitit-installment-payments' ),
	);

	if ( is_multisite() ) {
		$sites = get_sites();
		foreach ( $sites as $site ) {
			switch_to_blog( $site->blog_id );

			$table = $wpdb->prefix . 'splitit_log';

			SplitIt_FlexFields_Payment_Plugin_Log::save_log_info( $log_data, 'splitit_flexfields_payment_plugin_remove_user_id_fk_from_splitit_log_table() - Remove_user_id_fk_from: ' . $table, 'info' );

			try {
				$table_exists = $wpdb->get_var(
					$wpdb->prepare(
						'SHOW TABLES LIKE %s',
						$table
					)
				);

				if ( $table_exists !== $table ) {
					continue;
				}

				$fks = $wpdb->get_results(
					$wpdb->prepare(
						"
                SELECT CONSTRAINT_NAME
                FROM information_schema.KEY_COLUMN_USAGE
                WHERE TABLE_SCHEMA = DATABASE()
                  AND TABLE_NAME = %s
                  AND COLUMN_NAME = 'user_id'
                  AND REFERENCED_TABLE_NAME IS NOT NULL
                ",
						$table
					)
				);

				$table_name = esc_sql( $table );

				if ( empty( $fks ) ) {
					SplitIt_FlexFields_Payment_Plugin_Log::save_log_info(
						$log_data,
						sprintf(
							'Multisite FK user_id does not exist in table "%s"',
							$table_name
						),
						'info'
					);
					continue;
				}

				foreach ( $fks as $fk ) {
					if ( empty( $fk->CONSTRAINT_NAME ) ) {
						continue;
					}

					$constraint = esc_sql( $fk->CONSTRAINT_NAME );

					$result = $wpdb->query(
						"ALTER TABLE {$table_name} DROP FOREIGN KEY {$constraint}" // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table and constraint names cannot be prepared.
					);

					if ( false === $result ) {
						SplitIt_FlexFields_Payment_Plugin_Log::save_log_info(
							$log_data,
							'Multisite Failed to drop FK ' . $constraint . ': ' . $wpdb->last_error,
							'error'
						);
					} else {
						SplitIt_FlexFields_Payment_Plugin_Log::save_log_info(
							$log_data,
							sprintf(
								'Multisite FK "%s" successfully removed from table "%s"%s',
								$constraint,
								$table_name,
								' (blog_id: ' . get_current_blog_id() . ')'
							),
							'info'
						);
					}
				}
			} catch ( \Throwable $e ) {
				SplitIt_FlexFields_Payment_Plugin_Log::save_log_info(
					$log_data,
					'Multisite user_id fk from splitit_log removal error: ' . $e->getMessage(),
					'error'
				);
			} finally {
				restore_current_blog();
			}
		}
	} else {
		$table = $wpdb->prefix . 'splitit_log';

		SplitIt_FlexFields_Payment_Plugin_Log::save_log_info( $log_data, 'splitit_flexfields_payment_plugin_remove_user_id_fk_from_splitit_log_table() - Remove_user_id_fk_from: ' . $table, 'info' );

		try {
			$table_exists = $wpdb->get_var(
				$wpdb->prepare(
					'SHOW TABLES LIKE %s',
					$table
				)
			);

			if ( $table_exists !== $table ) {
				return;
			}

			$fks = $wpdb->get_results(
				$wpdb->prepare(
					"
                SELECT CONSTRAINT_NAME
                FROM information_schema.KEY_COLUMN_USAGE
                WHERE TABLE_SCHEMA = DATABASE()
                  AND TABLE_NAME = %s
                  AND COLUMN_NAME = 'user_id'
                  AND REFERENCED_TABLE_NAME IS NOT NULL
                ",
					$table
				)
			);

			$table_name = esc_sql( $table );

			if ( empty( $fks ) ) {
				SplitIt_FlexFields_Payment_Plugin_Log::save_log_info(
					$log_data,
					sprintf(
						'FK user_id does not exist in table "%s"',
						$table_name
					),
					'info'
				);
				return;
			}

			foreach ( $fks as $fk ) {
				if ( empty( $fk->CONSTRAINT_NAME ) ) {
					continue;
				}

				$constraint = esc_sql( $fk->CONSTRAINT_NAME );

				$result = $wpdb->query(
					"ALTER TABLE {$table_name} DROP FOREIGN KEY {$constraint}" // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table and constraint names cannot be prepared.
				);

				if ( false === $result ) {
					SplitIt_FlexFields_Payment_Plugin_Log::save_log_info(
						$log_data,
						'Failed to drop FK ' . $constraint . ': ' . $wpdb->last_error,
						'error'
					);
				} else {
					SplitIt_FlexFields_Payment_Plugin_Log::save_log_info(
						$log_data,
						sprintf(
							'FK "%s" successfully removed from table "%s"',
							$constraint,
							$table_name
						),
						'info'
					);
				}
			}
		} catch ( \Throwable $e ) {
			SplitIt_FlexFields_Payment_Plugin_Log::save_log_info(
				$log_data,
				'user_id fk from splitit_log removal error: ' . $e->getMessage(),
				'error'
			);
		}
	}
}
