<?php
/**
 * InvoicePdfCompletedOrder.php
 *
 * @since
 * @author     alfiopiccione <alfio.piccione@gmail.com>

 * @license    http://opensource.org/licenses/gpl-2.0.php GPL v2
 *
 * Copyright (C) 2025 POP
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

namespace WcElectronInvoice\WooCommerce\Emails;

use WcElectronInvoice\Plugin;
use function WcElectronInvoice\Functions\disableInvoiceOnOrderTotalZero;
use function WcElectronInvoice\Functions\getZugferdCompletedOrderAttachments;
use WcElectronInvoice\Integrations;

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

/**
 * Class CustomCompletedOrder
 *
 * @author alfiopiccione <alfio.piccione@gmail.com>
 */
class InvoicePdfCompletedOrder extends \WC_Email
{
    /**
     * Constructor.
     */
    public function __construct()
    {
        $this->id             = 'invoice_pdf_order_completed';
        $this->title          = __('Send Invoice PDF on order completed', WC_EL_INV_TEXTDOMAIN);
        $this->description    = __('Personalized email for sending the PDF invoice.', WC_EL_INV_TEXTDOMAIN);
        $this->template_html  = 'html-pop-email-completed-order.php';
        $this->template_plain = 'plain-pop-email-completed-order.php';
        $this->template_base  = Plugin::getPluginDirPath('/woocommerce') . '/emails/';
        $this->placeholders   = array(
            '{order_date}'   => '',
            '{order_number}' => '',
        );

        // Triggers for this email.
        add_action('woocommerce_order_status_completed_notification', array($this, 'trigger'), 10, 2);

        // Call parent constructor.
        parent::__construct();

        // Other settings.
        $this->recipient = $this->get_option('recipient', get_option('admin_email'));
    }

    /**
     * Get email subject.
     *
     * @return string
     * @since  3.1.0
     */
    public function get_default_subject()
    {
        return __('[{site_title}]: Invoice PDF for order #{order_number}', WC_EL_INV_TEXTDOMAIN);
    }

    /**
     * Get email heading.
     *
     * @return string
     * @since  3.1.0
     */
    public function get_default_heading()
    {
        return __('Invoice PDF for Order: #{order_number}', WC_EL_INV_TEXTDOMAIN);
    }

    /**
     * Trigger the sending of this email.
     *
     * @param int            $order_id The order ID.
     * @param WC_Order|false $order    Order object.
     */
    public function trigger($order_id, $order = false)
    {
        $this->setup_locale();

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

        if (is_a($order, 'WC_Order')) {
            $this->object                         = $order;
            $this->placeholders['{order_date}']   = wc_format_datetime($this->object->get_date_created());
            $this->placeholders['{order_number}'] = $this->object->get_order_number();
        }

        // Disable email whit total zero
        if (disableInvoiceOnOrderTotalZero($this->object)) {
            return;
        }

        if (Integrations::isGermanyZugferdContext()) {
            $attachments = $this->attachmentsPdfToEmail($order);
            if ($this->is_enabled() && $this->get_recipient() && ! empty($attachments)) {
                $this->send(
                    apply_filters('wc_el_inv-invoice_pdf_email_recipient', $this->get_recipient(), $order),
                    $this->get_subject(),
                    $this->get_content(),
                    $this->get_headers(),
                    $attachments
                );
            }

            $this->restore_locale();
            return;
        }

        if ($this->is_enabled() && $this->get_recipient()) {

            $attachments = $this->attachmentsPdfToEmail($order);

            $this->send(
                apply_filters('wc_el_inv-invoice_pdf_email_recipient', $this->get_recipient(), $order),
                $this->get_subject(),
                $this->get_content(),
                $this->get_headers(),
                $attachments
            );
        }

        $this->restore_locale();
    }

    /**
     * Invoice Pdf
     *
     * @param $order
     *
     * @return array|false|string
     */
    private function attachmentsPdfToEmail($order)
    {
        if (Integrations::isGermanyZugferdContext()) {
            return getZugferdCompletedOrderAttachments($order);
        }

        try {
            $pdf = new \WcElectronInvoice\Pdf\CreatePdf();

            if ($pdf instanceof \WcElectronInvoice\Pdf\CreatePdf) {
                $attachments = $pdf->attachmentsPdfToEmail(
                    '',
                    'custom_email_completed_order_pdf_invoice',
                    $order
                );

                return is_array($attachments) ? $attachments : array();
            }
        } catch (\Dompdf\Exception $e) {
            return '';
        }

        return '';
    }

    /**
     * Get content html.
     *
     * @return string
     */
    public function get_content_html()
    {
        return wc_get_template_html(
            $this->template_html,
            array(
                'order'              => $this->object,
                'email_heading'      => $this->get_heading(),
                'additional_content' => $this->get_additional_content(),
                'sent_to_admin'      => true,
                'plain_text'         => false,
                'email'              => $this,
            ),
            $this->template_base,
            $this->template_base
        );
    }

    /**
     * Get content plain.
     *
     * @return string
     */
    public function get_content_plain()
    {
        return wc_get_template_html(
            $this->template_plain,
            array(
                'order'              => $this->object,
                'email_heading'      => $this->get_heading(),
                'additional_content' => $this->get_additional_content(),
                'sent_to_admin'      => true,
                'plain_text'         => true,
                'email'              => $this,
            ),
            $this->template_base,
            $this->template_base
        );
    }

    /**
     * Initialise settings form fields.
     */
    public function init_form_fields()
    {
        /* translators: %s: list of placeholders */
        $placeholder_text  = sprintf(__('Available placeholders: %s', 'woocommerce'),
            '<code>' . implode('</code>, <code>', array_keys($this->placeholders)) . '</code>');
        $this->form_fields = array(
            'enabled'            => array(
                'title'   => __('Enable/Disable', 'woocommerce'),
                'type'    => 'checkbox',
                'label'   => __('Enable this email notification', 'woocommerce'),
                'default' => 'no',
            ),
            'recipient'          => array(
                'title'       => __('Recipient(s)', 'woocommerce'),
                'type'        => 'text',
                /* translators: %s: WP admin email */
                'description' => sprintf(__('Enter recipients (comma separated) for this email. Defaults to %s.',
                    'woocommerce'), '<code>' . esc_attr(get_option('admin_email')) . '</code>'),
                'placeholder' => '',
                'default'     => '',
                'desc_tip'    => true,
            ),
            'subject'            => array(
                'title'       => __('Subject', 'woocommerce'),
                'type'        => 'text',
                'desc_tip'    => true,
                'description' => $placeholder_text,
                'placeholder' => $this->get_default_subject(),
                'default'     => '',
            ),
            'heading'            => array(
                'title'       => __('Email heading', 'woocommerce'),
                'type'        => 'text',
                'desc_tip'    => true,
                'description' => $placeholder_text,
                'placeholder' => $this->get_default_heading(),
                'default'     => '',
            ),
            'additional_content' => array(
                'title'       => __('Additional content', 'woocommerce'),
                'description' => __('Text to appear below the main email content.',
                        'woocommerce') . ' ' . $placeholder_text,
                'css'         => 'width:400px; height: 75px;',
                'placeholder' => esc_html__('Receive this email from the site {site_title}. Attached is the PDF invoice for order #{order_number}',
                    WC_EL_INV_TEXTDOMAIN),
                'type'        => 'textarea',
                'default'     => '',
                'desc_tip'    => true,
            ),
            'email_type'         => array(
                'title'       => __('Email type', 'woocommerce'),
                'type'        => 'select',
                'description' => __('Choose which format of email to send.', 'woocommerce'),
                'default'     => 'html',
                'class'       => 'email_type wc-enhanced-select',
                'options'     => $this->get_email_type_options(),
                'desc_tip'    => true,
            ),
        );
    }
}
