<?php
if (!defined('ABSPATH')) exit;

function paycal_invoice_download_forbidden(): void {
    wp_die(esc_html__('Access denied.', 'klamra-paycal-for-aspaclaria'), '', ['response' => 403]);
}

function paycal_invoice_download_not_found(): void {
    wp_die(esc_html__('Invoice not found.', 'klamra-paycal-for-aspaclaria'), '', ['response' => 404]);
}

function paycal_invoice_download_handler(): void {
    if (!is_user_logged_in()) {
        paycal_invoice_download_forbidden();
    }

    $invoice_id = isset($_GET['invoice_id']) ? absint(wp_unslash($_GET['invoice_id'])) : 0;
    if (!$invoice_id) {
        paycal_invoice_download_not_found();
    }

    $nonce = sanitize_text_field(wp_unslash($_GET['_wpnonce'] ?? ''));
    if (!$nonce || !wp_verify_nonce($nonce, 'paycal_invoice_download_' . $invoice_id)) {
        paycal_invoice_download_forbidden();
    }

    if (!function_exists('paycal_invoice_get_authorized_order_for_download')) {
        paycal_invoice_download_not_found();
    }

    $order = paycal_invoice_get_authorized_order_for_download($invoice_id);
    if (is_wp_error($order)) {
        $status = (int) ($order->get_error_data()['status'] ?? 403);
        if ($status === 404) {
            paycal_invoice_download_not_found();
        }
        paycal_invoice_download_forbidden();
    }

    $html = paycal_invoice_render_html($invoice_id, (int) $order->get_id());

    header('Content-Type: text/html; charset=utf-8');
    header('Content-Disposition: attachment; filename="invoice-' . $invoice_id . '.html"');
    echo wp_kses_post($html);
    exit;
}

add_action('admin_post_paycal_invoice_download', 'paycal_invoice_download_handler');
add_action('admin_post_nopriv_paycal_invoice_download', 'paycal_invoice_download_handler');
