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

/**
 * @param int  $order_id
 * @param bool $was_already_paid
 * @return void
 */
function elementsell_complete_paid_order_side_effects( $order_id, $was_already_paid = false ) {
    $order_id = (int) $order_id;

    if ( $order_id <= 0 ) {
        return;
    }

    $order = elementsell_get_order( $order_id );

    if ( ! $order || ! elementsell_is_order_payment_paid( $order ) ) {
        return;
    }

    elementsell_complete_returning_customer_access( $order );

    if ( elementsell_should_send_login_credentials( (int) $order_id ) ) {
        elementsell_setup_customer_account_for_order( $order );
    }

    elementsell_apply_upsell_access_for_order( $order );

    if ( ! $was_already_paid ) {
        elementsell_billing_flush_paid_orders_cache();
        do_action( 'elementsell_order_paid', $order_id );

        if ( function_exists( 'elementsell_send_paid_order_notification' ) ) {
            elementsell_send_paid_order_notification( $order );
        }
    }

    if ( ! elementsell_claim_paid_customer_email_send( $order_id ) ) {
        return;
    }

    $order_for_email = elementsell_get_order( $order_id );

    if ( ! $order_for_email ) {
        $order_for_email = $order;
    }

    $email_sent = elementsell_send_paid_email( $order_for_email );

    if ( $email_sent ) {
        elementsell_upsert_order_field(
            $order_id,
            'paid_email_sent_at',
            current_time( 'mysql', true )
        );
        elementsell_upsert_order_field( $order_id, 'paid_email_error', '' );
        elementsell_release_paid_customer_email_claim( $order_id );
    } else {
        elementsell_release_paid_customer_email_claim( $order_id );

        $meta  = function_exists( 'elementsell_get_last_email_send_meta' ) ? elementsell_get_last_email_send_meta() : [];
        $error = trim( (string) ( $meta['error'] ?? '' ) );

        if ( $error !== '' ) {
            elementsell_upsert_order_field( $order_id, 'paid_email_error', $error );
        }
    }
}

/**
 * @param object|null $order
 * @return bool
 */
function elementsell_is_order_payment_paid( $order ) {
    return $order && (string) $order->payment_status === 'paid';
}

/**
 * @param object|null $order
 * @return bool
 */
function elementsell_is_order_payment_pending( $order ) {
    if ( ! $order ) {
        return false;
    }

    return in_array(
        (string) $order->payment_status,
        [
            'waiting_for_payment',
            'waiting_for_confirmation',
            'pending',
            'created',
            'payment_created',
        ],
        true
    );
}

/**
 * @param object|null $order
 * @return bool
 */
function elementsell_is_order_payment_failed( $order ) {
    if ( ! $order ) {
        return false;
    }

    return in_array(
        (string) $order->payment_status,
        [
            'expired',
            'failed',
            'refunded',
            'preauth_cancelled',
            'preauth_expired',
        ],
        true
    );
}

/**
 * Odkaz pro dokončení platby v e-mailu (upomínka).
 * ThePay → výběr platební metody, jinak resume URL nebo stránka /diky.
 *
 * @param object $order
 * @return string
 */
function elementsell_get_order_reminder_payment_url( $order ) {
    if ( ! $order ) {
        return '';
    }

    if ( (string) $order->payment_method === 'thepay' && trim( (string) $order->payment_uid ) !== '' ) {
        return elementsell_get_thepay_picker_url( (string) $order->payment_uid );
    }

    if ( (string) $order->payment_method === 'fio' ) {
        $resume_url = elementsell_get_order_payment_resume_url( $order );

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

    $resume_url = elementsell_get_order_payment_resume_url( $order );

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

    return elementsell_get_thank_you_url_for_order( $order );
}

/**
 * @param object $order
 * @return string
 */
function elementsell_get_order_payment_resume_url( $order ) {
    $detail_url = trim( (string) elementsell_get_order_field( (int) $order->id, 'payment_detail_url' ) );

    if ( $detail_url !== '' ) {
        return esc_url_raw( $detail_url );
    }

    $pay_url = trim( (string) $order->pay_url );

    return $pay_url !== '' ? esc_url_raw( $pay_url ) : '';
}

/**
 * @param object               $order
 * @param \ThePay\ApiClient\Model\Payment $payment
 * @return object
 */
function elementsell_apply_thepay_payment_to_order( $order, $payment ) {
    $state       = (string) $payment->getState();
    $method      = (string) $payment->getPaymentMethod();
    $is_paid_now = ( $state === 'paid' );
    $was_first_paid_transition = false;

    if ( $is_paid_now ) {
        $payment_method = $method !== '' ? $method : (string) $order->payment_method;
        $was_first_paid_transition = elementsell_mark_order_payment_paid_atomically(
            (int) $order->id,
            [ 'payment_method' => $payment_method ]
        );

        if (
            ! $was_first_paid_transition
            && elementsell_is_order_payment_paid( $order )
            && $payment_method !== ''
            && $payment_method !== (string) $order->payment_method
        ) {
            elementsell_update_order(
                (int) $order->id,
                [
                    'payment_method' => $payment_method,
                    'updated_at'     => current_time( 'mysql' ),
                ]
            );
        }
    } else {
        elementsell_update_order(
            (int) $order->id,
            [
                'payment_status' => $state,
                'payment_method' => $method !== '' ? $method : (string) $order->payment_method,
                'updated_at'     => current_time( 'mysql' ),
            ]
        );
    }

    $detail_url = (string) $payment->getDetailUrl();

    if ( $detail_url !== '' ) {
        elementsell_save_order_field_once( (int) $order->id, 'payment_detail_url', esc_url_raw( $detail_url ) );
    }

    elementsell_sync_invoice_with_order( (int) $order->id );

    if ( $is_paid_now ) {
        elementsell_complete_paid_order_side_effects( (int) $order->id, ! $was_first_paid_transition );
    }

    $fresh = elementsell_get_order( (int) $order->id );

    return $fresh ? $fresh : $order;
}

/**
 * @param int    $order_id
 * @param string $field_name
 * @param string $field_value
 * @return void
 */
function elementsell_save_order_field_once( $order_id, $field_name, $field_value ) {
    if ( (string) elementsell_get_order_field( $order_id, $field_name ) !== '' ) {
        return;
    }

    elementsell_save_order_field( $order_id, $field_name, $field_value );
}

/**
 * @param object $order
 * @return object
 */
function elementsell_refresh_thepay_order_payment_status( $order ) {
    if ( ! $order || (string) $order->payment_method !== 'thepay' ) {
        return $order;
    }

    try {
        $payment = elementsell_verify_thepay_payment( $order );

        return elementsell_apply_thepay_payment_to_order( $order, $payment );
    } catch ( Exception $e ) {
        error_log( 'ElementSell: refresh ThePay status failed for order ' . (int) $order->id . ': ' . $e->getMessage() );

        return $order;
    }
}

/**
 * @param object $order
 * @return array{title: string, body: string, access: string, actions: string, auto_refresh: bool, tone: string}
 */
function elementsell_get_thank_you_view_for_order( $order ) {
    if ( elementsell_is_order_payment_paid( $order ) ) {
        $message        = elementsell_get_paid_message_for_order( $order );
        $needs_password = elementsell_should_send_login_credentials( (int) $order->id );
        $confirmation   = elementsell_render_thank_you_paid_confirmation();
        $email_body     = trim( (string) $message['body'] );
        $uses_slot      = function_exists( 'elementsell_thank_you_uses_elementor_slot' ) && elementsell_thank_you_uses_elementor_slot();

        if ( $needs_password ) {
            $access = elementsell_render_thank_you_access_section( $order, $email_body );

            // Elementor /diky: shortcode dřív vracel jen access — bez potvrzení vypadá stránka „prázdná“.
            if ( $uses_slot ) {
                $access = $confirmation . $access;
            }

            return [
                'title'        => '',
                'body'         => $uses_slot ? '' : $confirmation,
                'access'       => $access,
                'actions'      => '',
                'auto_refresh' => false,
                'tone'         => 'success',
            ];
        }

        if ( $uses_slot ) {
            $slot = $confirmation;

            if ( $email_body !== '' ) {
                $slot .= '<div class="elementsell-thank-you-access-email">'
                    . wpautop( wp_kses_post( $email_body ) )
                    . '</div>';
            }

            return [
                'title'        => '',
                'body'         => '',
                'access'       => $slot,
                'actions'      => '',
                'auto_refresh' => false,
                'tone'         => 'success',
            ];
        }

        if ( $email_body !== '' ) {
            $confirmation .= '<div class="elementsell-thank-you-body elementsell-thank-you-body--secondary">'
                . wpautop( wp_kses_post( $email_body ) )
                . '</div>';
        }

        return [
            'title'        => '',
            'body'         => $confirmation,
            'access'       => '',
            'actions'      => '',
            'auto_refresh' => false,
            'tone'         => 'success',
        ];
    }

    if ( (string) $order->payment_status === 'waiting_for_confirmation' ) {
        return [
            'title'        => 'Platba se zpracovává',
            'body'         => elementsell_render_thank_you_calm_icon( 'processing' )
                . '<p class="elementsell-thank-you-lead">Platbu jsme přijali a čekáme na potvrzení od banky. Jakmile bude v pořádku, pošleme vám e-mail s přístupem k obsahu. Tuto stránku můžete zavřít.</p>',
            'actions'      => elementsell_render_thank_you_status_actions( $order, false ),
            'auto_refresh' => true,
            'tone'         => 'processing',
        ];
    }

    if ( (string) $order->payment_status === 'expired' ) {
        return [
            'title'        => 'Platba vypršela',
            'body'         => '<p>Čas pro zaplacení této objednávky už uplynul. Vytvořte prosím novou objednávku a zkuste to znovu.</p>',
            'actions'      => elementsell_render_thank_you_status_actions( $order, true ),
            'auto_refresh' => false,
            'tone'         => 'warning',
        ];
    }

    if ( in_array( (string) $order->payment_status, [ 'refunded', 'partially_refunded' ], true ) ) {
        return [
            'title'        => 'Platba byla vrácena',
            'body'         => '<p>K této objednávce byla vrácena platba. Pokud potřebujete pomoc, kontaktujte nás.</p>',
            'actions'      => '',
            'auto_refresh' => false,
            'tone'         => 'neutral',
        ];
    }

    if ( (string) $order->payment_status === 'failed' ) {
        return [
            'title'        => 'Platba se nepovedla',
            'body'         => '<p>Platbu se nepodařilo dokončit. Můžete to zkusit znovu stejným odkazem, nebo vytvořit novou objednávku.</p>',
            'actions'      => elementsell_render_thank_you_status_actions( $order, true ),
            'auto_refresh' => false,
            'tone'         => 'error',
        ];
    }

    return [
        'title'        => 'Čekáme na platbu',
        'body'         => '<p>Objednávku máme zaznamenanou, ale platba zatím nebyla dokončena.</p>'
            . '<p>Pokud jste zvolili bankovní převod, peníze mohou dorazit později — po připsání vám přijde e-mail s přístupem.</p>'
            . '<p>Pokud jste platbu ještě neodeslali, dokončete ji tlačítkem níže.</p>',
        'actions'      => elementsell_render_thank_you_status_actions( $order, true ),
        'auto_refresh' => true,
        'tone'         => 'pending',
    ];
}

/**
 * @return string
 */
function elementsell_render_thank_you_paid_confirmation() {
    return '<div class="elementsell-thank-you-confirm" role="status">'
        . '<div class="elementsell-thank-you-confirm__icon" aria-hidden="true">'
        . '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" aria-hidden="true">'
        . '<circle cx="12" cy="12" r="11" fill="#22C55E"/>'
        . '<path d="M7.5 12.2l3 3 6-6.4" fill="none" stroke="#fff" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/>'
        . '</svg>'
        . '</div>'
        . '<div class="elementsell-thank-you-confirm__text">'
        . '<p class="elementsell-thank-you-confirm__title">Povedlo se!</p>'
        . '<p class="elementsell-thank-you-confirm__subtitle">Platba proběhla v pořádku.</p>'
        . '</div>'
        . '</div>';
}

/**
 * @return string
 */
function elementsell_render_thank_you_success_icon() {
    return '<div class="elementsell-thank-you-mood elementsell-thank-you-mood--success" role="img" aria-label="Platba proběhla úspěšně">'
        . '<div class="elementsell-thank-you-mood__bubble">'
        . '<svg class="elementsell-thank-you-mood__svg" xmlns="http://www.w3.org/2000/svg" width="80" height="80" viewBox="0 0 80 80" aria-hidden="true">'
        . '<circle cx="40" cy="40" r="38" fill="#DCFCE7"/>'
        . '<circle cx="40" cy="40" r="30" fill="#22C55E"/>'
        . '<path d="M27 41.5L36.2 50.5L54 32.5" fill="none" stroke="#fff" stroke-width="4.5" stroke-linecap="round" stroke-linejoin="round"/>'
        . '</svg>'
        . '</div>'
        . '</div>';
}

/**
 * @param string $variant
 * @return string
 */
function elementsell_render_thank_you_calm_icon( $variant = 'processing' ) {
    if ( $variant !== 'processing' ) {
        return '';
    }

    return '<div class="elementsell-thank-you-mood" role="img" aria-label="Platba je na cestě, brzy vám přijde e-mail">'
        . '<div class="elementsell-thank-you-mood__bubble">'
        . '<svg class="elementsell-thank-you-mood__svg" xmlns="http://www.w3.org/2000/svg" width="72" height="72" viewBox="0 0 72 72" aria-hidden="true">'
        . '<circle cx="36" cy="36" r="34" fill="#E8F5E9"/>'
        . '<path d="M18 28c0-2.2 1.8-4 4-4h28c2.2 0 4 1.8 4 4v16c0 2.2-1.8 4-4 4H22c-2.2 0-4-1.8-4-4V28z" fill="#fff" stroke="#4CAF50" stroke-width="2"/>'
        . '<path d="M18 28l18 12 18-12" fill="none" stroke="#4CAF50" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>'
        . '<circle cx="50" cy="22" r="11" fill="#4CAF50"/>'
        . '<path d="M45 22l3.5 3.5L56 18" fill="none" stroke="#fff" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>'
        . '</svg>'
        . '</div>'
        . '</div>';
}

/**
 * @param object $order
 * @param bool   $show_retry
 * @return string
 */
function elementsell_render_thank_you_status_actions( $order, $show_retry ) {
    $html        = '<div class="elementsell-thank-you-actions">';
    $resume_url  = elementsell_get_order_payment_resume_url( $order );
    $source_url  = elementsell_get_order_source_page_url_with_form( $order );

    if ( $show_retry && $resume_url !== '' ) {
        $html .= '<p><a class="elementsell-thank-you-button" href="' . esc_url( $resume_url ) . '">Dokončit platbu</a></p>';
    }

    if ( $source_url !== '' ) {
        $html .= '<p><a class="elementsell-thank-you-link" href="' . esc_url( $source_url ) . '">Zpět na objednávku</a></p>';
    }

    $html .= '</div>';

    return $html;
}

/**
 * @param bool $enabled
 * @return string
 */
function elementsell_render_thank_you_auto_refresh_script( $enabled ) {
    if ( ! $enabled ) {
        return '';
    }

    return '<script>
        setTimeout(function () {
            window.location.reload();
        }, 15000);
    </script>';
}
