<?php
defined( 'ABSPATH' ) || exit;

class Formulate_Pricing_Database {

	/**
	 * Migrate legacy plugin tables and options from earlier names.
	 */
	public static function maybe_migrate_legacy() {
		global $wpdb;

		$target_forms   = self::get_forms_table();
		$target_entries = self::get_entries_table();

		$legacy_form_tables = array(
			$wpdb->prefix . 'smart_pricing_forms',
			$wpdb->prefix . 'quotelix_forms',
		);

		foreach ( $legacy_form_tables as $legacy_table ) {
			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- One-time migration check.
			if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $legacy_table ) ) === $legacy_table
				&& $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $target_forms ) ) !== $target_forms ) {
				self::rename_table( $legacy_table, $target_forms );
				break;
			}
		}

		$legacy_entry_tables = array(
			$wpdb->prefix . 'smart_pricing_entries',
			$wpdb->prefix . 'quotelix_entries',
		);

		foreach ( $legacy_entry_tables as $legacy_table ) {
			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- One-time migration check.
			if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $legacy_table ) ) === $legacy_table
				&& $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $target_entries ) ) !== $target_entries ) {
				self::rename_table( $legacy_table, $target_entries );
				break;
			}
		}

		$legacy_product_options = array( 'smart_pricing_product_id', 'quotelix_product_id' );
		foreach ( $legacy_product_options as $legacy_option ) {
			$legacy_product_id = get_option( $legacy_option );
			if ( false !== $legacy_product_id && false === get_option( 'formulate_pricing_product_id', false ) ) {
				update_option( 'formulate_pricing_product_id', $legacy_product_id );
			}
			delete_option( $legacy_option );
		}

		delete_option( 'smart_pricing_db_version' );
		delete_option( 'quotelix_db_version' );
	}

	public static function install() {
		global $wpdb;

		self::maybe_migrate_legacy();

		$charset_collate = $wpdb->get_charset_collate();

		$forms_table   = $wpdb->prefix . 'formulate_pricing_forms';
		$entries_table = $wpdb->prefix . 'formulate_pricing_entries';

		$sql = "CREATE TABLE $forms_table (
			id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
			title varchar(255) NOT NULL DEFAULT '',
			slug varchar(255) NOT NULL DEFAULT '',
			form_config longtext NOT NULL,
			status varchar(20) NOT NULL DEFAULT 'published',
			created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
			updated_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
			PRIMARY KEY  (id),
			KEY status (status)
		) $charset_collate;

		CREATE TABLE $entries_table (
			id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
			form_id bigint(20) unsigned NOT NULL,
			entry_data longtext NOT NULL,
			status varchar(20) NOT NULL DEFAULT 'unread',
			payment_status varchar(20) NOT NULL DEFAULT '',
			ip_address varchar(45) DEFAULT NULL,
			user_agent text DEFAULT NULL,
			created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
			wc_order_id bigint(20) unsigned DEFAULT NULL,
			booking_post_id bigint(20) unsigned DEFAULT NULL,
			PRIMARY KEY  (id),
			KEY form_id (form_id),
			KEY status (status),
			KEY payment_status (payment_status),
			KEY wc_order_id (wc_order_id),
			KEY created_at (created_at)
		) $charset_collate;";

		require_once ABSPATH . 'wp-admin/includes/upgrade.php';
		dbDelta( $sql );

		update_option( 'formulate_pricing_db_version', FORMULATE_PRICING_DB_VERSION );
	}

	public static function get_forms_table() {
		global $wpdb;
		return $wpdb->prefix . 'formulate_pricing_forms';
	}

	public static function get_entries_table() {
		global $wpdb;
		return $wpdb->prefix . 'formulate_pricing_entries';
	}

	/**
	 * Rename a legacy plugin table to the current table name.
	 *
	 * @param string $from Legacy table name.
	 * @param string $to   Target table name.
	 */
	private static function rename_table( $from, $to ) {
		global $wpdb;

		if ( ! self::is_allowed_table_name( $from ) || ! self::is_allowed_table_name( $to ) ) {
			return;
		}

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- One-time migration; table names validated and passed via %i placeholders.
		$wpdb->query( $wpdb->prepare( 'RENAME TABLE %i TO %i', $from, $to ) );
	}

	/**
	 * Whether a table name is one this plugin may rename or drop.
	 *
	 * @param string $table Full table name including prefix.
	 * @return bool
	 */
	private static function is_allowed_table_name( $table ) {
		global $wpdb;

		$allowed = array(
			self::get_forms_table(),
			self::get_entries_table(),
			$wpdb->prefix . 'smart_pricing_forms',
			$wpdb->prefix . 'smart_pricing_entries',
			$wpdb->prefix . 'quotelix_forms',
			$wpdb->prefix . 'quotelix_entries',
		);

		return is_string( $table ) && in_array( $table, $allowed, true );
	}

	/**
	 * Drop a plugin table if it exists (uninstall / cleanup).
	 *
	 * @param string $table Full table name including prefix.
	 */
	public static function drop_table_if_exists( $table ) {
		global $wpdb;

		if ( ! self::is_allowed_table_name( $table ) ) {
			return;
		}

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Uninstall cleanup; table name validated and passed via %i placeholder.
		$wpdb->query( $wpdb->prepare( 'DROP TABLE IF EXISTS %i', $table ) );
	}
}
