<?php

namespace GrUpnPf\Pro;

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

class GrUpnPf_Pro_Features
{
    private $upn_image_path = '';
    private static $current_email = null;

    private static $attachment_added_for_email = [];
    // Reset per email
    private static $email_rendered_once = false;
    private static $embed_registered_once = false;

    public function __construct()
    {
        /**
         * === ORDER CREATION / IMAGE GENERATION ===
         */
        add_action('woocommerce_checkout_order_processed', [$this, 'generate_and_save_upn_image_on_checkout'], 10, 1);
        add_action('woocommerce_checkout_update_order_meta', [$this, 'generate_and_save_upn_image_on_checkout'], 10, 2);
        add_action('woocommerce_new_order', [$this, 'generate_and_save_upn_image_on_checkout'], 10, 1);
        add_action('woocommerce_store_api_checkout_order_processed', [$this, 'generate_and_save_upn_image_on_checkout'], 10, 2);
        add_action('woocommerce_order_status_pending_to_on-hold', [$this, 'generate_and_save_upn_image_on_checkout'], 10, 1);

        /**
         * === CAPTURE WC EMAIL OBJECT ===
         */
        add_action('woocommerce_email_before_send', [$this, 'capture_current_email'], 5, 2);
        add_action('woocommerce_email', [$this, 'capture_current_email'], 5);
        add_action('woocommerce_email_init', [$this, 'capture_current_email'], 5);

        /**
         * === EMAIL OUTPUT HOOKS ===
         */
        add_action('woocommerce_email_before_order_table', [$this, 'prepareUPNForEmail'], 1, 4);
        add_action('woocommerce_email_after_order_table', [$this, 'displayUPNOnEmails'], 20, 4);

        /**
         * === ATTACHMENT ONLY FOR ON-HOLD ===
         */
        add_filter('woocommerce_email_attachments', [$this, 'add_upn_attachment'], 10, 4);

        /**
         * === THANK YOU PAGE ===
         */
        add_action('woocommerce_thankyou', [$this, 'displayUPNOnOrderPage'], 5, 1);

        /**
         * === CLEANUP ===
         */
        add_action('woocommerce_order_status_completed', [$this, 'cleanup_upn_image']);
        add_action('woocommerce_order_status_cancelled', [$this, 'cleanup_upn_image']);
        add_action('woocommerce_order_status_refunded', [$this, 'cleanup_upn_image']);

        /**
         * === SHORTCODE ===
         */
        add_shortcode('grupnpf_upn', [$this, 'grupnpf_upn_shortcode']);
    }

    /**
     * Resolve UPN image path using PRO meta or FREE fallback.
     */
    private function grupnpf_get_image_path_fallback($order_id)
    {
        $order_id = absint($order_id);
        if (!$order_id) {
            return '';
        }

        // 1. Try PRO meta path
        $meta_path = get_post_meta($order_id, '_grupnpf_upn_path', true);
        if ($meta_path && file_exists($meta_path)) {
            return $meta_path;
        }

        // 2. Try PRO-style upload (older plugin versions)
        $upload_dir = wp_upload_dir();
        $fallback_pro = trailingslashit($upload_dir['basedir']) .
            'grupnpf-qrcodes/grupnpf-order-' . $order_id . '.png';

        if (file_exists($fallback_pro)) {
            update_post_meta($order_id, '_grupnpf_upn_path', $fallback_pro);
            return $fallback_pro;
        }

        // 3. Try FREE plugin fallback
        $fallback_free = trailingslashit($upload_dir['basedir']) .
            'gr-upn-pf/upn-' . $order_id . '.png';

        if (file_exists($fallback_free)) {

            // Store meta so PRO works next time
            update_post_meta($order_id, '_grupnpf_upn_path', $fallback_free);

            return $fallback_free;
        }

        // No image found anywhere
        return '';
    }

    /**
     * Shortcode to display UPN image (no WooCommerce dependency).
     *
     * @param array $atts Shortcode attributes.
     * @return string HTML output of the UPN image or empty string.
     */
    public function grupnpf_upn_shortcode($atts)
    {
        // Attribute defaults
        $atts = shortcode_atts(
            [
                'order_id' => 0,
            ],
            $atts,
            'grupnpf_upn'
        );

        // ---- Get order ID ----
        $order_id = absint($atts['order_id']);

        // Try URL ?order-received=XXXX
        if (!$order_id && isset($_GET['order-received'])) {
            $order_id = absint($_GET['order-received']);
        }

        // WooFunnels thank-you page (order_id)
        if (!$order_id && isset($_GET['order_id'])) {
            $order_id = absint($_GET['order_id']);
        }

        // Try post context on thank-you page
        if (!$order_id) {
            $pid = get_the_ID();
            if ($pid && get_post_type($pid) === 'shop_order') {
                $order_id = absint($pid);
            }
        }

        if (!$order_id) {
            return '';
        }

        // ---- STEP 1: Try meta path ----
        $image_path = $this->grupnpf_get_image_path_fallback($order_id);

        if (!$image_path) {
            return '';
        }

        $contents = @file_get_contents($image_path);
        if (!$contents) {
            return '';
        }

        $img = base64_encode($contents);

        // ---- Output ----
        return '<div class="grupnpf-upn-shortcode" style="margin-top:20px;">
                <img src="data:image/png;base64,' . esc_attr($img) . '" alt="UPN QR" />
            </div>';
    }

    /**
     * Capture WC Email object & reset flags for NEW email
     */
    public function capture_current_email($email)
    {
        if ($email instanceof \WC_Email) {
            self::$current_email = $email;

            // RESET FLAGS — CRITICAL FIX
            self::$email_rendered_once = false;
            self::$embed_registered_once = false;

            \GrUpnPf\grupnpf_log("PRO: capture_current_email: " . $email->id);
        }
    }

    /**
     * Generate UPN PNG
     */
    public function generate_and_save_upn_image_on_checkout($order_id)
    {
        $order = wc_get_order($order_id);
        if (!$order || $order->get_payment_method() !== 'bacs') {
            return;
        }

        $existing_path = get_post_meta($order_id, '_grupnpf_upn_path', true);
        if ($existing_path && file_exists($existing_path)) {
            return;
        }

        $logic = new \GrUpnPf\GrUpnPf_Logic_UPN();
        $png = $logic->genUPN($order);

        if ($png) {
            $image_path = $logic->saveUpnImage($png, $order_id);
        }
    }

    /**
     * Attach image only to ON-HOLD email
     */
    public function add_upn_attachment($attachments, $email_id, $order, $email = null)
    {
        if (!($order instanceof \WC_Order)) {
            return $attachments;
        }

        if ($order->get_payment_method() !== 'bacs') {
            return $attachments;
        }

        if ($email_id !== 'customer_on_hold_order') {
            return $attachments;
        }
        $key = $email_id . '_' . $order->get_id();

        // Prevent duplicates across multiple filter calls
        if (isset(self::$attachment_added_for_email[$key])) {
            return $attachments;
        }

        $image_path = $this->grupnpf_get_image_path_fallback($order->get_id());

        if (
            get_option('grupnpf_email_priponka') === 'yes' &&
            $image_path &&
            file_exists($image_path)
        ) {
            $attachments[] = $image_path;
            self::$attachment_added_for_email[$key] = true;
        }

        return $attachments;
    }

    /**
     * Prepare for inline UPN (NO output if not on-hold email)
     */
    public function prepareUPNForEmail($order, $sentToAdmin, $plainText, $email = null)
    {
        // EARLY EXIT BEFORE BUFFER — FIX
        if (!$email || $email->id !== 'customer_on_hold_order')
            return;
        if ($sentToAdmin || $plainText)
            return;
        if ($order->get_payment_method() !== 'bacs')
            return;

        ob_start();

        $this->upn_image_path = $this->grupnpf_get_image_path_fallback($order->get_id());

        ob_end_clean(); // ALWAYS CLEAN — FIX
    }

    /**
     * Print inline UPN IMG + embed only for on-hold email
     */
    public function displayUPNOnEmails($order, $sentToAdmin, $plainText, $email = null)
    {
        // EARLY EXIT BEFORE BUFFER — FIX
        if (!$email || $email->id !== 'customer_on_hold_order')
            return;
        if ($sentToAdmin || $plainText)
            return;
        if ($order->get_payment_method() !== 'bacs')
            return;
        if (get_option('grupnpf_email_vstavi_upn') !== 'yes')
            return;

        $path = $this->grupnpf_get_image_path_fallback($order->get_id());
        if (!$path || !file_exists($path)) {
            return;
        }

        ob_start();

        $cid = basename($path);

        // Render inline HTML once
        if (!self::$email_rendered_once) {
            self::$email_rendered_once = true;

            echo '<div style="margin-top:20px;">';
            echo '<img src="cid:' . esc_attr($cid) . '" alt="UPN QR" />';
            echo '</div>';
        }

        // Embed image once
        if (!self::$embed_registered_once) {
            self::$embed_registered_once = true;

            add_action('phpmailer_init', function ($phpmailer) use ($path, $cid) {
                try {
                    $phpmailer->AddEmbeddedImage($path, $cid, $cid, 'base64', 'image/png');
                } catch (\Exception $e) {
                    \GrUpnPf\grupnpf_log("PRO: embed failed: " . $e->getMessage());
                }
            });
        }

        echo ob_get_clean();
    }

    /**
     * Thank-you page
     */
    public function displayUPNOnOrderPage($orderId)
    {
        static $printed_for_order = [];

        // Normalize order id
        if (is_object($orderId) && method_exists($orderId, 'get_id')) {
            $orderId = $orderId->get_id();
        }

        $orderId = absint($orderId);
        if (!$orderId) {
            return;
        }

        // Prevent duplicates PER ORDER per request
        if (isset($printed_for_order[$orderId])) {
            return;
        }

        $order = wc_get_order($orderId);
        if (!$order || $order->get_payment_method() !== 'bacs') {
            return;
        }

        $image_path = $this->grupnpf_get_image_path_fallback($orderId);
        if (!$image_path || !file_exists($image_path)) {
            return;
        }

        // Mark as printed BEFORE echo — prevents race conditions
        $printed_for_order[$orderId] = true;

        // Output UPN QR
        $img = base64_encode(file_get_contents($image_path));
        echo '<div class="grupnpf-upn" style="margin-top:20px;">';
        echo '<img src="data:image/png;base64,' . $img . '" alt="UPN QR" />';
        echo '</div>';
    }


    /**
     * Cleanup
     */
    public function cleanup_upn_image($order)
    {
        $order_id = is_object($order) ? $order->get_id() : $order;
        $file_path = get_post_meta($order_id, '_grupnpf_upn_path', true);

        if ($file_path && file_exists($file_path)) {
            wp_delete_file($file_path);
        }

        delete_post_meta($order_id, '_grupnpf_upn_path');
        delete_post_meta($order_id, '_grupnpf_upn_url');
    }
}

new GrUpnPf_Pro_Features();