<?php

function correct_message(string $message, string $main_language, mixed $message_map):string
{
    foreach ($message_map as $item) {
        $from = $item['from'];
        $to = $item['to'];

        foreach ($from as $lang => $map_string) {
            if ($lang == $main_language or !isset($to[$main_language])) {
                break;
            }
            $message = str_replace($from[$lang], $to[$main_language], $message);
            break;
        }
    }
    return $message;
}

function correct_subject(string $subject, string $main_language, array $subject_map): string
{
    foreach ($subject_map as $item) {
        $from = $item['from'];
        $to = $item['to'];

        foreach ($from as $lang => $template_string) {
            if ($lang == $main_language OR !isset($to[$main_language])) {
                break;
            }

            if (compare_subjects($subject, $template_string)) {
                $order_number = extract_number_by_pattern($subject, '/\d+/');
                return str_replace('{number}', $order_number, $to[$main_language]);
            }

            break;
        }
    }
    return $subject;
}

function extract_number_by_pattern(string $subject, string $pattern, int $match_number = 0): int|bool
{
    if (preg_match($pattern, $subject, $matches)) {
        return $matches[$match_number];
    }
    return false;
}

function compare_subjects(string $user_string, string $map_string): bool
{
    $escaped_map_string = preg_quote($map_string, '/');
    $pattern = '/^' . str_replace('\{number\}', '\d+', $escaped_map_string) . '$/';

    if (preg_match($pattern, $user_string)) {
        return true;
    }
    return false;
}

function determine_language(string $email):string|bool
{
    global $wpdb;

    $post_ids =
        $wpdb->get_results(
            $wpdb->prepare(
                '
            SELECT post_id FROM wp_postmeta 
            WHERE  meta_key = "_billing_email"  AND meta_value = %s ORDER BY post_id DESC LIMIT 1', $email
            )
        );
    if(empty($post_ids)) {
        return false;
    }
    $post_id = $post_ids[0]->post_id;

    $langs =
        $wpdb->get_results(
            $wpdb->prepare(
                '
        SELECT meta_value FROM wp_postmeta 
        WHERE  post_id = %s AND meta_key = "wpml_language"', $post_id
            )
        );

    if(empty($langs)) {
        return false;
    }
    return $langs[0]->meta_value;
}