<?php
/**
 * Invoice Module — POS/Thermal invoice generation.
 *
 * Generates 80mm-width HTML invoices for thermal printers.
 * Accessible via order actions and REST API.
 *
 * @package CapiFlow
 */

namespace CapiFlow\Core\Modules\Invoice;

defined( 'ABSPATH' ) || exit;

class Invoice_Generator {

    /**
     * Boot the module.
     */
    public static function init() {
        $instance = new self();

        // Add print button to order actions.
        add_filter( 'woocommerce_order_actions', array( $instance, 'add_print_action' ) );
        add_action( 'woocommerce_order_action_capiflow_print_invoice', array( $instance, 'handle_print_action' ) );

        // Admin page for invoice printing.
        add_action( 'admin_init', array( $instance, 'handle_print_request' ) );
    }

    /**
     * Add print invoice action to order actions dropdown.
     *
     * @param array $actions Existing actions.
     * @return array
     */
    public function add_print_action( $actions ) {
        $actions['capiflow_print_invoice'] = __( '🖨️ Print Thermal Invoice', 'capiflow' );
        return $actions;
    }

    /**
     * Handle print action from order actions dropdown.
     *
     * @param \WC_Order $order Order.
     */
    public function handle_print_action( $order ) {
        // Redirect to print page.
        wp_safe_redirect( admin_url( 'admin.php?capiflow_print_invoice=' . $order->get_id() . '&_wpnonce=' . wp_create_nonce( 'capiflow_print' ) ) );
        exit;
    }

    /**
     * Handle direct print request.
     */
    public function handle_print_request() {
        if ( empty( $_GET['capiflow_print_invoice'] ) ) {
            return;
        }

        if ( ! current_user_can( 'manage_woocommerce' ) ) {
            wp_die( esc_html__( 'Unauthorized', 'capiflow' ) );
        }

        check_admin_referer( 'capiflow_print' );

        $order_id = absint( $_GET['capiflow_print_invoice'] );
        $order    = wc_get_order( $order_id );

        if ( ! $order ) {
            wp_die( esc_html__( 'Order not found.', 'capiflow' ) );
        }

        $this->render_invoice( $order );
        exit;
    }

    /**
     * Render thermal invoice HTML (80mm width).
     *
     * @param \WC_Order $order Order.
     */
    private function render_invoice( $order ) {
        $store_name    = get_bloginfo( 'name' );
        $store_address = get_option( 'woocommerce_store_address', '' );
        $store_phone   = get_option( 'woocommerce_store_phone', '' );

        ?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title><?php echo esc_html( sprintf( 'Invoice #%s', $order->get_order_number() ) ); ?></title>
    <?php // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet -- Standalone HTML page rendered via exit(); wp_enqueue_style() is unavailable outside the WP template lifecycle. ?>
    <link rel="stylesheet" href="<?php echo esc_url( plugins_url( 'invoice-print.css', __FILE__ ) ); ?>" />
</head>
<body>
    <div class="no-print" style="text-align:center;margin-bottom:10px;">
        <button onclick="window.print()" style="padding:8px 20px;font-size:14px;cursor:pointer;">
            🖨️ Print Invoice
        </button>
    </div>

    <div class="center">
        <h1><?php echo esc_html( $store_name ); ?></h1>
        <div class="store-info">
            <?php if ( $store_address ) : ?>
                <?php echo esc_html( $store_address ); ?><br>
            <?php endif; ?>
            <?php if ( $store_phone ) : ?>
                📞 <?php echo esc_html( $store_phone ); ?>
            <?php endif; ?>
        </div>
    </div>

    <div class="line"></div>

    <div class="center bold">
        INVOICE #<?php echo esc_html( $order->get_order_number() ); ?>
    </div>
    <div class="center" style="font-size:10px;">
        <?php echo esc_html( $order->get_date_created() ? $order->get_date_created()->format( 'd/m/Y h:i A' ) : '' ); ?>
    </div>

    <div class="line"></div>

    <div style="font-size:11px;">
        <strong><?php echo esc_html( $order->get_billing_first_name() . ' ' . $order->get_billing_last_name() ); ?></strong><br>
        📞 <?php echo esc_html( $order->get_billing_phone() ); ?><br>
        📍 <?php echo esc_html( $order->get_billing_address_1() ); ?>
        <?php if ( $order->get_billing_city() ) : ?>
            , <?php echo esc_html( $order->get_billing_city() ); ?>
        <?php endif; ?>
    </div>

    <div class="line"></div>

    <table>
        <tr style="border-bottom:1px solid #000;">
            <td class="bold">Item</td>
            <td class="bold" style="text-align:center;">Qty</td>
            <td class="bold" style="text-align:right;">Price</td>
        </tr>
        <?php foreach ( $order->get_items() as $item ) : ?>
        <tr>
            <td style="max-width:120px;overflow:hidden;"><?php echo esc_html( $item->get_name() ); ?></td>
            <td style="text-align:center;"><?php echo esc_html( $item->get_quantity() ); ?></td>
            <td style="text-align:right;"><?php echo wp_kses_post( wc_price( $item->get_total(), array( 'currency' => $order->get_currency() ) ) ); ?></td>
        </tr>
        <?php endforeach; ?>
    </table>

    <div class="line"></div>

    <div class="item-row">
        <span>Subtotal</span>
        <span><?php echo wp_kses_post( wc_price( $order->get_subtotal(), array( 'currency' => $order->get_currency() ) ) ); ?></span>
    </div>

    <?php if ( (float) $order->get_total_discount() > 0 ) : ?>
    <div class="item-row">
        <span>Discount</span>
        <span>-<?php echo wp_kses_post( wc_price( $order->get_total_discount(), array( 'currency' => $order->get_currency() ) ) ); ?></span>
    </div>
    <?php endif; ?>

    <?php if ( (float) $order->get_shipping_total() > 0 ) : ?>
    <div class="item-row">
        <span>Shipping</span>
        <span><?php echo wp_kses_post( wc_price( $order->get_shipping_total(), array( 'currency' => $order->get_currency() ) ) ); ?></span>
    </div>
    <?php endif; ?>

    <div class="line"></div>

    <div class="total-row" style="font-size:14px;">
        <span>TOTAL</span>
        <span><?php echo wp_kses_post( wc_price( $order->get_total(), array( 'currency' => $order->get_currency() ) ) ); ?></span>
    </div>

    <div class="line"></div>

    <div class="center" style="font-size:10px;margin-top:5px;">
        Payment: <?php echo esc_html( $order->get_payment_method_title() ); ?><br>
        <?php esc_html_e( 'Thank you for your purchase!', 'capiflow' ); ?>
    </div>



</body>
</html>
        <?php
    }
}

// Auto-init when module loads via Plugin_Loader::load_module('invoice').
add_action( 'capiflow_module_loaded_invoice', array( 'CapiFlow\Core\Modules\Invoice\Invoice_Generator', 'init' ) );
