<?php

namespace WPDesk\FakturyKSEF\Services;

use WPDesk\FakturyKSEF\Repository\PluginSettings;
use WPDeskKSEFVendor\WPDesk\Persistence\ElementNotExistsException;

class DocumentKSeFSettings {

	public const ZERO_RATE_TYPE = 'ksef_zero_rate_mapping';

	private PluginSettings $settings;

	public function __construct( PluginSettings $settings ) {
		$this->settings = $settings;
	}

	public function get( int $document_id, string $key, $default = null ) {

		if ( $default === null ) {
			try {
				$default = $this->get_from_plugin_settings( $key );
			} catch ( ElementNotExistsException $e ) { //phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch
				//do nothing and continue execution with default value
			}
		}

		$document_value = $this->get_from_document_meta( $document_id, $key );
		return empty( $document_value ) ? $default : $document_value;
	}

	private function get_from_plugin_settings( string $key ) {
		return $this->settings->get( $key );
	}

	private function get_from_document_meta( int $document_id, string $key ) {
		return get_post_meta( $document_id, '_' . $key, true );
	}

	public function set( int $post_id, string $key, $value ) {
		return update_post_meta( $post_id, '_' . $key, $value );
	}
}
