<?php
defined('ABSPATH') || exit;
class PDFInvX_Admin {
    private $settings;
    public function __construct(PDFInvX_Settings $settings) {
        $this->settings = $settings;
        add_action('admin_menu', [$this, 'add_menu_link']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_assets']);
        add_filter('woocommerce_admin_order_actions', [$this, 'add_order_action'], 10, 2);
        add_action('add_meta_boxes', [$this, 'add_meta_box']);
        add_action('wp_ajax_pdfinvx_generate_pdf', [$this, 'handle_generate_pdf']);
        add_action('wp_ajax_pdfinvx_download_pdf', [$this, 'handle_download_pdf']);
    }
    public function add_menu_link() {
        add_submenu_page(
            'woocommerce',
            esc_html__('PDF InvoiceX', 'pdf-invoicex'),
            esc_html__('PDF InvoiceX', 'pdf-invoicex'),
            'manage_woocommerce',
            'pdfinvx-settings',
            [$this->settings, 'render_settings_page']
        );
    }
    public function enqueue_assets($hook) {
        if (!in_array($hook, ['edit.php', 'post.php', 'woocommerce_page_pdfinvx-settings'], true) || ('edit.php' === $hook && 'shop_order' !== get_post_type())) {
            return;
        }
        wp_enqueue_media();
        wp_enqueue_style('pdfinvx-admin', PDFINVX51_PLUGIN_URL . 'assets/css/admin.css', [], PDFINVX51_VERSION);
        wp_enqueue_script('pdfinvx-admin', PDFINVX51_PLUGIN_URL . 'assets/js/admin.js', ['jquery', 'wp-i18n', 'media-editor'], PDFINVX51_VERSION, true);
        
        wp_localize_script('pdfinvx-admin', 'pdfInvoiceXAdmin', [
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('pdfinvx_generate_pdf'),
            'i18n' => [
                'generating' => esc_html__('Generating PDF...', 'pdf-invoicex'),
                'error' => esc_html__('Failed to generate PDF: Please check server logs or contact support.', 'pdf-invoicex'),
                'mediaError' => esc_html__('Media library failed to load. Please try again.', 'pdf-invoicex'),
            ],
        ]);
    }
    public function add_order_action($actions, $order) {
        if ($order->has_status(wc_get_is_paid_statuses())) {
            $actions['pdfinvx_generate_pdf'] = [
                'action' => 'pdfinvx_generate_pdf',
                'name' => esc_html__('Download PDF Invoice', 'pdf-invoicex'),
                'url' => wp_nonce_url(admin_url('admin-ajax.php?action=pdfinvx_generate_pdf&order_id=' . $order->get_id()), 'pdfinvx_generate_pdf'),
                'class' => 'pdfinvx-download-pdf',
            ];
        }
        return $actions;
    }
    public function add_meta_box() {
        add_meta_box(
            'pdfinvx_invoice',
            esc_html__('PDF InvoiceX', 'pdf-invoicex'),
            [$this, 'render_meta_box'],
            'shop_order',
            'side',
            'default'
        );
    }
    public function render_meta_box($post) {
        $order = wc_get_order($post->ID);
        if ($order && $order->has_status(wc_get_is_paid_statuses())) {
            $url = wp_nonce_url(admin_url('admin-ajax.php?action=pdfinvx_generate_pdf&order_id=' . $order->get_id()), 'pdfinvx_generate_pdf');
            printf(
                '<a href="%s" class="button pdfinvx-button pdfinvx-download-pdf">%s</a>',
                esc_url($url),
                esc_html__('Download Invoice', 'pdf-invoicex')
            );
        } else {
            printf('<p>%s</p>', esc_html__('Invoice available after payment.', 'pdf-invoicex'));
        }
    }
    public function handle_generate_pdf() {
        // Ensure clean output buffer
        while (ob_get_level()) {
            ob_end_clean();
        }
        ob_start();
        check_ajax_referer('pdfinvx_generate_pdf', 'nonce');
        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error(['message' => esc_html__('Unauthorized access.', 'pdf-invoicex')]);
        }
        $order_id = isset($_GET['order_id']) ? absint($_GET['order_id']) : 0;
        $order = wc_get_order($order_id);
        if (!$order || !$order->has_status(wc_get_is_paid_statuses())) {
            wp_send_json_error(['message' => esc_html__('Invalid or unpaid order.', 'pdf-invoicex')]);
        }
        try {
            if (!file_exists(PDFINVX51_PLUGIN_DIR . 'vendor/autoload.php')) {
                throw new Exception(esc_html__('PDF library is missing. Please run composer install.', 'pdf-invoicex'));
            }
            $generator = new PDFInvX_Generator();
            
            // Check if this is an AJAX request expecting JSON or a direct download request
            if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower(sanitize_text_field(wp_unslash($_SERVER['HTTP_X_REQUESTED_WITH']))) == 'xmlhttprequest') {
                // This is an AJAX request, create a temporary file with restricted access
                $invoice_number = $generator->get_invoice_number($order_id);
                $filename = sprintf('invoice-%s.pdf', sanitize_file_name($invoice_number));
                
                // Generate a unique token for this download
                $token = wp_generate_password(32, false);
                
                // Store the token with a short expiration
                set_transient('pdfinvx_download_' . $token, $order_id, 5 * MINUTE_IN_SECONDS);
                
                // Return the secure download URL with the token
                $download_url = add_query_arg(
                    [
                        'action' => 'pdfinvx_download_pdf',
                        'token' => $token,
                        '_wpnonce' => wp_create_nonce('pdfinvx_download_pdf')
                    ],
                    admin_url('admin-ajax.php')
                );
                
                ob_clean();
                wp_send_json_success(['file_url' => $download_url]);
            } else {
                // Direct download request
                $invoice_number = $generator->get_invoice_number($order_id);
                $filename = sprintf('invoice-%s.pdf', sanitize_file_name($invoice_number));
                
                // Generate PDF content
                $pdf_content = $generator->generate($order_id, false);
                
                // Set headers for direct download
                header('Content-Type: application/pdf');
                header('Content-Disposition: attachment; filename="' . $filename . '"');
                header('Content-Length: ' . strlen($pdf_content));
                header('Cache-Control: private, max-age=0, must-revalidate');
                header('Pragma: public');
                
                // Output the PDF content and exit
                // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Binary PDF data, not user input
                echo $pdf_content;
                exit;
            }
        } catch (Exception $e) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Error logging for production
            error_log('PDFInvoiceX PDF Generation Error for Order ' . $order_id . ': ' . $e->getMessage());
            if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower(sanitize_text_field(wp_unslash($_SERVER['HTTP_X_REQUESTED_WITH']))) == 'xmlhttprequest') {
                wp_send_json_error(['message' => esc_html($e->getMessage())]);
            } else {
                wp_die(esc_html($e->getMessage()));
            }
        }
    }
    
    /**
     * Handle secure PDF download using temporary tokens
     */
    public function handle_download_pdf() {
        // Ensure clean output buffer
        while (ob_get_level()) {
            ob_end_clean();
        }
        ob_start();
        
        // Verify nonce
        check_ajax_referer('pdfinvx_download_pdf');
        
        // Check user permissions
        if (!current_user_can('manage_woocommerce')) {
            wp_die(esc_html__('Unauthorized access.', 'pdf-invoicex'));
        }
        
        // Get and validate token
        $token = isset($_GET['token']) ? sanitize_text_field(wp_unslash($_GET['token'])) : '';
        if (empty($token)) {
            wp_die(esc_html__('Invalid download request.', 'pdf-invoicex'));
        }
        
        // Get order ID from token
        $order_id = get_transient('pdfinvx_download_' . $token);
        if (empty($order_id)) {
            wp_die(esc_html__('Download link has expired or is invalid.', 'pdf-invoicex'));
        }
        
        // Delete the transient to prevent reuse
        delete_transient('pdfinvx_download_' . $token);
        
        try {
            // Get order and validate
            $order = wc_get_order($order_id);
            if (!$order || !$order->has_status(wc_get_is_paid_statuses())) {
                throw new Exception(esc_html__('Invalid or unpaid order.', 'pdf-invoicex'));
            }
            
            if (!file_exists(PDFINVX51_PLUGIN_DIR . 'vendor/autoload.php')) {
                throw new Exception(esc_html__('PDF library is missing. Please run composer install.', 'pdf-invoicex'));
            }
            
            // Generate PDF
            $generator = new PDFInvX_Generator();
            $invoice_number = $generator->get_invoice_number($order_id);
            $filename = sprintf('invoice-%s.pdf', sanitize_file_name($invoice_number));
            $pdf_content = $generator->generate($order_id, false);
            
            // Set headers for direct download
            header('Content-Type: application/pdf');
            header('Content-Disposition: attachment; filename="' . $filename . '"');
            header('Content-Length: ' . strlen($pdf_content));
            header('Cache-Control: private, max-age=0, must-revalidate');
            header('Pragma: public');
            
            // Output the PDF content and exit
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Binary PDF data, not user input
            echo $pdf_content;
            exit;
            
        } catch (Exception $e) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Error logging for production
            error_log('PDFInvoiceX PDF Download Error for Order ' . $order_id . ': ' . $e->getMessage());
            wp_die(esc_html($e->getMessage()));
        }
    }
}
?>