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

class PDFInvX_Frontend {
    public function __construct() {
        // Add download link on the order details page
        // add_action('woocommerce_order_details_after_order_table', [$this, 'add_download_link'], 10, 1);
        
        // Add download button to My Account orders list
        add_filter('woocommerce_my_account_my_orders_actions', [$this, 'add_order_action_button'], 10, 2);
        
        // Register custom rewrite rules
        add_action('init', [$this, 'add_rewrite_rules']);
        
        // Add query vars
        add_filter('query_vars', [$this, 'add_query_vars']);
        
        // Handle the PDF download
        add_action('template_redirect', [$this, 'handle_pdf_download']);
        
        // Keep AJAX endpoints for backward compatibility
        add_action('wp_ajax_pdfinvx_generate_pdf', [$this, 'handle_generate_pdf']);
        add_action('wp_ajax_nopriv_pdfinvx_generate_pdf', [$this, 'handle_generate_pdf']);
    }
    
    /**
     * Add custom rewrite rules for PDF downloads
     */
    public function add_rewrite_rules() {
        add_rewrite_rule(
            'pdfinvx-pdf/([0-9]+)/?$',
            'index.php?pdfinvx_pdf=1&order_id=$matches[1]',
            'top'
        );
        
        // Check if we need to flush rewrite rules
        if (get_option('pdfinvx_flush_rewrite_rules', false)) {
            flush_rewrite_rules();
            delete_option('pdfinvx_flush_rewrite_rules');
        }
    }
    
    /**
     * Add custom query vars
     */
    public function add_query_vars($query_vars) {
        $query_vars[] = 'pdfinvx_pdf';
        $query_vars[] = 'order_id';
        return $query_vars;
    }
    
    /**
     * Add download link to the order page
     */
    public function add_download_link($order) {
        if ($order->has_status(wc_get_is_paid_statuses())) {
            // Generate URL to our custom endpoint
            $url = wp_nonce_url(
                home_url('pdfinvx-pdf/' . $order->get_id()),
                'pdfinvx_generate_pdf_' . $order->get_id()
            );
            
            printf(
                '<p><a href="%s" class="woocommerce-button button pdfinvx-button pdfinvx-download-pdf" target="_blank">%s</a></p>',
                esc_url($url),
                esc_html__('Download Invoice', 'pdf-invoicex')
            );
        }
    }
    
    /**
     * Add "Download Invoice" button to My Account order actions
     */
    public function add_order_action_button($actions, $order) {
        // Only add the invoice button for paid orders
        if ($order->has_status(wc_get_is_paid_statuses())) {
            // Generate URL to our custom endpoint
            $url = wp_nonce_url(
                home_url('pdfinvx-pdf/' . $order->get_id()),
                'pdfinvx_generate_pdf_' . $order->get_id()
            );
            
            // Add our custom action
            $actions['pdfinvx_invoice'] = array(
                'url'  => $url,
                'name' => esc_html__('Invoice', 'pdf-invoicex')
            );
        }
        
        return $actions;
    }
    
    /**
     * Handle PDF download from custom endpoint
     */
    public function handle_pdf_download() {
        global $wp_query;
        
        // Check if this is our PDF download request
        if (!isset($wp_query->query_vars['pdfinvx_pdf']) || !isset($wp_query->query_vars['order_id'])) {
            return;
        }
        
        $order_id = absint($wp_query->query_vars['order_id']);
        if (!$order_id) {
            wp_die(esc_html__('Invalid order ID.', 'pdf-invoicex'));
        }
        
        // Verify nonce
        $nonce_action = 'pdfinvx_generate_pdf_' . $order_id;
        $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : '';
        if (!$nonce || !wp_verify_nonce($nonce, $nonce_action)) {
            wp_die(esc_html__('Security check failed.', 'pdf-invoicex'), 403);
        }
        
        // Get order
        $order = wc_get_order($order_id);
        if (!$order || !$order->has_status(wc_get_is_paid_statuses())) {
            wp_die(esc_html__('Invalid or unpaid order.', 'pdf-invoicex'), 403);
        }
        
        // Check if user is allowed to access this order
        $user_id = get_current_user_id();
        if (!$user_id || ($order->get_user_id() !== $user_id && !current_user_can('edit_shop_orders'))) {
            wp_die(esc_html__('Unauthorized access.', 'pdf-invoicex'), 403);
        }
        
        try {
            // Check if vendor directory exists
            if (!file_exists(PDFINVX51_PLUGIN_DIR . 'vendor/autoload.php')) {
                throw new Exception(esc_html__('PDF library is missing. Please contact support.', 'pdf-invoicex'));
            }
            
            // Generate PDF - do this before cleaning the output buffer
            $generator = new PDFInvX_Generator();
            $pdf_content = $generator->generate($order_id, false);
            $invoice_number = $generator->get_invoice_number($order_id);
            $filename = sprintf('invoice-%s.pdf', sanitize_file_name($invoice_number));
            
            // Clean all output buffers
            while (ob_get_level()) {
                ob_end_clean();
            }
            
            // Send appropriate headers for PDF download
            nocache_headers();
            header('Content-Type: application/pdf');
            header('Content-Disposition: attachment; filename="' . $filename . '"');
            header('Content-Length: ' . strlen($pdf_content));
            header('Cache-Control: private, no-store, no-cache, must-revalidate, max-age=0');
            header('Pragma: no-cache');
            header('Expires: 0');
            
            // Output PDF content and exit
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- PDF binary content, safe for direct output
            echo $pdf_content;
            exit;
            
        } catch (Exception $e) {
            // Use WooCommerce logger instead of error_log
            $logger = wc_get_logger();
            $logger->error(
                sprintf('PDFInvoiceX PDF Download Error for Order %d: %s', $order_id, $e->getMessage()),
                ['source' => 'pdf-invoicex']
            );
            wp_die(esc_html($e->getMessage()), esc_html__('Error', 'pdf-invoicex'), ['response' => 500]);
        }
    }
    
    /**
     * Legacy AJAX handler - now redirects to the custom endpoint
     */
    public function handle_generate_pdf() {
        // Verify nonce
        $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : '';
        if (!$nonce || !wp_verify_nonce($nonce, 'pdfinvx_generate_pdf')) {
            wp_die(esc_html__('Security check failed.', 'pdf-invoicex'), 403);
        }
        
        $order_id = isset($_GET['order_id']) ? absint($_GET['order_id']) : 0;
        if ($order_id) {
            $redirect_url = wp_nonce_url(
                home_url('pdfinvx-pdf/' . $order_id),
                'pdfinvx_generate_pdf_' . $order_id
            );
            wp_redirect($redirect_url);
            exit;
        }
        wp_die(esc_html__('Invalid request', 'pdf-invoicex'), 400);
    }
}
?>