<?php

namespace Limb_Chatbot\Includes\Services;

use Exception;
use Limb_Chatbot\Includes\Traits\SingletonTrait;
use wpdb;

/**
 * Service responsible for deleting all plugin data from the database.
 *
 * Handles deletion of:
 * - All plugin-related tables
 * - All wp_options entries starting with the lbaic_ prefix
 *
 * @since 1.0.1
 */
class Data_Deletion_Service {

	use SingletonTrait;

	/**
	 * WordPress database global instance.
	 *
	 * @var wpdb
	 * @since 1.0.1
	 */
	protected $wpdb;

	/**
	 * Constructor is protected to enforce singleton pattern.
	 *
	 * @since 1.0.1
	 */
	protected function __construct() {
		$this->wpdb = \Limb_Chatbot\Includes\Database_Strategies\WPDB::instance();
	}

	/**
	 * Deletes all plugin data including tables and options.
	 *
	 * @return bool True if deletion was successful, false otherwise.
	 * @throws Exception
	 * @since 1.0.1
	 */
	public function delete_all_data(): bool {
		try {
			$this->wpdb->start_transaction();

			// Delete all plugin tables
			$this->delete_tables();

			// Delete all plugin options
			$this->delete_options();
			/**
			 * Fire action after plugin data deletion.
			 *
			 * @since 1.0.1
			 */
			do_action( 'lbaic_plugin_data_deleted' );

			$this->wpdb->commit_transaction();

			return true;
		} catch ( Exception $e ) {
			$this->wpdb->rollback_transaction();
			// Log error if needed
			Helper::log( 'Error deleting plugin data: ' . $e->getMessage() );
			throw $e;
		}
	}

	/**
	 * Deletes all plugin-related database tables.
	 *
	 * @return void
	 * @since 1.0.1
	 */
	protected function delete_tables(): void {
		$tables = Install::get_tables();

		foreach ( $tables as $table ) {
			$this->wpdb->get_wpdb()->query( "DROP TABLE IF EXISTS {$table}" );
		}
	}

	/**
	 * Deletes all wp_options entries starting with the lbaic_ prefix.
	 *
	 * @return void
	 * @since 1.0.1
	 */
	protected function delete_options(): void {
		$option_names = $this->wpdb->get_wpdb()->get_col(
			"SELECT option_name FROM {$this->wpdb->get_wpdb()->options} WHERE option_name LIKE 'lbaic.%'"
		);

		foreach ( $option_names as $option ) {
			delete_option( $option );
		}
	}
}