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

use Dompdf\Dompdf;
use Dompdf\Options;

class SIMPINBY_PDF {

  public static function download_invoice_pdf($invoice_id) {
    if (!current_user_can("manage_options")) return;

    global $wpdb;

    $invoice_table = $wpdb->prefix . "simpinby_invoices";
    $items_table   = $wpdb->prefix . "simpinby_invoice_items";
    $customers     = $wpdb->prefix . "simpinby_customers";

    $invoice = $wpdb->get_row(
      $wpdb->prepare("
        SELECT inv.*, c.name as customer_name, c.phone as customer_phone, c.address as customer_address
        FROM $invoice_table inv
        LEFT JOIN $customers c ON c.id = inv.customer_id
        WHERE inv.id=%d
      ", $invoice_id),
      ARRAY_A
    );

    if (!$invoice) {
      wp_die("Invoice not found");
    }

    $items = $wpdb->get_results(
      $wpdb->prepare("SELECT * FROM $items_table WHERE invoice_id=%d", $invoice_id),
      ARRAY_A
    );

    $pdf_settings = get_option("simpinby_pdf_settings", [
      "company_name" => "My Company",
      "footer_text" => "Thank you for your business!",
      "logo_url" => ""
    ]);

    // Render HTML template
    ob_start();
    include SIMPINBY_PLUGIN_PATH . "templates/invoice-pdf-template.php";
    $html = ob_get_clean();

    // Dompdf Options
    $options = new Options();
    $options->set('isRemoteEnabled', true); // allow logo URL
    $options->set('defaultFont', 'DejaVu Sans');

    $dompdf = new Dompdf($options);
    $dompdf->loadHtml($html);
    $dompdf->setPaper('A4', 'portrait');
    $dompdf->render();

    $filename = $invoice["invoice_number"] . ".pdf";
    $dompdf->stream($filename, ["Attachment" => true]);
    exit;
  }
}
