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

$paycal_invoice_template_id = isset($invoice_id) ? absint($invoice_id) : 0;
if (!$paycal_invoice_template_id && isset($_GET['invoice_id'])) {
  $paycal_invoice_template_id = absint(wp_unslash($_GET['invoice_id']));
  if (!is_user_logged_in() || !function_exists('paycal_invoice_get_authorized_order_for_download')) {
    wp_die(esc_html__('Access denied.', 'klamra-paycal-for-aspaclaria'), '', ['response' => 403]);
  }

  $paycal_invoice_nonce = sanitize_text_field(wp_unslash($_GET['_wpnonce'] ?? ''));
  if (!$paycal_invoice_nonce || !wp_verify_nonce($paycal_invoice_nonce, 'paycal_invoice_download_' . $paycal_invoice_template_id)) {
    wp_die(esc_html__('Access denied.', 'klamra-paycal-for-aspaclaria'), '', ['response' => 403]);
  }

  $order = paycal_invoice_get_authorized_order_for_download($paycal_invoice_template_id);
  if (is_wp_error($order)) {
    $status = (int) ($order->get_error_data()['status'] ?? 403);
    wp_die(
      $status === 404 ? esc_html__('Invoice not found.', 'klamra-paycal-for-aspaclaria') : esc_html__('Access denied.', 'klamra-paycal-for-aspaclaria'),
      '',
      ['response' => $status === 404 ? 404 : 403]
    );
  }
}

echo wp_kses_post(paycal_invoice_render_html($paycal_invoice_template_id));
