<?php

namespace WPDesk\FakturyKSEF\AjaxResponse;

class AjaxResponse {

	// Internal status codes for JSON responses, used by JavaScript frontend
	public const STATUS_SUCCESS          = 'success';
	public const STATUS_ERROR            = 'error';
	public const STATUS_AWAITING         = 'awaiting';
	public const STATUS_ALREADY_ARCHIVED = 'already_archived';

	public function send_success( string $message, ?array $additional_data = null, string $internal_status = self::STATUS_SUCCESS ): void {
		$this->send( $internal_status, $message, $additional_data, true );
	}

	public function send_error( string $message, ?array $additional_data = null, string $internal_status = self::STATUS_ERROR ): void {
		$this->send( $internal_status, $message, $additional_data, false );
	}

	public function send_awaiting( string $message, ?array $additional_data = null ): void {
		$this->send_success( $message, $additional_data, self::STATUS_AWAITING );
	}

	public function send_already_archived( string $message, ?array $additional_data = null ): void {
		$this->send_success( $message, $additional_data, self::STATUS_ALREADY_ARCHIVED );
	}

	private function send( string $internal_status, string $message, ?array $additional_data, bool $is_wp_success ): void {
		$response_payload = [
			'status'  => $internal_status,
			'message' => $message,
		];

		if ( $additional_data !== null ) {
			$response_payload = array_merge( $response_payload, $additional_data );
		}

		if ( $is_wp_success ) {
			wp_send_json_success( $response_payload );
		} else {
			wp_send_json_error( $response_payload );
		}
	}
}
