<?php
/**
 * Slug-scoped options — every key goes through Core::id(), so two factory
 * plugins can never collide, and uninstall can enumerate exactly what was
 * written. Autoload defaults to FALSE: factory plugins are admin tools and
 * must not weigh down every front-end request.
 *
 * @package Hakki\WooCore
 */

namespace ErenLabs\QuickVariableProducts\Vendor\Hakki\WooCore\Support;

use ErenLabs\QuickVariableProducts\Vendor\Hakki\WooCore\Core;

defined( 'ABSPATH' ) || exit;

final class Options {

	/** @var Core */
	private $core;

	public function __construct( Core $core ) {
		$this->core = $core;
	}

	/**
	 * @param string $key      Unprefixed key, e.g. 'settings'.
	 * @param mixed  $fallback Returned when the option is absent.
	 * @return mixed
	 */
	public function get( string $key, $fallback = false ) {
		return get_option( $this->core->id( $key ), $fallback );
	}

	/**
	 * @param string $key
	 * @param mixed  $value
	 * @param bool   $autoload Default false — see class docblock.
	 */
	public function set( string $key, $value, bool $autoload = false ): bool {
		return update_option( $this->core->id( $key ), $value, $autoload );
	}

	public function delete( string $key ): bool {
		return delete_option( $this->core->id( $key ) );
	}

	/**
	 * Delete every option whose key starts with this plugin's prefix. The one
	 * uninstall-time helper that keeps uninstall.php honest even when a feature
	 * forgot to register its key in a manual list.
	 *
	 * Safe ONLY because the factory scaffolder refuses slugs that extend an
	 * existing plugin's slug ("my-tool" vs "my-tool-pro"): without that guard,
	 * the LIKE pattern would reach a sibling's options.
	 *
	 * Runs a direct query on purpose: uninstall.php executes without the plugin
	 * bootstrapped, and options written over years can't be enumerated reliably
	 * any other way.
	 */
	public function delete_all(): int {
		global $wpdb;
		$like = $wpdb->esc_like( $this->core->prefix() ) . '%';
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- uninstall-scope cleanup by prefix.
		$deleted = (int) $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s", $like ) );
		wp_cache_flush();
		return $deleted;
	}
}
