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

/**
 * @return string
 */
function elementsell_get_vendor_mailer_autoload_path() {
    return dirname( __DIR__, 2 ) . '/vendor_mailer/autoload.php';
}

/**
 * @return bool
 */
function elementsell_email_vendor_mailer_available() {
    return file_exists( elementsell_get_vendor_mailer_autoload_path() );
}

/**
 * @return void
 */
function elementsell_reset_last_email_send_meta() {
    $GLOBALS['elementsell_last_email_send_meta'] = [
        'transport'              => '',
        'from_email'             => '',
        'reply_to'               => '',
        'error'                  => '',
        'deliverability_warning' => '',
    ];
    unset( $GLOBALS['elementsell_last_wp_mail_error'] );
}

/**
 * @return array{transport: string, from_email: string, reply_to: string, error: string, deliverability_warning: string}
 */
function elementsell_get_last_email_send_meta() {
    if ( ! isset( $GLOBALS['elementsell_last_email_send_meta'] ) || ! is_array( $GLOBALS['elementsell_last_email_send_meta'] ) ) {
        elementsell_reset_last_email_send_meta();
    }

    return $GLOBALS['elementsell_last_email_send_meta'];
}

/**
 * @param array<string, string> $data
 * @return void
 */
function elementsell_set_last_email_send_meta( array $data ) {
    $meta = elementsell_get_last_email_send_meta();

    foreach ( $data as $key => $value ) {
        if ( array_key_exists( $key, $meta ) ) {
            $meta[ $key ] = (string) $value;
        }
    }

    $GLOBALS['elementsell_last_email_send_meta'] = $meta;
}

/**
 * @param WP_Error $error
 * @return void
 */
function elementsell_capture_wp_mail_failed( $error ) {
    if ( ! $error instanceof WP_Error ) {
        return;
    }

    $GLOBALS['elementsell_last_wp_mail_error'] = $error->get_error_message();
    elementsell_set_last_email_send_meta(
        [
            'error' => (string) $error->get_error_message(),
        ]
    );
}

add_action( 'wp_mail_failed', 'elementsell_capture_wp_mail_failed' );

/**
 * @param string $email
 * @return bool
 */
function elementsell_email_is_gmail_address( $email ) {
    $domain = elementsell_email_get_domain( $email );

    return in_array( $domain, [ 'gmail.com', 'googlemail.com' ], true );
}

/**
 * @param string $email
 * @param string $app_password
 * @param string $from_name
 * @return array<string, mixed>|null
 */
function elementsell_build_gmail_smtp_config( $email, $app_password, $from_name = '' ) {
    $email        = sanitize_email( (string) $email );
    $app_password = preg_replace( '/\s+/', '', (string) $app_password );

    if ( $email === '' || ! is_email( $email ) || ! elementsell_email_is_gmail_address( $email ) || $app_password === '' ) {
        return null;
    }

    return [
        'host'       => 'smtp.gmail.com',
        'username'   => $email,
        'password'   => $app_password,
        'port'       => 587,
        'secure'     => 'tls',
        'from_email' => $email,
        'from_name'  => trim( (string) $from_name ),
    ];
}

/**
 * Gmail SMTP z nastavení v administraci (ElementSell → Gmail sekce nad fakturami).
 *
 * @return array<string, mixed>|null
 */
function elementsell_get_admin_gmail_smtp_config() {
    $email = sanitize_email( (string) get_option( 'elementsell_gmail_address', '' ) );
    $password = function_exists( 'elementsell_get_gmail_app_password' )
        ? elementsell_get_gmail_app_password()
        : preg_replace( '/\s+/', '', (string) get_option( 'elementsell_gmail_app_password', '' ) );

    return elementsell_build_gmail_smtp_config( $email, $password );
}

/**
 * @deprecated 3.2.4 Použijte elementsell_get_admin_gmail_smtp_config().
 * @param array|null $context
 * @return array<string, mixed>|null
 */
function elementsell_get_widget_gmail_smtp_config( $context = null ) {
    return elementsell_get_admin_gmail_smtp_config();
}

/**
 * Admin Gmail SMTP z nastavení v administraci.
 *
 * @param array|null $config
 * @return array|null
 */
function elementsell_filter_email_smtp_config_from_admin_gmail( $config ) {
    if ( is_array( $config ) && ! empty( $config['host'] ) ) {
        return $config;
    }

    $admin_config = elementsell_get_admin_gmail_smtp_config();

    return is_array( $admin_config ) ? $admin_config : $config;
}

add_filter( 'elementsell_email_smtp_config', 'elementsell_filter_email_smtp_config_from_admin_gmail', 5, 1 );

/**
 * SMTP konfigurace přes filtr elementsell_email_smtp_config (Gmail zákazníka).
 * Lokální override jen pro vývoj (mu-plugin / email-smtp-config.php, ten není v distribuci ZIP).
 *
 * @return array|null
 */
function elementsell_get_email_smtp_config() {
    $config = apply_filters( 'elementsell_email_smtp_config', null );

    if ( ! is_array( $config ) ) {
        return null;
    }

    $host     = trim( (string) ( $config['host'] ?? '' ) );
    $username = trim( (string) ( $config['username'] ?? '' ) );
    $password = (string) ( $config['password'] ?? '' );

    if ( $host === '' || $username === '' || $password === '' ) {
        return null;
    }

    return [
        'host'       => $host,
        'username'   => $username,
        'password'   => $password,
        'port'       => isset( $config['port'] ) ? (int) $config['port'] : 587,
        'secure'     => isset( $config['secure'] ) ? (string) $config['secure'] : 'tls',
        'from_email' => trim( (string) ( $config['from_email'] ?? $username ) ),
        'from_name'  => trim( (string) ( $config['from_name'] ?? '' ) ),
    ];
}

/**
 * @return string
 */
function elementsell_email_get_site_domain() {
    $host = wp_parse_url( home_url( '/' ), PHP_URL_HOST );

    return is_string( $host ) ? strtolower( $host ) : '';
}

/**
 * @param string $email
 * @return string
 */
function elementsell_email_get_domain( $email ) {
    $email = strtolower( sanitize_email( (string) $email ) );
    $at    = strrpos( $email, '@' );

    if ( $at === false ) {
        return '';
    }

    return substr( $email, $at + 1 );
}

/**
 * @param string $email
 * @return bool
 */
function elementsell_email_is_free_mail_domain( $email ) {
    $domain = elementsell_email_get_domain( $email );

    if ( $domain === '' ) {
        return false;
    }

    $free_domains = [
        'gmail.com',
        'googlemail.com',
        'seznam.cz',
        'email.cz',
        'post.cz',
        'centrum.cz',
        'volny.cz',
        'atlas.cz',
        'yahoo.com',
        'outlook.com',
        'hotmail.com',
        'icloud.com',
    ];

    return in_array( $domain, $free_domains, true );
}

/**
 * @param string $from_email
 * @param string $site_domain
 * @return bool
 */
function elementsell_email_from_matches_site_domain( $from_email, $site_domain = '' ) {
    $from_domain = elementsell_email_get_domain( $from_email );

    if ( $from_domain === '' ) {
        return false;
    }

    if ( $site_domain === '' ) {
        $site_domain = elementsell_email_get_site_domain();
    }

    if ( $site_domain === '' ) {
        return true;
    }

    $suffix = '.' . $site_domain;

    return $from_domain === $site_domain
        || ( $suffix !== '.' && substr( $from_domain, -strlen( $suffix ) ) === $suffix );
}

/**
 * Odesílatel (From) — Gmail z administrace, jinak admin e-mail webu (wp_mail).
 *
 * @param string $email_from_hint zachováno kvůli filtru elementsell_email_from_address
 * @return string
 */
function elementsell_get_email_from_address( $email_from_hint = '' ) {
    $filtered = apply_filters( 'elementsell_email_from_address', null, $email_from_hint );

    if ( $filtered !== null ) {
        $filtered = sanitize_email( (string) $filtered );

        if ( $filtered !== '' && is_email( $filtered ) ) {
            return $filtered;
        }
    }

    $admin_smtp = elementsell_get_admin_gmail_smtp_config();

    if ( $admin_smtp && ! empty( $admin_smtp['from_email'] ) && is_email( $admin_smtp['from_email'] ) ) {
        return sanitize_email( (string) $admin_smtp['from_email'] );
    }

    $admin_email = sanitize_email( (string) get_option( 'admin_email', '' ) );

    if ( $admin_email !== '' && is_email( $admin_email ) ) {
        return $admin_email;
    }

    return '';
}

/**
 * Hint pro Reply-To u testovacího e-mailu — Gmail / kontaktní e-mail z faktur.
 *
 * @return string
 */
function elementsell_get_test_email_reply_to_hint() {
    if ( function_exists( 'elementsell_get_invoice_supplier_email' ) ) {
        $email = sanitize_email( elementsell_get_invoice_supplier_email() );

        if ( $email !== '' && is_email( $email ) ) {
            return $email;
        }
    }

    return '';
}

/**
 * Automatické jméno odesílatele e-mailů (bez ručního nastavení ve widgetu).
 *
 * Pořadí: faktury_jmeno → název webu → první administrátor → legacy z objednávky.
 * Legacy se použije jen pokud faktury_jmeno i název webu jsou prázdné.
 *
 * @param string $legacy_name Hodnota z uložené objednávky / starého widgetu.
 * @return string
 */
function elementsell_get_sender_name( $legacy_name = '' ) {
    if ( function_exists( 'elementsell_get_widget_email_from_name_default' ) ) {
        $invoice_name = elementsell_get_widget_email_from_name_default();
    } else {
        $invoice_name = trim( (string) get_option( 'faktury_jmeno', '' ) );

        if ( $invoice_name === '' ) {
            $invoice_name = trim( (string) get_bloginfo( 'name' ) );
        }
    }

    if ( $invoice_name !== '' ) {
        return $invoice_name;
    }

    $admins = get_users(
        [
            'role'    => 'administrator',
            'number'  => 1,
            'orderby' => 'ID',
            'order'   => 'ASC',
            'fields'  => [ 'display_name' ],
        ]
    );

    if ( ! empty( $admins[0] ) ) {
        $admin_name = trim( (string) $admins[0]->display_name );

        if ( $admin_name !== '' ) {
            return $admin_name;
        }
    }

    $legacy = trim( (string) $legacy_name );

    if ( $legacy !== '' ) {
        return $legacy;
    }

    return 'Platební formulář';
}

/**
 * Jméno odesílatele pro konkrétní objednávku.
 * Hodnota z widgetu má prioritu; prázdné pole použije automatické jméno.
 *
 * @param int $order_id
 * @return string
 */
function elementsell_get_order_sender_name( $order_id ) {
    $legacy = function_exists( 'elementsell_get_order_field' )
        ? trim( (string) elementsell_get_order_field( (int) $order_id, 'email_from_name' ) )
        : '';

    if ( $legacy !== '' && ( ! function_exists( 'elementsell_is_legacy_widget_sender_name' ) || ! elementsell_is_legacy_widget_sender_name( $legacy ) ) ) {
        return $legacy;
    }

    return elementsell_get_sender_name();
}

/**
 * Jméno odesílatele pro test doručení.
 *
 * @return string
 */
function elementsell_get_test_email_from_name() {
    global $wpdb;

    $legacy      = '';
    $fields_table = $wpdb->prefix . 'elementsell_order_fields';
    $orders_table = $wpdb->prefix . 'elementsell_orders';

    $stored = $wpdb->get_var(
        "SELECT f.field_value
         FROM {$fields_table} f
         INNER JOIN {$orders_table} o ON o.id = f.order_id
         WHERE f.field_name = 'email_from_name'
           AND f.field_value != ''
         ORDER BY o.id DESC
         LIMIT 1"
    );

    if ( is_string( $stored ) ) {
        $legacy = trim( $stored );
    }

    return elementsell_get_sender_name( $legacy );
}

/**
 * Předmět a HTML tělo testovacího e-mailu ve stejném formátu jako po platbě.
 *
 * @return array{subject: string, message: string}
 */
function elementsell_build_test_delivery_email() {
    $subject = 'Test: doručení e-mailu (ElementSell)';
    $body = "Toto je testovací e-mail ve stejném formátu jako zpráva po úspěšné platbě.\n\n"
        . 'Pokud tento e-mail vidíte ve schránce (ne ve spamu), doručení funguje správně.';

    if ( function_exists( 'elementsell_format_email_body_with_blocks' ) ) {
        $body = elementsell_format_email_body_with_blocks( $body );
    }

    $message = function_exists( 'elementsell_email_template' )
        ? elementsell_email_template( $subject, $body, false )
        : wpautop( wp_kses_post( $body ) );

    return [
        'subject' => $subject,
        'message' => $message,
    ];
}

/**
 * Reply-To pro odpovědi zákazníků — Gmail / kontaktní e-mail z faktur, pak admin e-mail.
 *
 * @param string $reply_to_hint zachováno kvůli kompatibilitě
 * @return string
 */
function elementsell_get_email_reply_to_address( $reply_to_hint = '' ) {
    $filtered = apply_filters( 'elementsell_email_reply_to_address', null, $reply_to_hint );

    if ( $filtered !== null ) {
        $filtered = sanitize_email( (string) $filtered );

        if ( $filtered !== '' && is_email( $filtered ) ) {
            return $filtered;
        }
    }

    if ( function_exists( 'elementsell_get_invoice_supplier_email' ) ) {
        $contact_email = sanitize_email( elementsell_get_invoice_supplier_email() );

        if ( $contact_email !== '' && is_email( $contact_email ) ) {
            return $contact_email;
        }
    }

    $reply_to_hint = sanitize_email( (string) $reply_to_hint );

    if ( $reply_to_hint !== '' && is_email( $reply_to_hint ) ) {
        return $reply_to_hint;
    }

    $admin_email = sanitize_email( (string) get_option( 'admin_email', '' ) );

    if ( $admin_email !== '' && is_email( $admin_email ) ) {
        return $admin_email;
    }

    return '';
}

/**
 * @return bool
 */
function elementsell_email_has_external_smtp_plugin() {
    return defined( 'WPMS_PLUGIN_FILE' )
        || class_exists( 'Postman', false )
        || class_exists( 'EasyWPSMTP', false )
        || defined( 'FLUENTMAIL' );
}

/**
 * @return string
 */
function elementsell_email_get_deliverability_notice() {
    if ( elementsell_get_admin_gmail_smtp_config() !== null ) {
        return '';
    }

    if ( elementsell_email_has_external_smtp_plugin() ) {
        return '';
    }

    return 'E-maily teď jdou přes výchozí WordPress (wp_mail) — doručitelnost bývá horší. Pro spolehlivé doručení napojte Gmail v sekci „Napoj svůj Gmail“.';
}

/**
 * @param string $from_email
 * @param string $reply_to
 * @return string
 */
function elementsell_email_build_deliverability_warning( $from_email, $reply_to ) {
    $warnings = [];

    if ( ! elementsell_email_has_external_smtp_plugin() && elementsell_get_admin_gmail_smtp_config() === null ) {
        $warnings[] = 'Gmail není napojený — e-maily jdou přes wp_mail a mohou mít horší doručitelnost.';
    }

    $reply_to = sanitize_email( (string) $reply_to );

    if ( $reply_to !== '' && elementsell_email_is_free_mail_domain( $reply_to ) ) {
        $warnings[] = sprintf(
            'Odpovědi jdou na %s — zkontrolujte, že Reply-To odpovídá vašemu firemnímu e-mailu.',
            $reply_to
        );
    }

    return implode( ' ', $warnings );
}

/**
 * @param array<int, string> $headers
 * @return array<int, string>
 */
function elementsell_email_normalize_headers( $headers ) {
    $normalized = [];
    $has_type   = false;

    foreach ( (array) $headers as $header ) {
        $header = trim( (string) $header );

        if ( $header === '' ) {
            continue;
        }

        if ( stripos( $header, 'content-type:' ) === 0 ) {
            if ( $has_type ) {
                continue;
            }

            $has_type = true;
        }

        if ( stripos( $header, 'from:' ) === 0 ) {
            continue;
        }

        $normalized[] = $header;
    }

    if ( ! $has_type ) {
        $normalized[] = 'Content-Type: text/html; charset=UTF-8';
    }

    return $normalized;
}

/**
 * @param string       $to
 * @param string       $subject
 * @param string       $message
 * @param array        $headers
 * @param array        $attachments
 * @param string       $from_name
 * @param string       $from_email
 * @param string       $reply_to
 * @param array        $smtp_config
 * @return bool
 */
function elementsell_send_email_via_phpmailer( $to, $subject, $message, $attachments, $from_name, $from_email, $reply_to, $smtp_config ) {
    if ( ! elementsell_email_vendor_mailer_available() ) {
        elementsell_set_last_email_send_meta(
            [
                'error' => 'PHPMailer není k dispozici.',
            ]
        );

        return false;
    }

    require_once elementsell_get_vendor_mailer_autoload_path();

    try {
        $mail = new \PHPMailer\PHPMailer\PHPMailer( true );

        $mail->isSMTP();
        $mail->Host       = $smtp_config['host'];
        $mail->SMTPAuth   = true;
        $mail->Username   = $smtp_config['username'];
        $mail->Password   = $smtp_config['password'];
        $mail->SMTPSecure = $smtp_config['secure'] === 'ssl'
            ? \PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS
            : \PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = (int) $smtp_config['port'];
        $mail->CharSet    = 'UTF-8';
        $mail->isHTML( true );

        $sender_name = trim( (string) $from_name );
        if ( $sender_name === '' ) {
            $sender_name = elementsell_get_sender_name();
        }
        if ( $sender_name === '' && ! empty( $smtp_config['from_name'] ) ) {
            $sender_name = trim( (string) $smtp_config['from_name'] );
        }

        $sender_email = sanitize_email( (string) $from_email );
        if ( $sender_email === '' || ! is_email( $sender_email ) ) {
            $sender_email = sanitize_email( (string) $smtp_config['from_email'] );
        }

        $mail->setFrom( $sender_email, $sender_name );
        $mail->addAddress( $to );

        $reply_address = sanitize_email( (string) $reply_to );
        if ( $reply_address !== '' && is_email( $reply_address ) ) {
            $mail->addReplyTo( $reply_address, $sender_name );
        }

        $mail->Subject = $subject;
        $mail->Body    = $message;

        if ( ! empty( $attachments ) && is_array( $attachments ) ) {
            foreach ( $attachments as $attachment ) {
                if ( file_exists( $attachment ) ) {
                    $mail->addAttachment( $attachment, basename( $attachment ) );
                } else {
                    error_log( 'ElementSell email: příloha neexistuje: ' . $attachment );
                }
            }
        }

        $mail->send();

        return true;
    } catch ( Exception $e ) {
        $error_message = $e->getMessage();
        error_log( 'ElementSell email SMTP chyba: ' . $error_message );
        elementsell_set_last_email_send_meta(
            [
                'error' => $error_message,
            ]
        );

        return false;
    }
}

/**
 * @param string $to
 * @param string $subject
 * @param string $message
 * @param array  $headers
 * @param array  $attachments
 * @param string $from_name
 * @param string $from_email
 * @param string $reply_to
 * @return bool
 */
function elementsell_email_configure_phpmailer( $phpmailer ) {
    if ( ! is_object( $phpmailer ) ) {
        return;
    }

    $domain = elementsell_email_get_site_domain();

    if ( $domain === '' ) {
        $domain = 'localhost.localdomain';
    }

    if ( empty( $phpmailer->MessageID ) ) {
        $phpmailer->MessageID = '<es-' . uniqid( '', true ) . '@' . $domain . '>';
    }

    if ( stripos( (string) $phpmailer->ContentType, 'text/html' ) !== false && trim( (string) $phpmailer->AltBody ) === '' ) {
        $phpmailer->AltBody = wp_strip_all_tags( (string) $phpmailer->Body );
    }
}

/**
 * @param string $to
 * @param string $subject
 * @param string $message
 * @param array  $headers
 * @param array  $attachments
 * @param string $from_name
 * @param string $from_email
 * @param string $reply_to
 * @return bool
 */
function elementsell_send_email_via_wp_mail( $to, $subject, $message, $headers, $attachments, $from_name, $from_email, $reply_to ) {
    $mail_headers = elementsell_email_normalize_headers( $headers );

    $sender_name = trim( (string) $from_name );
    if ( $sender_name === '' ) {
        $sender_name = elementsell_get_sender_name();
    }

    $from_address  = sanitize_email( (string) $from_email );
    $reply_address = sanitize_email( (string) $reply_to );

    if ( $reply_address === '' || ! is_email( $reply_address ) ) {
        $reply_address = elementsell_get_email_reply_to_address();
    }

    if ( $reply_address !== '' && is_email( $reply_address ) ) {
        $mail_headers[] = 'Reply-To: ' . $reply_address;
    }

    $from_filter = static function () use ( $from_address ) {
        return $from_address;
    };
    $name_filter = static function () use ( $sender_name ) {
        return $sender_name;
    };

    if ( $from_address !== '' && is_email( $from_address ) ) {
        add_filter( 'wp_mail_from', $from_filter, 999 );
        add_filter( 'wp_mail_from_name', $name_filter, 999 );
    }

    add_action( 'phpmailer_init', 'elementsell_email_configure_phpmailer', 20 );

    unset( $GLOBALS['elementsell_last_wp_mail_error'] );

    $sent = wp_mail( $to, $subject, $message, $mail_headers, is_array( $attachments ) ? $attachments : [] );

    remove_action( 'phpmailer_init', 'elementsell_email_configure_phpmailer', 20 );

    if ( $from_address !== '' && is_email( $from_address ) ) {
        remove_filter( 'wp_mail_from', $from_filter, 999 );
        remove_filter( 'wp_mail_from_name', $name_filter, 999 );
    }

    if ( ! $sent ) {
        $error_message = isset( $GLOBALS['elementsell_last_wp_mail_error'] )
            ? (string) $GLOBALS['elementsell_last_wp_mail_error']
            : 'wp_mail vrátilo false';

        error_log( 'ElementSell email wp_mail selhalo pro ' . $to . ': ' . $error_message );
        elementsell_set_last_email_send_meta(
            [
                'error' => $error_message,
            ]
        );

        return false;
    }

    if ( ! empty( $GLOBALS['elementsell_last_wp_mail_error'] ) ) {
        $error_message = (string) $GLOBALS['elementsell_last_wp_mail_error'];
        error_log( 'ElementSell email wp_mail hlásí chybu pro ' . $to . ': ' . $error_message );
        elementsell_set_last_email_send_meta(
            [
                'error' => $error_message,
            ]
        );

        return false;
    }

    return true;
}

/**
 * @param string $to
 * @param string $subject
 * @param string $message
 * @param array  $headers
 * @param array  $attachments
 * @param string $from_name
 * @param string $reply_to
 * @return bool
 */
function elementsell_send_email( $to, $subject, $message, $headers = [], $attachments = [], $from_name = '', $reply_to = '' ) {
    elementsell_reset_last_email_send_meta();

    $to            = sanitize_email( (string) $to );
    $reply_to_hint = sanitize_email( (string) $reply_to );

    if ( $to === '' || ! is_email( $to ) ) {
        elementsell_set_last_email_send_meta(
            [
                'error' => 'Neplatná příjemce: ' . (string) $to,
            ]
        );

        return false;
    }

    $admin_smtp = elementsell_get_admin_gmail_smtp_config();

    if ( $admin_smtp !== null ) {
        $from_address     = elementsell_get_email_from_address( $reply_to_hint );
        $reply_to_address = elementsell_get_email_reply_to_address( $reply_to_hint );

        elementsell_set_last_email_send_meta(
            [
                'from_email'             => $from_address,
                'reply_to'               => $reply_to_address,
                'deliverability_warning' => elementsell_email_build_deliverability_warning( $from_address, $reply_to_address ),
            ]
        );

        if ( $from_address === '' || ! is_email( $from_address ) ) {
            elementsell_set_last_email_send_meta(
                [
                    'error' => 'Chybí platná adresa odesílatele (From).',
                ]
            );

            return false;
        }

        $warning = elementsell_get_last_email_send_meta()['deliverability_warning'];

        if ( $warning !== '' ) {
            error_log( 'ElementSell email deliverability: ' . $warning );
        }

        if ( trim( (string) $from_name ) === '' && ! empty( $admin_smtp['from_name'] ) ) {
            $from_name = (string) $admin_smtp['from_name'];
        }

        $sent = elementsell_send_email_via_phpmailer(
            $to,
            $subject,
            $message,
            $attachments,
            $from_name,
            $from_address,
            $reply_to_address,
            $admin_smtp
        );

        if ( $sent ) {
            elementsell_set_last_email_send_meta(
                [
                    'transport' => 'smtp_gmail',
                    'error'     => '',
                ]
            );

            return true;
        }
    }

    $from_address     = elementsell_get_email_from_address( $reply_to_hint );
    $reply_to_address = elementsell_get_email_reply_to_address( $reply_to_hint );

    elementsell_set_last_email_send_meta(
        [
            'from_email'             => $from_address,
            'reply_to'               => $reply_to_address,
            'deliverability_warning' => elementsell_email_build_deliverability_warning( $from_address, $reply_to_address ),
        ]
    );

    if ( $from_address === '' || ! is_email( $from_address ) ) {
        elementsell_set_last_email_send_meta(
            [
                'error' => 'Chybí platná adresa odesílatele (From).',
            ]
        );

        return false;
    }

    $warning = elementsell_get_last_email_send_meta()['deliverability_warning'];

    if ( $warning !== '' ) {
        error_log( 'ElementSell email deliverability: ' . $warning );
    }

    if ( ! apply_filters( 'elementsell_email_use_wp_mail_fallback', true ) ) {
        return false;
    }

    $sent = elementsell_send_email_via_wp_mail(
        $to,
        $subject,
        $message,
        $headers,
        $attachments,
        $from_name,
        $from_address,
        $reply_to_address
    );

    if ( $sent ) {
        elementsell_set_last_email_send_meta(
            [
                'transport' => 'wp_mail',
                'error'     => '',
            ]
        );

        return true;
    }

    return false;
}
