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

add_action( 'admin_post_nopriv_elementsell_thepay_return', 'elementsell_handle_thepay_return' );
add_action( 'admin_post_elementsell_thepay_return', 'elementsell_handle_thepay_return' );

/**
 * @return bool
 */
function elementsell_thepay_return_is_notification() {
    return isset( $_GET['type'] ) && (string) $_GET['type'] !== '';
}

/**
 * @param bool $success
 * @return void
 */
function elementsell_thepay_return_finish( $success = true ) {
    if ( elementsell_thepay_return_is_notification() ) {
        status_header( $success ? 200 : 500 );
        nocache_headers();
        echo $success ? 'OK' : 'ERROR';
        exit;
    }
}

function elementsell_handle_thepay_return() {
    $payment_uid = isset( $_GET['payment_uid'] )
        ? sanitize_text_field( wp_unslash( $_GET['payment_uid'] ) )
        : '';

    if ( $payment_uid === '' ) {
        if ( elementsell_thepay_return_is_notification() ) {
            elementsell_thepay_return_finish( false );
        }

        wp_die( 'Chybí payment_uid.' );
    }

    $order = elementsell_get_order_by_payment_uid( $payment_uid );

    if ( ! $order ) {
        if ( elementsell_thepay_return_is_notification() ) {
            elementsell_thepay_return_finish( false );
        }

        wp_die( 'Objednávka nebyla nalezena pro payment_uid: ' . esc_html( $payment_uid ) );
    }

    try {
        $payment_detail = elementsell_verify_thepay_payment( $order );
        $is_notification = elementsell_thepay_return_is_notification();

        $order = elementsell_apply_thepay_payment_to_order( $order, $payment_detail );

        if ( $is_notification ) {
            elementsell_thepay_return_finish( true );
        }

        wp_safe_redirect( elementsell_get_thank_you_url_for_order( $order ) );
        exit;
    } catch ( Exception $e ) {
        error_log( 'ElementSell ThePay return failed: ' . $e->getMessage() );

        if ( elementsell_thepay_return_is_notification() ) {
            elementsell_thepay_return_finish( false );
        }

        elementsell_save_order_field( (int) $order->id, 'thepay_verify_error', $e->getMessage() );

        wp_safe_redirect( elementsell_get_thank_you_url_for_order( $order ) );
        exit;
    }
}
