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

/**
 * Krátké upozornění majiteli na zaplacenou objednávku (self-send na Gmail z administrace).
 *
 * @param object|null $order
 * @return bool
 */
function elementsell_send_paid_order_notification( $order ) {
    if ( ! $order || empty( $order->id ) ) {
        return false;
    }

    if ( (int) get_option( 'elementsell_gmail_disable_paid_notifications', 0 ) ) {
        return false;
    }

    if ( ! function_exists( 'elementsell_gmail_smtp_is_configured' ) || ! elementsell_gmail_smtp_is_configured() ) {
        return false;
    }

    $order_id = (int) $order->id;

    if ( ! empty( elementsell_get_order_field( $order_id, 'paid_admin_notification_sent_at' ) ) ) {
        return false;
    }

    if ( ! elementsell_claim_merchant_paid_notification( $order_id ) ) {
        return false;
    }

    $to = sanitize_email( (string) get_option( 'elementsell_gmail_address', '' ) );

    if ( $to === '' || ! is_email( $to ) ) {
        return false;
    }

    $product = trim( (string) ( $order->product_name ?? '' ) );

    if ( $product === '' ) {
        $product = '—';
    }

    $amount          = number_format( (float) ( $order->amount ?? 0 ), 0, ',', ' ' ) . ' Kč';
    $customer_email  = sanitize_email( (string) ( $order->email ?? '' ) );
    $customer_label  = $customer_email !== '' && is_email( $customer_email ) ? $customer_email : '—';
    $orders_url      = admin_url( 'admin.php?page=elementsell' );
    $is_landing_lead = function_exists( 'elementsell_get_order_field' )
        && (string) elementsell_get_order_field( $order_id, 'landing_lead' ) === '1';

    if ( $is_landing_lead ) {
        $website = function_exists( 'elementsell_get_order_field' )
            ? trim( (string) elementsell_get_order_field( $order_id, 'website' ) )
            : '';
        $intent  = function_exists( 'elementsell_get_order_field' )
            ? trim( (string) elementsell_get_order_field( $order_id, 'product_intent' ) )
            : '';
        $name    = trim( (string) ( $order->first_name ?? '' ) . ' ' . (string) ( $order->surname ?? '' ) );

        $subject   = 'Nová poptávka z landingu';
        $body_text = sprintf(
            "Jméno: %1\$s\nE-mail: %2\$s\nWeb: %3\$s\nCo bude prodávat: %4\$s\n\n<a href=\"%5\$s\">Objednávky</a>",
            $name !== '' ? $name : '—',
            $customer_label,
            $website !== '' ? $website : '—',
            $intent !== '' ? $intent : $product,
            esc_url( $orders_url )
        );
    } else {
        $subject   = 'Zaplaceno! ' . $amount;
        $body_text = sprintf(
            "Produkt: %1\$s\nČástka: %2\$s\nE-mail zákazníka: %3\$s\n\n<a href=\"%4\$s\">Objednávky</a>",
            $product,
            $amount,
            $customer_label,
            esc_url( $orders_url )
        );
    }

    $body = function_exists( 'elementsell_format_email_body_with_blocks' )
        ? elementsell_format_email_body_with_blocks( $body_text )
        : wpautop( esc_html( $body_text ) );

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

    $from_name = function_exists( 'elementsell_get_sender_name' )
        ? elementsell_get_sender_name()
        : get_bloginfo( 'name' );

    $sent = elementsell_send_email( $to, $subject, $message, [], [], $from_name, '' );

    if ( $sent ) {
        elementsell_upsert_order_field(
            $order_id,
            'paid_admin_notification_sent_at',
            current_time( 'mysql', true )
        );
        elementsell_release_merchant_paid_notification_claim( $order_id );
    } else {
        elementsell_release_merchant_paid_notification_claim( $order_id );
    }

    return $sent;
}

function elementsell_send_paid_email( $order ) {

    $message = elementsell_get_paid_message_for_order( $order );
    $subject = $message['subject'];
    $body    = elementsell_replace_email_html_variables( $message['body'], $order );
    $body    = elementsell_format_email_body_with_blocks( $body );

    $login_block = elementsell_prepare_customer_login_for_order( $order );

    if ( $login_block ) {
        $body .= $login_block;
    }

    $upsell_block = elementsell_build_upsell_email_html( $order );

    if ( $upsell_block ) {
        $body .= $upsell_block;
    }

    $message = elementsell_email_template( $subject, $body );

    $attachments = [];
    $pdf_path    = elementsell_get_invoice_pdf_for_order( (int) $order->id );

    if ( $pdf_path && file_exists( $pdf_path ) ) {
        $attachments[] = $pdf_path;
    }

    $from_name = elementsell_get_order_sender_name( (int) $order->id );

    $result = elementsell_send_email(
        $order->email,
        $subject,
        $message,
        [],
        $attachments,
        $from_name,
        ''
    );

    if ( $result ) {
        $logged = elementsell_log_sent_email(
            $order->id,
            $order->email,
            $subject,
            $message
        );

        if ( false === $logged ) {
            $result = false;
            $error  = 'E-mail byl odeslán, ale nepodařilo se ho zapsat do logu (zkontrolujte tabulku elementsell_email_log).';
            elementsell_save_order_field( (int) $order->id, 'paid_email_error', $error );
            error_log( 'ElementSell: paid email log FAIL pro objednávku ' . (int) $order->id );
        } else {
            elementsell_save_order_field( (int) $order->id, 'paid_email_error', '' );
        }
    } else {
        $meta  = elementsell_get_last_email_send_meta();
        $error = trim( (string) ( $meta['error'] ?? '' ) );

        if ( $error === '' ) {
            $error = 'E-mail se nepodařilo odeslat (wp_mail/SMTP).';
        }

        elementsell_log_failed_email(
            $order->id,
            $order->email,
            $subject,
            $message
        );
        elementsell_save_order_field( (int) $order->id, 'paid_email_error', $error );
        error_log( 'ElementSell: paid email FAIL pro objednávku ' . (int) $order->id . ': ' . $error );
    }

    return $result;
}
