<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

function qtranxf_wc_add_filters_admin(): void {
    // priority 20 is used because in case other plugins add some untranslated content on normal priority
    // it will still hopefully then get translated.
    $admin_hooks = array(
        'woocommerce_email_footer_text'     => 20,
        'woocommerce_email_from_address'    => 20,
        'woocommerce_email_from_name'       => 20,
        'woocommerce_attribute_taxonomies'  => 20,
        'woocommerce_variation_option_name' => 20,
    );

    $email_ids = array(
        'backorder'                         => 20,
        'cancelled_order'                   => 20,
        'customer_completed_order'          => 20,
        'customer_invoice'                  => 20,
        'customer_invoice_paid'             => 20,
        'customer_new_account'              => 20,
        'customer_note'                     => 20,
        'customer_partially_refunded_order' => 20,
        'customer_processing_order'         => 20,
        'customer_refunded_order'           => 20,
        'customer_reset_password'           => 20,
        'failed_order'                      => 20,
        'low_stock'                         => 20,
        'new_order'                         => 20,
        'no_stock'                          => 20,
    );

    // not all combinations are in use, but it is ok, they may be added in the future.
    foreach ( $email_ids as $name => $priority ) {
        $admin_hooks[ 'woocommerce_email_recipient_' . $name ] = $priority;
        $admin_hooks[ 'woocommerce_email_subject_' . $name ]   = $priority;
        $admin_hooks[ 'woocommerce_email_heading_' . $name ]   = $priority;
        $admin_hooks[ 'woocommerce_email_content_' . $name ]   = $priority;
    }

    qtranxf_add_filters( [ 'text' => $admin_hooks ] );
}

qtranxf_wc_add_filters_admin();

add_action( 'admin_enqueue_scripts', 'qtranxf_wc_add_admin_styles' );
function qtranxf_wc_add_admin_styles(): void {
    wp_enqueue_style( 'qtranxf_wc_qtranslate_admin', plugins_url( '/css/modules/woo-commerce.css', QTRANSLATE_FILE ), array(), QTX_VERSION );
}

add_filter( 'qtranslate_admin_config', 'qtranxf_wc_add_admin_page_config' );
function qtranxf_wc_add_admin_page_config( array $page_configs ): array {
    // post.php
    // TODO refactor append config
    if ( ! isset( $page_configs['post'] ) ) {
        $page_configs['post'] = array();
    }
    $post_config = &$page_configs['post'];
    if ( ! isset( $post_config['pages'] ) ) {
        $post_config['pages'] = array( 'post.php' => '', 'post-new.php' => '' );
    }
    if ( ! isset( $post_config['anchors'] ) ) {
        $post_config['anchors'] = array( 'post-body-content' => array( 'where' => 'first last' ) );
    }
    $post_config['anchors']['woocommerce-product-data'] = array( 'where' => 'before' );

    if ( ! isset( $post_config['forms'] ) ) {
        $post_config['forms'] = array();
    }
    if ( ! isset( $post_config['forms']['post'] ) ) {
        $post_config['forms']['post'] = array();
    }
    if ( ! isset( $post_config['forms']['post']['fields'] ) ) {
        $post_config['forms']['post']['fields'] = array();
    }
    $fields                             = &$post_config['forms']['post']['fields'];
    $fields['inp-variable_description'] = array( 'jquery' => 'textarea[name^=variable_description]' );
    $fields['_purchase_note']           = array();
    $fields['td-attribute_name']        = array( 'jquery' => 'td.attribute_name', 'encode' => 'display' );
    $fields['a-wc-order-item-name']     = array( 'jquery' => 'a.wc-order-item-name', 'encode' => 'display' );
    $fields['strong-attribute_name']    = array( 'jquery' => 'strong.attribute_name', 'encode' => 'display' );
    $fields['order_number']             = array( 'jquery' => '.order_number', 'encode' => 'display' );
    $fields['display_meta']             = array( 'jquery' => '.display_meta', 'encode' => 'display' );
    $fields['select-option']            = array( 'jquery' => 'select option', 'encode' => 'display' );

    $page_configs[] = array(
        'pages'   => array( 'edit.php' => 'post_type=product&page=product_attributes' ),
        'anchors' => array( 'col-container' ),
        'forms'   => array(
            array(
                'form'   => array( 'jquery' => 'form[action^="edit.php"]' ),
                'fields' => array(
                    array( 'id' => 'attribute_label' ),
                    array( 'jquery' => 'td a', 'container_id' => 'col-right', 'encode' => 'display' ),
                    array(
                        'jquery'       => 'td.attribute-terms',
                        'container_id' => 'col-right',
                        'encode'       => 'display'
                    )
                )
            )
        )
    );

    $page_configs[] = array(
        'pages' => array( 'admin.php' => 'page=wc-settings&tab=tax' ),
        'forms' => array(
            array(
                'form'   => array( 'id' => 'mainform' ),
                'fields' => array(
                    array( 'jquery' => '.subsubsub', 'encode' => 'display' ),
                    array( 'id' => 'woocommerce_tax_classes', 'encode' => 'byline' ),
                    array( 'id' => 'woocommerce_price_display_suffix' )
                )
            )
        )
    );

    $page_configs[] = array(
        'pages' => array( 'admin.php' => 'page=wc-settings&tab=checkout&section=bacs' ),
        'forms' => array(
            array(
                'form'   => array( 'id' => 'mainform' ),
                'fields' => array(
                    array( 'id' => 'woocommerce_bacs_title' ),
                    array( 'id' => 'woocommerce_bacs_description' ),
                    array( 'id' => 'woocommerce_bacs_instructions' )
                )
            )
        )
    );

    $page_configs[] = array(
        'pages' => array( 'admin.php' => 'page=wc-settings&tab=checkout&section=cheque' ),
        'forms' => array(
            array(
                'form'   => array( 'id' => 'mainform' ),
                'fields' => array(
                    array( 'id' => 'woocommerce_cheque_title' ),
                    array( 'id' => 'woocommerce_cheque_description' ),
                    array( 'id' => 'woocommerce_cheque_instructions' )
                )
            )
        )
    );

    $page_configs[] = array(
        'pages' => array( 'admin.php' => 'page=wc-settings&tab=checkout&section=cod' ),
        'forms' => array(
            array(
                'form'   => array( 'id' => 'mainform' ),
                'fields' => array(
                    array( 'id' => 'woocommerce_cod_title' ),
                    array( 'id' => 'woocommerce_cod_description' ),
                    array( 'id' => 'woocommerce_cod_instructions' )
                )
            )
        )
    );

    $page_configs[] = array(
        'pages' => array( 'admin.php' => 'page=wc-settings&tab=checkout&section=paypal' ),
        'forms' => array(
            array(
                'form'   => array( 'id' => 'mainform' ),
                'fields' => array(
                    array( 'id' => 'woocommerce_paypal_title' ),
                    array( 'id' => 'woocommerce_paypal_description' ),
                    array( 'id' => 'woocommerce_paypal_instructions' )
                )
            )
        )
    );

    // Support for WooCommerce PayPal Checkout extension
    $page_configs[] = array(
        'pages' => array( 'admin.php' => 'page=wc-settings&tab=checkout&section=ppec_paypal' ),
        'forms' => array(
            array(
                'form'   => array( 'id' => 'mainform' ),
                'fields' => array(
                    array( 'id' => 'woocommerce_ppec_paypal_title' ),
                    array( 'id' => 'woocommerce_ppec_paypal_description' ),
                )
            )
        )
    );

    $page_configs[] = array(
        'pages' => array( 'admin.php' => 'page=wc-settings&tab=account' ),
        'forms' => array(
            array(
                'form'   => array( 'id' => 'mainform' ),
                'fields' => array(
                    array( 'id' => 'woocommerce_registration_privacy_policy_text' ),
                    array( 'id' => 'woocommerce_checkout_privacy_policy_text' )
                )
            )
        )
    );

    // TODO fix tab=shipping, these fields are not static anymore, they have to be handled dynamically in JS
    // $fields[] = array( 'id' => 'woocommerce_free_shipping_title' );
    // $fields[] = array( 'id' => 'woocommerce_flat_rate_title' );
    // $fields[] = array( 'id' => 'woocommerce_international_delivery_title' );
    // $fields[] = array( 'id' => 'woocommerce_local_delivery_title' );
    // $fields[] = array( 'id' => 'woocommerce_local_pickup_title' );

    $page_configs[] = array(
        'pages' => array( 'admin.php' => 'page=wc-settings&tab=email(&section=|)$' ),
        'forms' => array(
            array(
                'form'   => array( 'id' => 'mainform' ),
                'fields' => array(
                    array( 'id' => 'woocommerce_email_from_name' ),
                    array( 'id' => 'woocommerce_email_footer_text' )
                )
            )
        )
    );

    $page_configs[] = array(
        'pages' => array( 'admin.php' => 'page=wc-settings&tab=email&section=wc_email' ),
        'forms' => array(
            array(
                'form'   => array( 'id' => 'mainform' ),
                'fields' => array(
                    array( 'jquery' => 'input.input-text[type=text][name^=woocommerce_][name$=_subject]' ),
                    array( 'jquery' => 'input.input-text[type=text][name^=woocommerce_][name$=_heading]' ),
                    array( 'jquery' => 'input.input-text[type=text][name^=woocommerce_][name$=_paid]' ),
                    array( 'jquery' => 'input.input-text[type=text][name^=woocommerce_][name*=refunded]' ),
                    array( 'jquery' => 'textarea[type=textarea][name^=woocommerce_][name$=_additional_content]' ),
                    array( 'id' => 'woocommerce_email_footer_text' )
                )
            )
        )
    );

    return $page_configs;
}

function qtranxf_wc_email_get_option( $value_translated, $wc_email, $value = null, $key = null, $empty_value = null ) {
    if ( ! $value ) {
        return $value_translated; // so that older WC versions do not get nasty output
    }

    return $value;
}

add_filter( 'woocommerce_email_get_option', 'qtranxf_wc_email_get_option', 0, 4 );

add_filter( 'woocommerce_variation_option_name', 'qtranxf_term_name_encoded', 5 );

/**
 * Append the language to the link for changing the order status, so that mails are sent in the language the customer
 * used during the order process
 *
 * @param string $url
 *
 * @return string
 */
function qtranxf_wc_admin_url_append_language( $url ) {
    if ( strpos( $url, 'action=woocommerce_mark_order_status' ) ) {
        $components = parse_url( $url );
        $params     = array();

        parse_str( $components['query'], $params );

        $order_id      = absint( $params['order_id'] );
        $user_language = get_post_meta( $order_id, '_user_language', true );

        if ( $user_language ) {
            $url .= '&lang=' . $user_language;
        }
    }

    return $url;
}

add_filter( 'admin_url', 'qtranxf_wc_admin_url_append_language' );

/**
 * Append the language to ajax links on the order edit page, so that mails are sent in the language the customer used
 * during the order process
 *
 * @param string $url
 *
 * @return string
 */
function qtranxf_wc_admin_url_append_language_edit_page( $url ) {
    if ( strpos( $url, 'admin-ajax.php' ) === false || ! isset( $_GET['action'] ) || ! isset( $_GET['post'] ) || $_GET['action'] != 'edit' ) {
        return $url;
    }
    $order_id = absint( $_GET['post'] );
    if ( ! $order_id ) {
        return $url;
    }
    $post = get_post( $order_id );
    if ( ! $post ) {
        return $url;
    }
    if ( $post->post_type != 'shop_order' ) {
        return $url;
    }

    $user_language = get_post_meta( $order_id, '_user_language', true );
    if ( $user_language ) {
        return $url . '?lang=' . $user_language;
    }

    return $url;
}

add_filter( 'admin_url', 'qtranxf_wc_admin_url_append_language_edit_page' );

/**
 * Option 'woocommerce_email_from_name' needs to be translated for e-mails, and needs to stay untranslated for settings.
 *
 * @param $val
 *
 * @return array|mixed|string|void
 */
function qtranxf_wc_admin_email_option( $val ) {
    global $q_config;
    global $pagenow;

    switch ( $pagenow ) {
        case 'admin-ajax.php':
        case 'post.php':
            return qtranxf_use( $q_config['language'], $val, false, false );
        case 'admin.php'://for sure off
        default:
            return $val;
    }
}

add_filter( 'option_woocommerce_email_from_name', 'qtranxf_wc_admin_email_option' );

/**
 * This helps to use order's language on re-sent emails from post.php order edit page.
 *
 * @param $content
 * @param WC_Order|null $order
 *
 * @return array|mixed|string|void
 */
function qtranxf_wc_admin_email_translate( $content, $order = null ) {
    global $q_config;

    $lang = null;
    if ( $order && $order->get_id() ) {
        $lang = get_post_meta( $order->get_id(), '_user_language', true );
    }
    if ( ! $lang ) {
        $lang = $q_config['language'];
    }

    return qtranxf_use( $lang, $content, false, false );
}

add_filter( 'woocommerce_email_order_items_table', 'qtranxf_wc_admin_email_translate', 20, 2 );

/**
 * Called to process action when button 'Save Order' pressed in /wp-admin/post.php?post=xxx&action=edit
 * Helps to partly change language in email sent, but not all, since some parts are already translated into admin language.
 *
 * @param WC_Order $order
 */
function qtranxf_wc_admin_before_resend_order_emails( $order ): void {
    if ( ! ( $order && $order->get_id() ) ) {
        return;
    }

    $lang = get_post_meta( $order->get_id(), '_user_language', true );
    if ( ! $lang ) {
        return;
    }

    global $q_config;
    $q_config['language'] = $lang;
}

add_action( 'woocommerce_before_resend_order_emails', 'qtranxf_wc_admin_before_resend_order_emails' );

/**
 * Undo the effect of qtranxf_wc_admin_before_resend_order_emails
 */
function qtranxf_wc_admin_after_resend_order_emails( $order ): void {
    global $q_config;
    $q_config['language'] = $q_config['url_info']['language'];
}

add_action( 'woocommerce_after_resend_order_email', 'qtranxf_wc_admin_after_resend_order_emails' );

function qtranxf_wc_admin_filters(): void {
    global $pagenow;
    switch ( $pagenow ) {
        case 'admin.php':
            if ( isset( $_SERVER['QUERY_STRING'] ) && strpos( $_SERVER['QUERY_STRING'], 'page=wc-settings&tab=checkout' ) !== false ) {
                qtranxf_add_filters( [ 'text' => [ 'woocommerce_gateway_title' => 5 ] ] );
            }
            break;
        case 'edit.php':
            // translate column 'product_cat'
            if ( isset( $_SERVER['QUERY_STRING'] )
                 && strpos( $_SERVER['QUERY_STRING'], 'post_type=product' ) !== false
            ) {
                qtranxf_add_filters( [ 'text' => [ 'get_term' => 6 ] ] );
            }
            break;
    }
}

qtranxf_wc_admin_filters();
