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

namespace EDD\Pro\Invoices\Admin;

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit; // @codeCoverageIgnore

use EDD\EventManagement\SubscriberInterface;

/**
 * Bulk class.
 */
class Bulk implements SubscriberInterface {

	/**
	 * Constructor.
	 */
	public static function get_subscribed_events() {
		if ( ! current_user_can( 'edit_shop_payments' ) ) {
			return array();
		}

		return array(
			'admin_enqueue_scripts'     => 'enqueue_bulk_scripts',
			'edd_payments_page_bottom'  => array( 'add_download_button', 5 ),
			'wp_ajax_edd_invoices_bulk' => 'generate_invoices',
			'edd_export_init'           => 'register_export',
			'edd_export_form'           => 'export_form',
		);
	}

	/**
	 * Enqueues the scripts needed for bulk downloading invoices.
	 *
	 * @since 1.4.0
	 * @return void
	 */
	public function enqueue_bulk_scripts() {
		if ( ! edd_is_admin_page( 'payments', 'list-table' ) ) {
			return;
		}
		// Register PDF scripts so the edd-invoices-pdf dependency exists at enqueue time (WP 6.9.1+).
		edd_invoices_register_pdf_scripts();
		wp_enqueue_script( 'edd-invoices-admin', edd_get_assets_url( 'pro/js/invoice' ) . 'invoices-admin.js', array( 'edd-invoices-pdf' ), edd_admin_get_script_version(), true );
		wp_localize_script(
			'edd-invoices-admin',
			'EDDInvoices',
			array(
				'ajaxurl'  => edd_get_ajax_url(),
				'debug'    => edd_doing_script_debug(),
				'nonce'    => wp_create_nonce( 'edd-invoices-bulk' ),
				'text'     => __( 'Download Invoices', 'easy-digital-downloads' ),
				'running'  => __( 'Generating Invoices', 'easy-digital-downloads' ),
				'filename' => 'invoices.pdf',
			)
		);
	}

	/**
	 * Adds a button to bulk download invoices to the orders table.
	 *
	 * @since 1.4.0
	 * @return void
	 */
	public function add_download_button() {
		?>
		<span class="edd-hidden edd-invoices-bulk__actions">
			<button class="button button-secondary edd-invoices-bulk" disabled>
				<?php esc_html_e( 'Download Invoices', 'easy-digital-downloads' ); ?>
			</button>
			<?php
			$tooltip = new \EDD\HTML\Tooltip(
				array(
					'content' => __( 'Select orders to generate invoices for export. This will open a new window with the included invoices. Using the Print dialog, you can save the invoices as a PDF.', 'easy-digital-downloads' ),
				)
			);
			$tooltip->output();
			?>
		</span>
		<?php
	}

	/**
	 * Generates the invoices for the script to bundle and download.
	 *
	 * @since 1.4.0
	 * @return void
	 */
	public function generate_invoices() {
		if ( ! current_user_can( 'edit_shop_payments' ) ) {
			wp_send_json_error();
		}

		if ( ! wp_verify_nonce( $_POST['nonce'], 'edd-invoices-bulk' ) ) {
			wp_send_json_error();
		}

		if ( empty( $_POST['ids'] ) ) {
			wp_send_json_error();
		}

		ob_start();

		// Get the header template.
		edd_get_template_part( 'invoice/invoice-bulk-header' );

		$ids      = explode( ',', $_POST['ids'] );
		$ids      = array_map( 'absint', $ids );
		$invoices = array();

		foreach ( $ids as $id ) {
			$invoice_loaded = $this->get_invoice( $id );
			if ( ! $invoice_loaded ) {
				continue;
			}

			$invoices[] = $id;
		}

		if ( empty( $invoices ) ) {
			wp_send_json_error();
		}

		// Get the footer template.
		edd_get_template_part( 'invoice/invoice-bulk-footer' );

		// Get the combined document.
		$document = ob_get_clean();

		wp_send_json_success( $document );
	}

	/**
	 * Adds the form fields for the XML invoices export.
	 *
	 * @since 1.4.0
	 * @param string $exporter_id The exporter ID.
	 * @return void
	 */
	public function export_form( $exporter_id ) {
		if ( 'edd_invoice_xml' !== $exporter_id ) {
			return;
		}
		?>
		<fieldset class="edd-to-and-from-container">
			<legend class="screen-reader-text">
				<?php esc_html_e( 'Export Invoices Date', 'easy-digital-downloads' ); ?>
			</legend>
			<label for="edd_export_invoices_month" class="screen-reader-text"><?php esc_html_e( 'Select start month', 'easy-digital-downloads' ); ?></label>
			<?php echo EDD()->html->month_dropdown( 'month', 0, 'edd_export_invoice_xml', true ); ?>
			<label for="edd_export_invoices_year" class="screen-reader-text"><?php esc_html_e( 'Select start year', 'easy-digital-downloads' ); ?></label>
			<?php echo EDD()->html->year_dropdown( 'year', 0, 5, 0, 'edd_export_invoice_xml' ); ?>
		</fieldset>
		<label for="edd_export_invoices_status" class="screen-reader-text"><?php esc_html_e( 'Select Status', 'easy-digital-downloads' ); ?></label>
		<?php
		$statuses = array();
		foreach ( edd_invoices_get_invoiceable_order_statuses() as $status ) {
			if ( 'publish' === $status ) {
				continue;
			}
			$statuses[ $status ] = edd_get_payment_status_label( $status );
		}
		$select = new \EDD\HTML\Select(
			array(
				'id'               => 'edd_export_invoice_xml_status',
				'name'             => 'status',
				'show_option_all'  => __( 'All Statuses', 'easy-digital-downloads' ),
				'show_option_none' => false,
				'selected'         => false,
				'options'          => $statuses,
			)
		);
		$select->output();
	}

	/**
	 * Registers the XML invoices export.
	 *
	 * @since 3.5.0
	 * @param \EDD\Admin\Exports\Registry $registry The registry.
	 * @return void
	 */
	public function register_export( \EDD\Admin\Exports\Registry $registry ) {
		$registry->register_exporter(
			'edd_invoice_xml',
			array(
				'label'       => __( 'Electronic Invoices', 'easy-digital-downloads' ),
				'description' => __( 'Download a .zip file of electronic invoices for a specific month/year.', 'easy-digital-downloads' ),
				'class'       => Export::class,
				'button'      => __( 'Download eInvoices', 'easy-digital-downloads' ),
			)
		);
	}

	/**
	 * Adds the invoices export form to the reports screen.
	 *
	 * @return void
	 */
	public function xml_export() {
		?>
		<div class="postbox edd-export-invoices">
			<h2 class="hndle"><?php esc_html_e( 'Export Electronic Invoices', 'easy-digital-downloads' ); ?></h3>
			<div class="inside">
				<p><?php esc_html_e( 'Download a .zip file of electronic invoices for a specific month/year.', 'easy-digital-downloads' ); ?></p>
				<form id="edd-export-invoice-xml" class="edd-export-form edd-import-export-form">
					<?php
					$this->export_form( 'edd_invoice_xml' );
					wp_nonce_field( 'edd_ajax_export', 'edd_ajax_export' );
					?>
					<input type="hidden" name="edd-export-class" value="EDD\Invoices\Admin\Export">
					<button type="submit" class="button button-secondary"><?php esc_html_e( 'Download eInvoices', 'easy-digital-downloads' ); ?></button>
				</form>
			</div>
		</div>
		<?php
	}

	/**
	 * Gets the invoice HTML.
	 *
	 * @since 1.4.0
	 * @param int $id The order ID.
	 * @return bool Whether the invoice was loaded.
	 */
	private function get_invoice( $id ) {
		$order = edd_get_order( $id );
		if ( ! in_array( $order->status, edd_invoices_get_invoiceable_order_statuses(), true ) ) {
			return false;
		}

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

		edd_get_template_part( 'invoice/invoice-bulk' );

		set_query_var( 'order', null );

		return true;
	}
}
