<?php

namespace Storeplugin\PDFInvoice\App\Integrations;

defined('ABSPATH') || exit;

use Storeplugin\PDFInvoice\App\Contracts\WooHookableInterface;
use Storeplugin\PDFInvoice\App\TempDir;
use Storeplugin\PDFInvoice\App\Utils;

class WooCommerceEmailIntegration implements WooHookableInterface {
    public function init(): void {
        // Attach PDF to emails
        add_filter('woocommerce_email_attachments', [$this, 'attach_pdf_to_email'], 10, 4);

        // Auto-generate on status change
        add_action('woocommerce_order_status_changed', [$this, 'maybe_generate_invoice'], 10, 4);

        // Add invoice buttons to email body
        add_action('woocommerce_email_after_order_table', [$this, 'add_invoice_buttons_to_email'], 10, 4);

        // Cleanup temp PDFs
        add_action('nxts_cleanup_temp_pdf', [$this, 'cleanup_temp_pdf']);
    }

    public function attach_pdf_to_email($attachments, $email_id, $order, $email = null) {
        if (!$order || !is_a($order, 'WC_Order')) {
            if (is_numeric($order)) {
                $order = wc_get_order((int) $order);
            }
        }

        if (!$order || !is_a($order, 'WC_Order')) {
            return $attachments;
        }

        $attach_to = Utils::getOption('attach_to_emails', Utils::GROUP_SETTINGS);

        if (!is_array($attach_to)) {
            $attach_to = [$attach_to];
        }

        if (empty($attach_to) || !in_array($email_id, $attach_to, true)) {
            return $attachments;
        }

        $pdf_path = $this->generate_temp_pdf($order);
        if ($pdf_path && file_exists($pdf_path)) {
            $attachments[] = $pdf_path;
        }

        return $attachments;
    }

    public function add_invoice_buttons_to_email($order, $sent_to_admin = false, $plain_text = false, $email = null) {
        if (!$order || !is_a($order, 'WC_Order')) {
            return;
        }

        if (!$email || !isset($email->id)) {
            return;
        }

        $access_mode = (string) Utils::getOption('customer_print_access', Utils::GROUP_SETTINGS);

        if ($access_mode === 'disabled') {
            return;
        }

        $attach_to = Utils::getOption('attach_to_emails', Utils::GROUP_SETTINGS);
        if (!is_array($attach_to)) {
            $attach_to = [$attach_to];
        }

        if (empty($attach_to) || !in_array($email->id, $attach_to, true)) {
            return;
        }

        $frontend_access = new WooCommerceFrontendIntegration();
        $view_url = $frontend_access->get_invoice_url($order, 'view');
        $download_url = $frontend_access->get_invoice_url($order, 'download');

        if ($plain_text) {
            echo "\n" . esc_html__('Download Invoice', 'storeinvoice-print-pdf-invoices-and-packing-slips') . ': ' . esc_url($download_url) . "\n";
            echo esc_html__('View Invoice', 'storeinvoice-print-pdf-invoices-and-packing-slips') . ': ' . esc_url($view_url) . "\n";
            return;
        }

        ?>
        <div style="margin: 16px 0; padding: 0; text-align: center;">
            <!--[if mso]>
            <v:roundrect xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w="urn:schemas-microsoft-com:office:word" href="<?php echo esc_url($download_url); ?>" style="height:40px;v-text-anchor:middle;width:180px;" arcsize="10%" strokecolor="#7f54b3" fillcolor="#7f54b3">
            <w:anchorlock/>
            <center style="color:#ffffff;font-family:Helvetica,Arial,sans-serif;font-size:14px;font-weight:bold;"><?php esc_html_e('Download Invoice', 'storeinvoice-print-pdf-invoices-and-packing-slips'); ?></center>
            </v:roundrect>
            <![endif]-->
            <!--[if !mso]><!-->
            <table cellpadding="0" cellspacing="0" border="0" role="presentation" style="margin: 0 auto; border-collapse: separate;">
                <tr>
                    <td align="center" valign="middle" style="background-color: #7f54b3; border-radius: 4px; padding: 0; mso-padding-alt: 0;">
                        <a href="<?php echo esc_url($download_url); ?>" target="_blank" style="display: inline-block; background-color: #7f54b3; color: #ffffff; font-family: Helvetica, Arial, sans-serif; font-size: 14px; font-weight: bold; line-height: 40px; text-align: center; text-decoration: none; width: 180px; -webkit-text-size-adjust: none; border-radius: 4px; mso-hide: all;">
                            <?php esc_html_e('Download Invoice', 'storeinvoice-print-pdf-invoices-and-packing-slips'); ?>
                        </a>
                    </td>
                    <td style="width: 12px;">&nbsp;</td>
                    <td align="center" valign="middle" style="border: 2px solid #7f54b3; border-radius: 4px; padding: 0; mso-padding-alt: 0;">
                        <a href="<?php echo esc_url($view_url); ?>" target="_blank" style="display: inline-block; color: #7f54b3; font-family: Helvetica, Arial, sans-serif; font-size: 14px; font-weight: bold; line-height: 36px; text-align: center; text-decoration: none; width: 180px; -webkit-text-size-adjust: none; border-radius: 4px;">
                            <?php esc_html_e('View Invoice', 'storeinvoice-print-pdf-invoices-and-packing-slips'); ?>
                        </a>
                    </td>
                </tr>
            </table>
            <!--<![endif]-->
        </div>
        <?php
    }

    public function maybe_generate_invoice($order_id, $old_status, $new_status, $order) {
        $auto_statuses = Utils::getOption('auto_generate_on_status', Utils::GROUP_SETTINGS);

        if (!is_array($auto_statuses)) {
            $auto_statuses = [$auto_statuses];
        }

        if (empty($auto_statuses) || !in_array($new_status, $auto_statuses, true)) {
            return;
        }

        if (!$order || !is_a($order, 'WC_Order')) {
            $order = wc_get_order($order_id);
        }

        if (!$order || !is_a($order, 'WC_Order')) {
            return;
        }

        // Generate and store invoice number if using sequential mode
        $generator = new PdfDocumentGenerator();
        $generator->get_invoice_number($order);
    }

    private function generate_temp_pdf($order) {
        $generator = new PdfDocumentGenerator();
        $result = $generator->generate_order_pdf($order->get_id());

        if (is_wp_error($result)) {
            return false;
        }

        $filename = $generator->get_pdf_filename([
            'order_number' => $order->get_order_number(),
            'invoice_number' => $generator->get_invoice_number($order),
        ]);
        $base = pathinfo($filename, PATHINFO_FILENAME);
        $ext = pathinfo($filename, PATHINFO_EXTENSION) ?: 'pdf';
        $unique = $base . '-' . $order->get_id() . '-' . uniqid('', true) . '.' . $ext;

        $filepath = TempDir::store($unique, $generator->get_pdf_string());

        // Schedule cleanup
        wp_schedule_single_event(time() + 3600, 'nxts_cleanup_temp_pdf', [$filepath]);

        return $filepath;
    }

    public function cleanup_temp_pdf($filepath): void {
        if (is_string($filepath)) {
            TempDir::remove($filepath);
        }
    }
}
