<?php

namespace WPDesk\FakturyKSEF\Dashboard;

use WPDesk\FakturyKSEF\Api\APIClient;
use WPDesk\FakturyKSEF\Api\Repository\DocumentStateRepository;
use WPDesk\FakturyKSEF\Renderer\KSeFRenderer;
use WPDeskKSEFVendor\WPDesk\PluginBuilder\Plugin\Hookable;
use WPDesk\CoreAlias\Document;
use WPDesk\CoreAlias\DocumentFactory;

class Columns implements Hookable {

	private const KSEF_ID = 'ksef_id';

	private KSeFRenderer $renderer;

	private DocumentStateRepository $document_state_repository;

	private APIClient $api;

	private ?bool $authenticated = null;

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

	public function hooks() {
		add_filter( 'fi/core/lists/columns/header', [ $this, 'add_custom_columns_filter' ] );
		add_action( 'fi/core/lists/columns/body', [ $this, 'custom_columns_body_action' ], 10, 2 );
	}

	public function add_custom_columns_filter( $columns ) {
		$new_columns = [];
		foreach ( $columns as $column_id => $column_name ) {
			if ( $column_id === 'client' ) {
				$new_columns[ self::KSEF_ID ] = esc_html__( 'KSEF ID', 'ksef-for-flexible-invoices' );
			}
			$new_columns[ $column_id ] = $column_name;
		}

		return $new_columns;
	}


	public function custom_columns_body_action( $column_name, $document ) {

		if ( $column_name !== self::KSEF_ID ) {
			return;
		}

		$state = $this->document_state_repository->get( $document->get_id() );

		if ( $state->is_success() ) {
			$this->renderer->output_document_sent_to_ksef( $state->get_ksef_number() );
			return;
		}

		if ( $state->has_errors() ) {
			$this->renderer->output_cannot_send_document();
			return;
		}

		if ( $this->authenticated === null ) {
			$this->authenticated = $this->api->authenticate();
		}

		if ( $this->authenticated === false ) {
			$this->renderer->output_unauthorized_connection_document_notice();
			return;
		}

		$this->renderer->output_document_ready_to_send();
	}
}
