<?php
/**
 * Invoice download controller.
 *
 * @since 3.0.0
 */

declare( strict_types=1 );
namespace FeData\FastEvents\RestAPI\Public\Download;

defined( 'ABSPATH' ) || exit;

use FeData\FastEvents\Storage\PluginSettings;
use FeData\FastEvents\Utilities\JsonUtil;
use FeData\FastEvents\Utilities\PluginUtil;
use FeData\FastEvents\Utilities\WebhookUtil;
use JetBrains\PhpStorm\NoReturn;
use WP_REST_Request;
use WP_REST_Server;

/**
 * Downloads class.
 */
class InvoiceDownloadController {


	/**
	 * Invoice download constructor.
	 *
	 * @since 3.0.0
	 *
	 * @param PluginSettings $settings Plugin settings.
	 */
	public function __construct( private readonly PluginSettings $settings ) {}


	/**
	 * Register the routes for the download of the invoice.
	 *
	 * @since 1.0
	 * @since 2.1.0 Added download tickets via qrcode ids (1 or more)
	 */
	public function register_routes(): void {

		// Download invoice.
		register_rest_route(
			'fast-events',
			'/v1/invoice/(?P<uid>[\w]{40})',
			array(
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => array( $this, 'fast_events_download_invoice' ),
				'permission_callback' => '__return_true',
			)
		);
	}



	/**
	 * Generate and download invoice
	 *
	 * @since 1.0
	 * @since 2.3.0 Use fast_events_json_encode.
	 *
	 * @param WP_REST_Request $data Request instance.
	 */
	#[NoReturn] public function fast_events_download_invoice( WP_REST_Request $data ): void {
		global $wpdb;

		// Get the order.
		$event_table = $wpdb->prefix . 'fe_events';
		$order_table = $wpdb->prefix . 'fe_event_orders';
		// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		$result = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT $order_table.id, $order_table.event_id, $order_table.input_fields, $order_table.created_at, " .
				"$order_table.event_date, $order_table.name, $order_table.email, $event_table.event_name, " .
				"$event_table.invoice_needed, $event_table.webhooks_needed, $event_table.pdf_info, " .
				"$event_table.event_date_format " .
				"FROM $order_table " .
				"INNER JOIN $event_table ON $event_table.id = $order_table.event_id " .
				"WHERE $order_table.uid = %s",
				$data['uid']
			)
		);
		// phpcs:enable

		if ( empty( $result ) ) {
			http_response_code( 404 );
			die();
		}

		// Does the event support tickets?
		if ( 0 === (int) $result->invoice_needed ) {
			http_response_code( 404 );
			die();
		}

		// Is there an action registered to print an invoice? If not use the default PDF.
		if ( has_action( 'fast_events_invoice' ) ) {
			$attr = json_decode( JsonUtil::fast_events_json_encode( $result ), true );
			unset( $attr['invoice_needed'], $attr['webhooks_needed'], $attr['input_fields'], $attr['pdf_info'] );
			$inp             = json_decode( $result->input_fields, true );
			$attr['tickets'] = $inp['tickets'] ?? array();
			$attr['invoice'] = $inp['invoice'] ?? array();
			unset( $attr['invoice']['locked'] );

			/**
			 * Action to print invoice.
			 *
			 * @since 2.1.0
			 *
			 * @param string $id                 The unique order id.
			 * @param string $event_id           The event_id.
			 * @param array  $tickets            Array of tickets.
			 * @param array  $invoice            Invoice data.
			 * @param string $name               The name of the orderer.
			 * @param string $email              The emailaddress of the orderer.
			 * @param string $created_at         The datetime of the order.
			 * @param string $event_name         The name of the event
			 * @param string $event_date         The date of the event
			 * @param string $event_date_format  The date format of the event (See docs)
			 */
			do_action( 'fast_events_invoice', $attr );
		} else {

			// Prepare the PDF.
			$pdf = new EventInvoice( $this->settings->sender_name(), $this->settings->currency_symbol(), $result->pdf_info );

			// Create the invoice pages.
			$pdf->print_invoice( $result );

			// Send the PDF to the client.
			$pdf->send_pdf();
		}

		// Are webhooks activated for this event?
		if ( 1 === (int) $result->webhooks_needed ) {
			WebhookUtil::create_webhook( 'invoice.downloaded', array( (int) $result->id, current_time( 'mysql' ), PluginUtil::get_ip() ) );
		}

		die();
	}
}
