<?php

namespace WPDesk\FakturyKSEF\Services;

use WPDesk\FakturyKSEF\Api\Repository\DocumentStateRepository;
use WPDesk\FakturyKSEF\Renderer\KSeFRenderer;
use WPDeskKSEFVendor\WPDesk\PluginBuilder\Plugin\Hookable;

class RegisterQRCodeShortcode implements Hookable {

	private const SHORTCODE = 'fiksef_document_qrcode';

	private KSeFRenderer $renderer;

	private QRCodeService $qr_code_service;

	private KSeFPreviewURLService $preview_url_service;

	private $plugin_access;

	private DocumentStateRepository $document_state_repository;

	public function __construct( KSeFRenderer $renderer, QRCodeService $qr_code_service, KSeFPreviewURLService $preview_url_service, DocumentStateRepository $document_state_repository, $plugin_access ) {
		$this->document_state_repository = $document_state_repository;
		$this->plugin_access             = $plugin_access;
		$this->preview_url_service       = $preview_url_service;
		$this->qr_code_service           = $qr_code_service;
		$this->renderer                  = $renderer;
	}

	public function hooks() {
		add_shortcode( self::SHORTCODE, [ $this, 'get_document_qr_code' ] );
	}

	private function get_invoice_document_object( int $document_id ) {
		$document_factory_creator = $this->plugin_access->get_document_factory()->get_document_creator( $document_id );
		if ( ! $document_factory_creator ) {
			return null;
		}
		return $document_factory_creator->get_document();
	}

	public function get_document_qr_code( $atts ) {
		$attributes = shortcode_atts(
			[
				'document_id' => false,
			],
			$atts
		);

		if ( ! is_numeric( $attributes['document_id'] ) ) {
			return '';
		}

		$document_id = (int) $attributes['document_id'];

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

		if ( ! $state->is_success() ) {
			return '';
		}

		$invoice_document = $this->get_invoice_document_object( $document_id );
		$issue_date       = date( 'd-m-Y', $invoice_document->get_date_of_issue() );
		$verification_key = $state->get_verification_key();
		if ( ! $verification_key ) {
			return '';
		}

		$preview_url = $this->preview_url_service->get_invoice_preview_url( $issue_date, $verification_key );
		$qr_code     = $this->qr_code_service->generate( $preview_url );

		return $this->renderer->render_document_qr_code( $qr_code, $state->get_ksef_number() );
	}
}
