<?php

namespace YayMail\Integrations\YITHWooCustomOrderStatusPremium;

use YayMail\Integrations\YITHWooCustomOrderStatusPremium\Emails\CustomOrderStatusEmail;
use YayMail\Integrations\YITHWooCustomOrderStatusPremium\Emails\EmailsHandler;
use YayMail\Integrations\YITHWooCustomOrderStatusPremium\Shortcodes\YITHWooCustomOrderStatusPremiumShortcodes;
use YayMail\Utils\SingletonTrait;
use YayMail\Utils\Localize;

/**
 * Plugin: YITH WooCommerce Custom Order Status Premium
 * Link: https://docs.yithemes.com/yith-woocommerce-custom-order-status/
 *
 * YITHWooCustomOrderStatusPremium
 * * @method static YITHWooCustomOrderStatusPremium get_instance()
 */
class YITHWooCustomOrderStatusPremium {
    use SingletonTrait;

    private function __construct() {
        if ( self::is_3rd_party_installed() ) {
            $this->initialize_hooks();
            $this->initialize_elements();
            $this->initialize_shortcodes();
            $this->initialize_emails();

            add_filter( 'yaymail_get_all_templates', [ $this, 'remove_default_order_status' ] );
        }
    }

    public static function is_3rd_party_installed() {
        return class_exists( 'YITH_WCCOS_Admin' );
    }

    private function initialize_hooks() {
    }

    private function initialize_elements() {
    }

    private function initialize_shortcodes() {
        add_action(
            'yaymail_register_shortcodes',
            function () {
                YITHWooCustomOrderStatusPremiumShortcodes::get_instance();
            }
        );
    }

    private function initialize_emails() {

        /**
         * Hack to bypass the language issue
         * TODO: refactor for other cases
         */
        if ( function_exists( 'PLL' ) ) {
            $request_uri = esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ?? '' ) );
            $parsed_url  = wp_parse_url( $request_uri );
            $route       = $parsed_url['path'] ?? '';
            if ( strpos( $route, '/yaymail' ) !== false || strpos( sanitize_text_field( wp_unslash( $_REQUEST['action'] ?? '' ) ), 'yaymail' ) !== false ) { //phpcs:ignore WordPress.Security.NonceVerification.Recommended
                $translate_integrations = Localize::get_translate_integrations();
                if ( ! empty( $translate_integrations['current_translation'] ) ) {
                    $current_language = $translate_integrations['current_translation']['active_language'] ?? 'en';
                    PLL()->curlang    = PLL()->model->get_language( $current_language );
                }
            }
        }

        $custom_order_statuses = $this->get_custom_order_statuses();
        foreach ( $custom_order_statuses as $key => $value ) {
            $template_informations = (object) [
                'id'        => $key ?? '',
                'title'     => $value['title'] ?? '',
                'recipient' => $value['recipients'] ?? 'Customer',
                'subject'   => __( 'Order Status', 'yaymail' ),
            ];
            EmailsHandler::get_instance()->add_email( new CustomOrderStatusEmail( $template_informations ) );
        }

        add_action(
            'yaymail_register_emails',
            function ( $email_service ) {
                $emails = EmailsHandler::get_instance()->get_emails();
                foreach ( $emails as $email_instance ) {
                    $email_service->register( $email_instance );
                }
            }
        );
    }


    public function get_custom_order_statuses() {
        $statuses   = [];
        $status_ids = get_posts(
            [
                'posts_per_page' => - 1,
                'post_type'      => 'yith-wccos-ostatus',
                'post_status'    => 'publish',
                'fields'         => 'ids',
            ]
        );
        foreach ( $status_ids as $id ) {
            $title                                  = apply_filters( 'yith_wccos_order_status_title', get_the_title( $id ), $id );
            $status_slug                            = 'wc-' . get_post_meta( $id, 'slug', true );
            $recipients                             = get_post_meta( $id, 'recipients', true );
            $statuses[ $status_slug ]['title']      = $title;
            $statuses[ $status_slug ]['recipients'] = ( ! empty( $recipients ) && is_array( $recipients ) )
                ? ucwords( implode( ', ', $recipients ) )
                : __( 'Customer', 'yaymail' );
        }

        return $statuses;
    }

    public function remove_default_order_status( $templates ) {
        return array_values(
            array_filter(
                $templates,
                function( $template ) {
                    return isset( $template['name'] ) && $template['name'] !== 'custom_order_status_email';
                }
            )
        );
    }
}
