<?php
/**
 * Actions
 *
 * @package   EDD\Pro\Invoices
 * @copyright Copyright (c) 2025, Sandhills Development, LLC
 * @license     https://opensource.org/licenses/gpl-2.0.php GNU Public License
 * @since     3.5.0
 */

/**
 * Generates, saves user details from the form, and displays the invoice to the user.
 *
 * @since 1.2
 */
function edd_invoices_generate_invoice() {
	// Check invoice generation was requested.
	if ( ! isset( $_REQUEST['edd-invoices-nonce'] ) ) {
		return;
	}

	if ( ! wp_verify_nonce( $_REQUEST['edd-invoices-nonce'], 'edd-invoices-generate-invoice' ) ) {
		return;
	}

	if ( ! edd_invoices_can_user_edit_invoice_data( get_current_user_id() ) ) {
		return;
	}

	$generator = new EDD\Pro\Invoices\Generator();

	$generator->validate_request();

	if ( ! $generator->is_valid_request() ) {
		wp_die( implode( '<br>', $generator->get_error_messages() ) );
	}

	// Save user details from POST.
	try {
		$generator->save_billing_information();
	} catch ( Exception $e ) {
		wp_die( esc_html( $e->getMessage() ) );
	}

	// Redirect to viewing the invoice.
	wp_safe_redirect( edd_invoices_get_invoice_url( $generator->order->ID, true ) );
	exit;
}
add_action( 'init', 'edd_invoices_generate_invoice' );

/**
 * Displays the invoice.
 *
 * @since 1.3
 */
function edd_invoices_display_invoice() {
	$generator = new EDD\Pro\Invoices\Generator();

	$generator->validate_request();

	if ( ! $generator->is_valid_request() ) {
		wp_die( implode( '<br>', $generator->get_error_messages() ) );
	}

	$order = $generator->order;

	// Generate HTML.
	set_query_var( 'order', $order );

	edd_get_template_part( 'invoice/invoice' );
	die();
}
add_action( 'edd_view_invoice', 'edd_invoices_display_invoice' );

/**
 * Adds an "Invoice" header to the order history table.
 *
 * @since 1.2
 */
function edd_invoices_order_history_header() {
	?>
	<th class="edd_invoice"><?php _e( 'Invoice', 'easy-digital-downloads' ); ?></th>
	<?php
}
add_action( 'edd_purchase_history_header_after', 'edd_invoices_order_history_header', 1 );

/**
 * Displays a "View Invoice" link for applicable orders.
 *
 * @param \EDD\Orders\Order|int $order_or_order_id In EDD 3.0, this is the order object; in 2.x, it is the payment ID.
 * @param array                 $purchase_data     The array of purchase data (not used in EDD 3.0).
 *
 * @since 1.2
 */
function edd_invoices_maybe_display_generate_invoice_link( $order_or_order_id, $purchase_data = array() ) {
	if ( $order_or_order_id instanceof \EDD\Orders\Order ) {
		$order_id = $order_or_order_id->id;
		remove_action( 'edd_purchase_history_row_end', 'edd_invoices_maybe_display_generate_invoice_link', 1, 2 );
	} else {
		$order_id = $order_or_order_id;
	}

	if ( ! edd_invoices_order_has_invoice( $order_id ) ) {
		?>
		<td class="edd_invoice"></td>
		<?php
		return;
	}
	?>
	<td class="edd_invoice">
		<a href="<?php echo esc_url( edd_invoices_get_invoice_url( $order_id ) ); ?>"><?php esc_html_e( 'View Invoice', 'easy-digital-downloads' ); ?></a>
	</td>
	<?php
}
add_action( 'edd_order_history_row_end', 'edd_invoices_maybe_display_generate_invoice_link', 1 );
add_action( 'edd_purchase_history_row_end', 'edd_invoices_maybe_display_generate_invoice_link', 1, 2 );

/**
 * Adds the invoice link to the order details in the order history block.
 *
 * @since 1.3.5
 * @param \EDD\Orders\Order $order The order object.
 * @return void
 */
function edd_invoices_show_invoice_link( $order ) {
	remove_action( 'edd_order_history_row_end', 'edd_invoices_maybe_display_generate_invoice_link', 1 );
	remove_action( 'edd_purchase_history_row_end', 'edd_invoices_maybe_display_generate_invoice_link', 1 );

	if ( ! edd_invoices_order_has_invoice( $order->id ) ) {
		return;
	}
	?>
	<div class="edd-invoices__order"><a href="<?php echo esc_url( edd_invoices_get_invoice_url( $order->id ) ); ?>"><?php esc_html_e( 'View Invoice', 'easy-digital-downloads' ); ?></a></div>
	<?php
}
add_action( 'edd_order_history_order_details', 'edd_invoices_show_invoice_link' );

/**
 * Adds a "View Invoice" link to the end of the purchase receipt table.
 *
 * @param \EDD\Orders\Order $order Order object.
 * @param array             $args             Receipt arguments.
 *
 * @since 1.2
 * @return void
 */
function edd_invoices_maybe_add_receipt_invoice_link( $order, $args ) {
	if ( ! edd_invoices_order_has_invoice( $order->id ) ) {
		return;
	}
	?>
	<tr>
		<td><strong><?php esc_html_e( 'Invoice:', 'easy-digital-downloads' ); ?></strong></td>
		<td>
			<a href="<?php echo esc_url( edd_invoices_get_invoice_url( $order->id ) ); ?>"><?php esc_html_e( 'View Invoice', 'easy-digital-downloads' ); ?></a>
		</td>
	</tr>
	<?php
}
add_action( 'edd_order_receipt_after', 'edd_invoices_maybe_add_receipt_invoice_link', 10, 2 );

/**
 * Adds the invoice link to the receipt block.
 *
 * @since 1.3.5
 * @param \EDD\Orders\Order $order The order object.
 * @return void
 */
function edd_invoices_show_invoice_on_block_receipt( $order ) {
	remove_action( 'edd_order_receipt_after', 'edd_invoices_maybe_add_receipt_invoice_link', 10, 2 );
	if ( ! edd_invoices_order_has_invoice( $order->id ) ) {
		return;
	}
	?>
	<div class="edd-blocks__row edd-blocks-receipt__row-item">
		<div class="edd-blocks__row-label"><?php esc_html_e( 'Invoice:', 'easy-digital-downloads' ); ?></div>
		<div class="edd-blocks__row-value">
			<a href="<?php echo esc_url( edd_invoices_get_invoice_url( $order->id ) ); ?>">
				<?php esc_html_e( 'View Invoice', 'easy-digital-downloads' ); ?>
			</a>
		</div>
	</div>
	<?php
}
add_action( 'edd_order_receipt_order_details', 'edd_invoices_show_invoice_on_block_receipt' );

/**
 * Generates an XML file for the invoice.
 *
 * @since 1.4.0
 * @param array $data The data for the invoice.
 */
function edd_invoices_generate_xml( $data ) {
	$order_id = ! empty( $data['id'] ) ? absint( $data['id'] ) : 0;
	if ( ! $order_id ) {
		$order_id = ! empty( $data['payment_id'] ) ? absint( $data['payment_id'] ) : 0;
	}

	if ( ! $order_id ) {
		return;
	}

	$order = edd_get_order( $order_id );
	if ( ! edd_can_view_receipt( $order ) ) {
		wp_die( esc_html__( 'You do not have permission to view this invoice.', 'easy-digital-downloads' ) );
	}
	$xml  = new EDD\Pro\Invoices\XML\Document( $order );
	$file = $xml->generate();
	if ( ! $file ) {
		return;
	}

	// Set headers.
	header( 'Content-Type: application/xml' );
	header( 'Content-Disposition: attachment; filename="' . basename( $file ) . '"' );
	header( 'Content-Length: ' . filesize( $file ) );

	$xml->download();

	die(); // Use this instead of edd_die() to prevent extra output from Query Monitor.
}
add_action( 'edd_invoices_generate_xml', 'edd_invoices_generate_xml' );

/**
 * If PDF Invoices is not active, redirects PDF Invoice links to the new invoice.
 *
 * @since 3.5.0
 * @return void
 */
add_action(
	'edd_generate_pdf_invoice',
	function () {
		if ( function_exists( 'edd_pdf_invoices' ) ) {
			return;
		}

		$order_id = filter_input( INPUT_GET, 'purchase_id', FILTER_SANITIZE_NUMBER_INT );
		if ( empty( $order_id ) ) {
			return;
		}

		$input_email = filter_input( INPUT_GET, 'email', FILTER_SANITIZE_EMAIL );
		$input_key   = ! empty( $_GET['purchase_key'] ) ? sanitize_text_field( $_GET['purchase_key'] ) : '';
		$key         = false;
		$order       = edd_get_order( intval( $order_id ) );
		if ( ! empty( $order->payment_key ) ) {
			$key = $order->payment_key;
		}
		foreach ( array( $input_email, $input_key, $key ) as $item_to_check ) {
			if ( empty( $item_to_check ) ) {
				return;
			}
		}

		if ( $input_email === $order->email && $input_key === $key ) {
			edd_redirect( edd_invoices_get_invoice_url( $order_id, true ) );
		}
		wp_die( esc_html__( 'You do not have permission to view this invoice.', 'easy-digital-downloads' ), esc_html__( 'Access Denied', 'easy-digital-downloads' ), array( 'response' => 403 ) );
	}
);
