<?php
/**
 * Receipt Downloader
 *
 * Handles secure receipt downloads.
 *
 * @package DonorCore\Receipts
 */

namespace DonorCore\Receipts;

defined( 'ABSPATH' ) || exit;

/**
 * Receipt Downloader Class
 */
class Receipt_Downloader {

	/**
	 * Initialize hooks.
	 */
	public function init() {
		add_action( 'wp_ajax_donorcore_download_receipt', array( $this, 'download' ) );
		add_action( 'wp_ajax_nopriv_donorcore_download_receipt', array( $this, 'download' ) );
	}

	/**
	 * Handle receipt download.
	 */
	public function download() {
		$order_id = isset( $_GET['order_id'] ) ? absint( wp_unslash( $_GET['order_id'] ) ) : 0;

		if ( ! $order_id ) {
			wp_die( esc_html__( 'Invalid order ID.', 'donorcore-donations' ) );
		}

		// Verify nonce.
		if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'download_receipt_' . $order_id ) ) {
			wp_die( esc_html__( 'Security check failed.', 'donorcore-donations' ) );
		}

		$order = wc_get_order( $order_id );

		if ( ! $order ) {
			wp_die( esc_html__( 'Order not found.', 'donorcore-donations' ) );
		}

		// Check permissions.
		if ( ! $this->can_download( $order ) ) {
			wp_die( esc_html__( 'You do not have permission to download this receipt.', 'donorcore-donations' ) );
		}

		$file_path = $order->get_meta( '_donorcore_receipt_path', true );

		if ( ! $file_path || ! file_exists( $file_path ) ) {
			wp_die( esc_html__( 'Receipt file not found.', 'donorcore-donations' ) );
		}

		// Stream file.
		$this->stream_file( $file_path, 'receipt-' . $order_id . '.pdf' );
	}

	/**
	 * Check if user can download receipt.
	 *
	 * @param \WC_Order $order Order object.
	 * @return bool
	 */
	private function can_download( $order ) {
		// Admins can download any receipt.
		if ( current_user_can( 'manage_options' ) ) {
			return true;
		}

		// Order owner can download.
		if ( is_user_logged_in() && get_current_user_id() === $order->get_customer_id() ) {
			return true;
		}

		// Guest with valid nonce (already verified above) can download.
		return true;
	}

	/**
	 * Stream file download.
	 *
	 * @param string $file_path File path.
	 * @param string $filename  Download filename.
	 */
	private function stream_file( $file_path, $filename ) {
		// Clear output buffers.
		while ( ob_get_level() ) {
			ob_end_clean();
		}

		// Set headers.
		header( 'Content-Type: application/pdf' );
		header( 'Content-Disposition: attachment; filename="' . $filename . '"' );
		header( 'Content-Length: ' . filesize( $file_path ) );
		header( 'Cache-Control: private, max-age=0, must-revalidate' );
		header( 'Pragma: public' );

		// Stream file.
		// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_readfile -- readfile is acceptable for one-time file downloads with proper headers
		readfile( $file_path );
		exit;
	}
}
