<?php
/**
 * Almacén de opciones (reemplaza wp_options).
 */

final class JB_Options {
	private static $cache = array();
	private static $table = '';

	public static function init( $table_name ) {
		self::$table = $table_name;
	}

	public static function get( $option, $default = false ) {
		if ( array_key_exists( $option, self::$cache ) ) {
			return self::$cache[ $option ];
		}
		global $wpdb;
		$row = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT option_value FROM `{$wpdb->prefix}options` WHERE option_name = %s LIMIT 1",
				$option
			)
		);
		if ( ! $row ) {
			return $default;
		}
		$value = maybe_unserialize( $row->option_value );
		self::$cache[ $option ] = $value;
		return $value;
	}

	public static function update( $option, $value, $autoload = true ) {
		global $wpdb;
		$exists = (bool) $wpdb->get_var(
			$wpdb->prepare(
				"SELECT option_id FROM `{$wpdb->prefix}options` WHERE option_name = %s LIMIT 1",
				$option
			)
		);
		$data = array(
			'option_value' => maybe_serialize( $value ),
			'autoload'     => $autoload ? 'yes' : 'no',
		);
		if ( $exists ) {
			$wpdb->update( "{$wpdb->prefix}options", $data, array( 'option_name' => $option ) );
		} else {
			$data['option_name'] = $option;
			$wpdb->insert( "{$wpdb->prefix}options", $data );
		}
		self::$cache[ $option ] = $value;
		return true;
	}

	public static function add( $option, $value, $autoload = true ) {
		if ( false !== self::get( $option, false ) ) {
			return false;
		}
		return self::update( $option, $value, $autoload );
	}

	public static function delete( $option ) {
		global $wpdb;
		unset( self::$cache[ $option ] );
		return (bool) $wpdb->delete( "{$wpdb->prefix}options", array( 'option_name' => $option ) );
	}
}

function get_option( $option, $default = false ) {
	return JB_Options::get( $option, $default );
}

function update_option( $option, $value, $autoload = true ) {
	return JB_Options::update( $option, $value, $autoload );
}

function add_option( $option, $value, $deprecated = '', $autoload = true ) {
	return JB_Options::add( $option, $value, $autoload );
}

function delete_option( $option ) {
	return JB_Options::delete( $option );
}

function maybe_serialize( $data ) {
	if ( is_array( $data ) || is_object( $data ) ) {
		return serialize( $data );
	}
	return (string) $data;
}

function maybe_unserialize( $data ) {
	if ( ! is_string( $data ) ) {
		return $data;
	}
	$unserialized = @unserialize( $data );
	if ( false !== $unserialized || 'b:0;' === $data ) {
		return $unserialized;
	}
	return $data;
}
