<?php
/**
 * Invoices. Invoice post columns.
 *
 * @package WPDesk\Library\FlexibleInvoicesCore
 */

namespace WPDesk\FakturyKSEF\Dashboard;

use WPDesk\FakturyKSEF\Api\APIClient;
use WPDesk\FakturyKSEF\Api\Repository\DocumentStateRepository;
use WPDesk\FakturyKSEF\Renderer\KSeFRenderer;
use WPDesk\FakturyKSEF\Repository\PluginSettings;
use WPDesk\FakturyKSEF\Services\DocumentKSeFSettings;
use WPDesk\FakturyKSEF\Services\DownloadXMLUrlGenerator;
use WPDeskKSEFVendor\WPDesk\PluginBuilder\Plugin\Hookable;
use WPDesk\CoreAlias\DocumentFactory;
use WPDesk\CoreAlias\ExternalPluginsAccess;

/**
 * Add custom columns in documents listing.
 *
 * @package WPDesk\Library\FlexibleInvoicesCore\Integration
 */
class MetaBox implements Hookable {

	private KSeFRenderer $renderer;

	private DocumentStateRepository $document_state_repository;

	private $plugins_access;

	private APIClient $api;

	private DownloadXMLUrlGenerator $download_xml_url_generator;

	private DocumentKSeFSettings $document_ksef_settings;

	public function __construct( KSeFRenderer $renderer, DocumentStateRepository $document_state_repository, $plugins_access, APIClient $api, DownloadXMLUrlGenerator $download_xml_url_generator, DocumentKSeFSettings $document_ksef_settings ) {
		$this->document_ksef_settings     = $document_ksef_settings;
		$this->download_xml_url_generator = $download_xml_url_generator;
		$this->plugins_access             = $plugins_access;
		$this->document_state_repository  = $document_state_repository;
		$this->renderer                   = $renderer;
		$this->api                        = $api;
	}

	public function hooks() {
		add_action( 'add_meta_boxes', [ $this, 'add_meta_box' ] );
		add_action( 'save_post_inspire_invoice', [ $this, 'save_meta_box_data' ] );
	}

	public function save_meta_box_data( $post_id ) {

		if ( empty( $_POST['ksef_params'] ) || ! is_array( $_POST['ksef_params'] ) ) {
			return;
		}

		if ( ! wp_verify_nonce( $_POST['fiksef_meta_box_nonce'] ?? '', 'fiksef_save_meta_box_data' ) ) { //phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
			return;
		}

		foreach ( $_POST['ksef_params'] as $key => $value ) { //phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
			$field_value = sanitize_text_field( $value );
			$this->document_ksef_settings->set( $post_id, $key, $field_value );
		}
	}

	public function add_meta_box() {

		$post_id = (int) sanitize_text_field( wp_unslash( $_GET['post'] ?? 0 ) ); //phpcs:ignore WordPress.Security.NonceVerification.Recommended

		$post_type = get_post_type( $post_id );

		if ( $post_type !== 'inspire_invoice' ) {
			return;
		}

		$document_factory_creator = $this->plugins_access->get_document_factory()->get_document_creator( $post_id );
		$document                 = $document_factory_creator->get_document();

		if ( ! in_array( $document->get_type(), [ 'invoice', 'correction' ], true ) ) {
			return;
		}

		add_meta_box(
			'wpdesk_ksef',
			__( 'KSeF', 'ksef-for-flexible-invoices' ),
			[ $this, 'render_meta_box_content' ],
			[ 'inspire_invoice' ],
			'side',
		);
	}

	public function render_meta_box_content( $post ) {
		$id = $post->ID;

		$state = $this->document_state_repository->get( $id );

		if ( $state->is_success() ) {
			$this->renderer->output_document_sent_to_ksef( $state->get_ksef_number() );
			$shortcode = sprintf( '[fiksef_document_qrcode document_id="%d"]', $id );
			echo do_shortcode( $shortcode );
			return;
		}

		$this->output_ksef_params_form( (int) $id );

		if ( $state->has_errors() ) {
			$this->renderer->output_cannot_send_document( $state->get_error_messages() );
			$this->renderer->output_metabox_action_buttons( $post->ID, $this->download_xml_url_generator->generate_by_id( (int) $id ) );
			return;
		}

		if ( ! $this->api->authenticate() ) {
			$this->renderer->output_unauthorized_connection_document_notice();
			return;
		}

		$this->renderer->output_document_ready_to_send();
		$this->renderer->output_metabox_action_buttons( $id, $this->download_xml_url_generator->generate_by_id( (int) $id ) );
	}

	private function output_ksef_params_form( int $document_id ) {
		$exemption      = (string) $this->document_ksef_settings->get( $document_id, PluginSettings::EXEMPTION );
		$zero_rate_type = (string) $this->document_ksef_settings->get( $document_id, DocumentKSeFSettings::ZERO_RATE_TYPE, 'auto' );
		$np_rate_type   = (string) $this->document_ksef_settings->get( $document_id, PluginSettings::DEFAULT_NP_RATE_TYPE );

		$this->renderer->output_metabox_form( $exemption, $zero_rate_type, $np_rate_type );
	}
}
