<?php
defined('ABSPATH') || exit;

class PDFInvX_Bulk {
    public function __construct() {
        add_filter('bulk_actions-edit-shop_order', [$this, 'add_bulk_action']);
        add_action('admin_action_pdfinvx_bulk_generate_pdf', [$this, 'handle_bulk_generate']);
    }

    public function add_bulk_action($actions) {
        $actions['pdfinvx_bulk_generate_pdf'] = esc_html__('Generate PDF Invoices', 'pdf-invoicex');
        return $actions;
    }

    public function handle_bulk_generate() {
        if (!isset($_GET['post']) || !current_user_can('manage_woocommerce')) {
            wp_die(esc_html__('No orders selected or unauthorized access.', 'pdf-invoicex'));
        }

        check_admin_referer('bulk-posts');

        // Initialize WP_Filesystem
        if (!function_exists('WP_Filesystem')) {
            require_once ABSPATH . 'wp-admin/includes/file.php';
        }
        WP_Filesystem();
        global $wp_filesystem;

        $order_ids = array_map('absint', $_GET['post']);
        $generator = new PDFInvX_Generator();
        $zip = new ZipArchive();
        $zip_file = sys_get_temp_dir() . '/pdfinvx_invoices_' . time() . '.zip';

        if ($zip->open($zip_file, ZipArchive::CREATE) !== true) {
            wp_die(esc_html__('Failed to create ZIP file.', 'pdf-invoicex'));
        }

        foreach ($order_ids as $order_id) {
            $order = wc_get_order($order_id);
            if ($order && $order->has_status(wc_get_is_paid_statuses())) {
                try {
                    $pdf_content = $generator->generate($order_id, false);
                    $invoice_number = $generator->get_invoice_number($order_id);
                    $zip->addFromString(sprintf('invoice-%s.pdf', sanitize_file_name($invoice_number)), $pdf_content);
                } catch (Exception $e) {
                    // Use WooCommerce logger instead of error_log
                    if (defined('WP_DEBUG') && WP_DEBUG) {
                        $logger = wc_get_logger();
                        $logger->error(
                            sprintf('PDFInvoiceX Bulk PDF Error for Order %d: %s', $order_id, $e->getMessage()),
                            ['source' => 'pdf-invoicex']
                        );
                    }
                }
            }
        }

        $zip->close();

        // Output the ZIP file using WP_Filesystem
        header('Content-Type: application/zip');
        header('Content-Disposition: attachment; filename="invoices.zip"');
        header('Content-Length: ' . $wp_filesystem->size($zip_file));
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Binary ZIP data, not user input
        echo $wp_filesystem->get_contents($zip_file);

        // Delete the ZIP file using wp_delete_file
        wp_delete_file($zip_file);
        exit;
    }
}
?>