<?php

if ( ! defined( 'ABSPATH' ) ) exit;

add_action('woocommerce_order_status_completed', 'ingen_generate_invoice_for_order');
add_action('woocommerce_admin_order_data_after_order_details', 'ingen_display_invoice_pdf_link');
add_action('woocommerce_thankyou', 'ingen_generate_invoice_and_show_link_on_thankyou', 10, 1);


function ingen_display_invoice_pdf_link($order) {
    $pdf_url = get_post_meta($order->get_id(), '_invoice_pdf_url', true);
    if ($pdf_url) {
        echo '<div class="form-field form-field-wide" style="padding-top: 30px; padding-bottom: 20px;">
            <strong>' . esc_attr(__('Invoice PDF', 'invoice-generator')) . ':</strong>
            <a href="' . esc_url($pdf_url) . '" target="_blank">' . esc_attr(__('Download PDF', 'invoice-generator')) . '</a>
        </div>';
    }
}


function ingen_generate_invoice_for_order($order_id) {

    if ( ! function_exists( 'ingen_api_generate_invoice' ) ) {
        return;
    }

    if (get_post_meta($order_id, '_invoice_pdf_url', true)) {return;}

    $order = wc_get_order($order_id);
    if (!$order) {return;}

    //==== Store data ====
    $bill_from_name = get_bloginfo('name');
    $bill_from_email = get_option('admin_email');
    $bill_from_description = get_bloginfo('description');


    //==== Customer data ====
    $billing_name = trim($order->get_billing_first_name() . ' ' . $order->get_billing_last_name());
    $billing_email = $order->get_billing_email();
    $billing_address_parts = array(
        $order->get_billing_company(),
        $order->get_billing_address_1(),
        $order->get_billing_address_2(),
        $order->get_billing_city(),
        $order->get_billing_state(),
        $order->get_billing_postcode(),
        $order->get_billing_country(),
    );

    $billing_address = implode(', ', array_filter($billing_address_parts));

    // ==== Items ====
    $items = array();
    foreach ($order->get_items() as $item) {
        if (!$item->get_quantity()) continue;

        $price_per_unit = $order->get_line_subtotal($item, false) / $item->get_quantity();
        $items[] = array(
            'name'  => $item->get_name(),
            'qty'   => $item->get_quantity(),
            'price' => $price_per_unit,
        );
    }

    if (empty($items)) {
        // error_log("Order #$order_id has no items, skipping invoice.");
        return;
    }

    // ==== Tax ====
    $subtotal = $order->get_subtotal();
    $tax_total = $order->get_total_tax();
    $tax_rate = ($subtotal > 0 && $tax_total > 0) ? round(($tax_total / $subtotal) * 100, 2) : 0;

    // ==== Full structure for API ====
    $data = array(
        'invoice_number'        => 'WC-' . $order->get_order_number(),
        'invoice_date'          => wp_date('Y-m-d'),
        'due_date'              => wp_date('Y-m-d', strtotime('+14 days')),
        'bill_from_name'        => $bill_from_name,
        'bill_from_email'       => $bill_from_email,
        'bill_from_description' => $bill_from_description,
        'bill_to_name'          => $billing_name ? $billing_name : '',
        'bill_to_email'         => $billing_email ? $billing_email : '',
        'bill_to_description'   => $billing_address ? $billing_address : '',
        'currency'              => $order->get_currency(),
        'items'                 => $items,
        'tax_rate'              => $tax_rate,
        'template_style'        => 'blue-accent',
        'table_class'           => 'invoice-table',
    );

    // ==== Generation of PDF ====
    $result = ingen_api_generate_invoice($data);

   if ($result['code'] === 200 && !empty($result['pdf_url'])) {
       update_post_meta($order_id, '_invoice_pdf_url', esc_url($result['pdf_url']));
   }
}


function ingen_generate_invoice_and_show_link_on_thankyou($order_id) {
    if (!function_exists('ingen_api_generate_invoice')) {return;}

    if (get_post_meta($order_id, '_invoice_pdf_url', true)) {
        return;
    }

    ingen_generate_invoice_for_order($order_id);

    $pdf_url = get_post_meta($order_id, '_invoice_pdf_url', true);

    if ($pdf_url) {
        echo '<div class="woocommerce-message" style="margin-top: 30px;">';
        echo '<strong>' . esc_html(__('Your Invoice PDF:', 'invoice-generator')) . '</strong> &nbsp; ';
        echo '<a href="' . esc_url($pdf_url) . '" target="_blank" rel="noopener noreferrer">' . esc_html(__('Download Invoice', 'invoice-generator')) . '</a>';
        echo '</div>';
    }
}
