<?php
/**
 * Bulk Print Controller
 *
 * Handles REST API requests for bulk document printing.
 *
 * @package    NovaPostForWoocommerce
 * @subpackage Api\Controllers
 */

namespace NovaPostForWoocommerce\Api\Controllers;

use NovaPostForWoocommerce\Exceptions\ShipmentException;
use NovaPostForWoocommerce\Models\Traits\TrackEvent;
use NovaPostForWoocommerce\Services\BulkPrintService;
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;

/**
 * Bulk Print Controller
 *
 * Handles bulk printing of shipment documents.
 */
class BulkPrintController {

    use TrackEvent;

    /**
     * Bulk print service instance.
     *
     * @var BulkPrintService
     */
    private $bulk_print_service;

    /**
     * Constructor.
     */
    public function __construct() {
        $this->bulk_print_service = new BulkPrintService();
    }

    /**
     * Print documents for multiple orders.
     *
     * @param WP_REST_Request $request The REST request object.
     * @return WP_REST_Response|WP_Error Response with merged PDF or error.
     */
    public function print_bulk_documents( WP_REST_Request $request ) {
        $order_ids = $request->get_param( 'orderIds' );
        $type      = $request->get_param( 'type' );

        $print_size_type = ( 'marking' === $type ) ? 'size_100_100' : 'size_A4';

        try {
            // Print documents.
            $result  = $this->bulk_print_service->print_bulk_documents( $order_ids, $type );
            $numbers = $result['numbers'] ?? array();

            $this->track_bulk_prints_created(
                array(
                    'numbers'       => $numbers,
                    'type'          => $type,
                    'printSizeType' => $print_size_type,
                )
            );

            return new WP_REST_Response(
                array(
                    'success' => true,
                    'data'    => $result['pdf_data'],
                    'summary' => $result['summary'],
                ),
                200
            );

        } catch ( ShipmentException $e ) {
            $this->track_bulk_prints_failed(
                array(
                    'error_message' => $e->getMessage(),
                    'numbers'       => array(),
                    'type'          => $type,
                    'printSizeType' => $print_size_type,
                )
            );

            return new WP_Error( 'shipment_exception', $e->getMessage(), $e->get_data() );
        } catch ( \Exception $e ) {
            return new WP_Error(
                'unexpected_error',
                sprintf(
                    /* translators: %s: error message */
                    __( 'An unexpected error occurred: %s', 'nova-post-for-woocommerce' ),
                    $e->getMessage()
                ),
                array( 'status' => 500 )
            );
        }
    }
}
