<?php
/**
 * SettingsStorageService class.
 *
 * Handles storage and retrieval of Firevert module settings using custom post type entries.
 *
 * @package Ilabs\Firevert\Core\Settings\Form
 */

declare( strict_types=1 );

namespace Ilabs\Firevert\Core\Settings\Form;

use WP_Post;

/**
 * Service for saving and retrieving module settings via CPT storage.
 */
class SettingsStorageService {

	/**
	 * Saves settings for a specific module to the CPT entry.
	 *
	 * @param string $module_slug Module slug.
	 * @param array  $data        Array of key => value pairs to store.
	 *
	 * @return void
	 */
	public function save_module_settings( string $module_slug, array $data ): void {
		$post = get_page_by_path( $module_slug, OBJECT, 'firevert_setting' );

		if ( ! $post instanceof WP_Post ) {
			$post_id = wp_insert_post(
				array(
					'post_title'  => ucfirst( $module_slug ) . ' Settings',
					'post_name'   => $module_slug,
					'post_status' => 'publish',
					'post_type'   => 'firevert_setting',
				)
			);
		} else {
			$post_id = $post->ID;
		}

		foreach ( $data as $key => $value ) {
			update_post_meta( $post_id, 'firevert_' . $module_slug . '_' . $key, $value );
		}
	}

	/**
	 * Retrieves a module setting value or returns the default.
	 *
	 * @param string     $module_slug    Module slug.
	 * @param string     $key            Setting key.
	 * @param mixed|null $default_value  Default value if key not found.
	 *
	 * @return mixed|null Stored setting value or default.
	 */
	public function get_module_setting( string $module_slug, string $key, $default_value = null ) {
		$post = get_page_by_path( $module_slug, OBJECT, 'firevert_setting' );

		if ( ! $post instanceof WP_Post ) {
			return $default_value;
		}

		$meta_key = 'firevert_' . $module_slug . '_' . $key;
		$value    = get_post_meta( $post->ID, $meta_key, true );

		return '' !== $value ? $value : $default_value;
	}
}
