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

add_action( 'admin_post_elementsell_billing_start', 'elementsell_handle_billing_token_start' );
add_action( 'admin_post_nopriv_elementsell_billing_return', 'elementsell_handle_billing_token_return' );
add_action( 'admin_post_elementsell_billing_return', 'elementsell_handle_billing_token_return' );

/**
 * @return void
 */
function elementsell_handle_billing_token_start() {
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_die( esc_html__( 'Nemáte oprávnění.', 'platebni-formular' ) );
    }

    check_admin_referer( 'elementsell_billing_start' );

    $card_required = elementsell_is_billing_blocked() || elementsell_billing_is_payment_failed();

    if ( ! $card_required && ! elementsell_billing_are_invoice_details_complete() ) {
        wp_safe_redirect(
            add_query_arg(
                'elementsell_billing_error',
                rawurlencode( 'Nejdřív vyplňte fakturační údaje níže.' ),
                admin_url( 'admin.php?page=elementsell' )
            )
        );
        exit;
    }

    $client = elementsell_billing_get_thepay_client();

    if ( ! $client ) {
        $detail = function_exists( 'elementsell_billing_get_last_credentials_error' )
            ? elementsell_billing_get_last_credentials_error()
            : '';
        $msg    = 'Nepodařilo se připojit k platební bráně.';
        if ( $detail !== '' ) {
            $msg .= ' (' . $detail . ')';
        } else {
            $msg .= ' Server elementsell.cz nevrátil ThePay údaje (credentials.php).';
        }
        wp_die( esc_html( $msg ) );
    }

    $amount      = elementsell_billing_get_card_verification_amount();
    $currency    = 'CZK';
    $payment_uid = uniqid( 'es_', true );
    $return_url  = admin_url( 'admin-post.php?action=elementsell_billing_return' );

    $customer_name  = trim( (string) get_option( 'faktury_jmeno', '' ) );
    $customer_email = function_exists( 'elementsell_get_invoice_supplier_email' )
        ? sanitize_email( elementsell_get_invoice_supplier_email() )
        : sanitize_email( (string) get_option( 'faktury_email', '' ) );

    if ( $customer_name === '' ) {
        $customer_name = get_bloginfo( 'name' );
    }

    if ( $customer_email === '' || ! is_email( $customer_email ) ) {
        $customer_email = sanitize_email( (string) get_option( 'admin_email' ) );
    }

    $customer = new \ThePay\ApiClient\Model\CreatePaymentCustomer(
        $customer_name,
        '',
        $customer_email,
        null,
        elementsell_billing_create_thepay_address()
    );

    $params = new \ThePay\ApiClient\Model\CreatePaymentParams( $amount, $currency, $payment_uid );
    $params->setOrderId( 'elementsell-card-' . time() );
    $params->setDescriptionForCustomer( 'Ověření platební karty pro ElementSell' );
    $params->setCustomer( $customer );
    $params->setReturnUrl( $return_url );
    $params->setSaveAuthorization( true );

    try {
        $payment_response = $client->createPayment( $params );
        $pay_url          = $payment_response->getPayUrl();

        update_option( 'elementsell_p_payment_uid', sanitize_text_field( $payment_uid ) );

        wp_redirect( $pay_url );
        exit;
    } catch ( Exception $e ) {
        wp_die( esc_html( 'Chyba při vytváření platby: ' . $e->getMessage() ) );
    }
}

/**
 * @return void
 */
function elementsell_handle_billing_token_return() {
    $payment_uid = (string) get_option( 'elementsell_p_payment_uid', '' );

    if ( $payment_uid === '' ) {
        wp_die( esc_html__( 'Chybí identifikátor platby.', 'platebni-formular' ) );
    }

    $client = elementsell_billing_get_thepay_client();

    if ( ! $client ) {
        wp_die( esc_html__( 'Nepodařilo se ověřit platbu.', 'platebni-formular' ) );
    }

    try {
        $payment_detail  = $client->getPayment( $payment_uid );
        $payment_state   = $payment_detail->getState();
        $payment_amount  = $payment_detail->getAmount();
        $payment_currency = $payment_detail->getCurrency();
        $resolved_uid    = $payment_detail->getUid();

        if ( $payment_state !== 'paid' ) {
            elementsell_billing_render_result_page(
                false,
                'Platební karta nebyla uložena. Zkuste to prosím znovu.'
            );
            return;
        }

        $option_key = 'zaplaceno_' . $payment_uid;

        if ( get_option( $option_key ) ) {
            elementsell_billing_render_result_page( true, 'Platební karta už byla dříve uložena.' );
            return;
        }

        update_option( $option_key, true );
        elementsell_billing_set_parent_payment_uid( $resolved_uid );
        delete_option( 'payment_failed' );
        elementsell_billing_reset_card_required_email_state();
        elementsell_telemetry_report_card_saved();

        wp_remote_post(
            'https://elementsell.cz/token_created.php',
            [
                'timeout' => 10,
                'body'    => [
                    'creation_date' => current_time( 'mysql' ),
                    'site_url'      => get_site_url(),
                ],
            ]
        );

        elementsell_billing_send_invoice_request(
            [
                'payment_uid' => $resolved_uid,
                'amount'      => $payment_amount / 100,
                'currency'    => $payment_currency,
            ]
        );

        elementsell_billing_render_result_page(
            true,
            'Platební karta byla uložena. Můžete pokračovat v práci s ElementSell.'
        );
    } catch ( Exception $e ) {
        elementsell_billing_render_result_page(
            false,
            'Chyba při ověření platby: ' . $e->getMessage()
        );
    }
}

/**
 * @param bool   $success
 * @param string $message
 * @return void
 */
function elementsell_billing_render_result_page( $success, $message ) {
    $bg      = $success ? '#e9f7ef' : '#fdecea';
    $border  = $success ? '#28a745' : '#dc3545';
    $color   = $success ? '#28a745' : '#dc3545';
    $icon    = $success ? '✔' : '✕';
    $admin   = esc_url( admin_url( 'admin.php?page=elementsell' ) );

    status_header( 200 );
    nocache_headers();

    echo '<!DOCTYPE html><html lang="cs"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1">';
    echo '<title>ElementSell</title></head><body style="margin:0;font-family:Arial,sans-serif;background:#f4f7f6;">';
    echo '<div style="min-height:100vh;display:flex;align-items:center;justify-content:center;padding:24px;">';
    echo '<div style="max-width:560px;width:100%;background:' . esc_attr( $bg ) . ';border:1px solid ' . esc_attr( $border ) . ';border-radius:14px;padding:32px;text-align:center;box-shadow:0 8px 24px rgba(0,0,0,.08);">';
    echo '<div style="font-size:42px;color:' . esc_attr( $color ) . ';margin-bottom:12px;">' . esc_html( $icon ) . '</div>';
    echo '<p style="margin:0 0 20px;font-size:18px;line-height:1.5;color:#1d2327;">' . esc_html( $message ) . '</p>';
    echo '<a href="' . $admin . '" style="display:inline-block;padding:12px 22px;background:#2271b1;color:#fff;text-decoration:none;border-radius:8px;font-weight:700;">Zpět do ElementSell</a>';
    echo '</div></div></body></html>';
    exit;
}

/**
 * @param array $extra
 * @return int|false
 */
function elementsell_billing_send_invoice_request( $extra = [] ) {
    $payment_uid = isset( $extra['payment_uid'] ) ? sanitize_text_field( (string) $extra['payment_uid'] ) : '';

    if ( $payment_uid === '' || ! function_exists( 'elementsell_billing_create_invoice' ) ) {
        return false;
    }

    $args = [
        'payment_uid'   => $payment_uid,
        'amount'        => isset( $extra['amount'] ) ? (float) $extra['amount'] : 0,
        'currency'      => isset( $extra['currency'] ) ? (string) $extra['currency'] : 'CZK',
        'billing_year'  => isset( $extra['billing_year'] ) ? (int) $extra['billing_year'] : 0,
        'billing_month' => isset( $extra['billing_month'] ) ? (int) $extra['billing_month'] : 0,
        'paid_date'     => current_time( 'Y-m-d' ),
    ];

    return elementsell_billing_create_invoice( $args );
}
