<?php

namespace HulkPlugins\Woo\ProductConditionManager\Models;

use HulkPlugins\Woo\ProductConditionManager\Traits\SingletonTrait;

defined( 'ABSPATH' ) || exit;

class SettingsModel {
	use SingletonTrait;

	private array $attributes = [];
	private string $optionName = 'hulk_woo_pcm_settings';
	private array $defaultOptions = [
		'productCondition'            => '',
		'productConditionCustomGroup' => '',
		'productConditionCustom'      => '',
		'productConditionLabel'       => '',
		'showOnShopPage'              => false,
		'productConditionShopLabel'   => '',
		'productConditionCustomCss'   => '',
	];

	/**
	 * Deletes the settings from the database.
	 * @return bool
	 */
	public function deleteSettings(): bool {
		return delete_option( $this->optionName );
	}

	/**
	 * Updates the settings in the database.
	 *
	 * @param array $settings Associative array with the settings to update.
	 *
	 * @return bool True if the settings were updated, false otherwise.
	 */
	public function updateSettings( array $settings ): bool {
		$updated = update_option( $this->optionName, $this->sanitizeSettings( $settings ), false );
		if ( $updated ) {
			// Clear the cached attributes so the next getSettings fetches fresh data.
			$this->attributes = [];
		}
		return $updated;
	}

	/**
	 * Get all settings
	 * @return array
	 */
	public function getSettings(): array {
		if ( empty( $this->attributes ) ) {
			$options = get_option( $this->optionName, $this->defaultOptions );
			$this->attributes = array_merge( $this->defaultOptions, is_array( $options ) ? $options : [] );
		}
		return $this->attributes;
	}

	/**
	 * Sanitizes settings
	 *
	 * @param array $data
	 *
	 * @return array Sanitized associative array
	 */
	public function sanitizeSettings( array $data ): array {
		$sanitized = [];
		foreach ( $data as $key => $value ) {
			$key = sanitize_text_field( $key );
			// Skip invalid option
			if ( ! array_key_exists( $key, $this->defaultOptions ) ) {
				continue;
			}
			switch ( $key ) {
				case 'showOnShopPage':
					$sanitized[ $key ] = filter_var( $value, FILTER_VALIDATE_BOOLEAN );
					break;
				case 'productConditionCustomCss':
					$sanitized[ $key ] = wp_kses_post( $value );
					break;
				default:
					$sanitized[ $key ] = sanitize_text_field( $value );
					break;
			}
		}
		return $sanitized;
	}
}
