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

add_action( 'admin_post_nopriv_elementsell_fio_confirmed', 'elementsell_handle_fio_confirmed' );
add_action( 'admin_post_elementsell_fio_confirmed', 'elementsell_handle_fio_confirmed' );
add_action( 'admin_post_nopriv_elementsell_fio_resume', 'elementsell_handle_fio_resume' );
add_action( 'admin_post_elementsell_fio_resume', 'elementsell_handle_fio_resume' );

/**
 * @return string
 */
function elementsell_generate_fio_vs() {
    return str_pad( substr( (string) time(), -4 ), 4, '0', STR_PAD_LEFT ) . wp_rand( 100, 999 );
}

/**
 * @param string $fio_account
 * @param string $fio_bank_code
 * @param float  $amount
 * @param string $vs
 * @param string $message
 * @return string
 */
function elementsell_build_fio_qr_url( $fio_account, $fio_bank_code, $amount, $vs, $message ) {
    return add_query_arg(
        [
            'accountNumber' => $fio_account,
            'bankCode'      => $fio_bank_code,
            'amount'        => number_format( (float) $amount, 2, '.', '' ),
            'currency'      => 'CZK',
            'vs'            => $vs,
            'message'       => $message,
            'size'          => 200,
        ],
        'https://api.paylibo.com/paylibo/generator/czech/image'
    );
}

/**
 * @param string $payment_uid
 * @return string
 */
function elementsell_get_fio_resume_url( $payment_uid ) {
    return wp_nonce_url(
        add_query_arg(
            [
                'action'      => 'elementsell_fio_resume',
                'payment_uid' => sanitize_text_field( (string) $payment_uid ),
            ],
            admin_url( 'admin-post.php' )
        ),
        'elementsell_fio_resume_' . $payment_uid
    );
}

/**
 * @return void
 */
function elementsell_handle_fio_payment( $widget_settings = null ) {
    $amount = isset( $_POST['amount'] ) ? floatval( $_POST['amount'] ) : 0;

    if ( $amount <= 0 ) {
        wp_die( 'Neplatná částka.' );
    }

    $fio_account = elementsell_get_fio_account_number();

    if ( $fio_account === '' ) {
        wp_die( 'Chyba: Číslo účtu Fio není nastaveno.' );
    }

    if ( elementsell_fio_get_api_token() === '' ) {
        wp_die( 'Chyba: Fio API token není nastaven.' );
    }

    $fio_bank_code = '2010';
    $payment_uid   = elementsell_generate_payment_uid( 'fio_' );
    $vs            = elementsell_generate_fio_vs();
    $product_name  = isset( $_POST['product_name'] )
        ? sanitize_text_field( wp_unslash( $_POST['product_name'] ) )
        : '';

    $order_id = elementsell_save_order(
        [
            'order_uid'       => $payment_uid,
            'payment_uid'     => $payment_uid,
            'payment_method'  => 'fio',
            'payment_status'  => 'pending',
            'vs'              => $vs,
            'pay_url'         => esc_url_raw( elementsell_get_fio_resume_url( $payment_uid ) ),
            'return_url'      => '',
            'widget_settings' => $widget_settings,
        ]
    );

    if ( ! $order_id ) {
        wp_die( 'Objednávku se nepodařilo uložit.' );
    }

    elementsell_sync_invoice_with_order( (int) $order_id );

    $order = elementsell_get_order( (int) $order_id );

    if ( $order ) {
        elementsell_update_order(
            (int) $order_id,
            [
                'return_url' => esc_url_raw( elementsell_get_thank_you_url_for_order( $order ) ),
                'updated_at' => current_time( 'mysql' ),
            ]
        );
    }

    elementsell_render_fio_payment_page(
        [
            'amount'        => $amount,
            'fio_account'   => $fio_account,
            'fio_bank_code' => $fio_bank_code,
            'vs'            => $vs,
            'payment_uid'   => $payment_uid,
            'qr_url'        => elementsell_build_fio_qr_url( $fio_account, $fio_bank_code, $amount, $vs, $product_name ),
        ]
    );
}

/**
 * @return void
 */
function elementsell_handle_fio_confirmed() {
    $payment_uid = isset( $_POST['payment_uid'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['payment_uid'] ) ) : '';

    if ( $payment_uid === '' ) {
        wp_die( 'Chybí identifikátor objednávky.' );
    }

    check_admin_referer( 'elementsell_fio_confirmed_' . $payment_uid );

    $order = elementsell_get_order_by_payment_uid( $payment_uid );

    if ( ! $order || (string) $order->payment_method !== 'fio' ) {
        wp_die( 'Objednávka nebyla nalezena.' );
    }

    if ( ! elementsell_is_order_payment_paid( $order ) ) {
        elementsell_update_order(
            (int) $order->id,
            [
                'payment_status' => 'waiting_for_confirmation',
                'updated_at'     => current_time( 'mysql' ),
            ]
        );

        elementsell_fio_check_pending_payments( true );
        $order = elementsell_get_order( (int) $order->id );
    }

    if ( ! $order ) {
        wp_die( 'Objednávka nebyla nalezena.' );
    }

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

/**
 * @return void
 */
function elementsell_handle_fio_resume() {
    $payment_uid = isset( $_GET['payment_uid'] ) ? sanitize_text_field( wp_unslash( (string) $_GET['payment_uid'] ) ) : '';

    if ( $payment_uid === '' ) {
        wp_die( 'Chybí identifikátor objednávky.' );
    }

    check_admin_referer( 'elementsell_fio_resume_' . $payment_uid );

    $order = elementsell_get_order_by_payment_uid( $payment_uid );

    if ( ! $order || (string) $order->payment_method !== 'fio' ) {
        wp_die( 'Objednávka nebyla nalezena.' );
    }

    if ( elementsell_is_order_payment_paid( $order ) ) {
        wp_safe_redirect( elementsell_get_thank_you_url_for_order( $order ) );
        exit;
    }

    $fio_account = elementsell_get_fio_account_number();

    if ( $fio_account === '' ) {
        wp_die( 'Chyba: Číslo účtu Fio není nastaveno.' );
    }

    elementsell_render_fio_payment_page(
        [
            'amount'        => (float) $order->amount,
            'fio_account'   => $fio_account,
            'fio_bank_code' => '2010',
            'vs'            => (string) $order->vs,
            'payment_uid'   => $payment_uid,
            'qr_url'        => elementsell_build_fio_qr_url(
                $fio_account,
                '2010',
                (float) $order->amount,
                (string) $order->vs,
                (string) $order->product_name
            ),
        ]
    );
    exit;
}

/**
 * @param array $data
 * @return void
 */
function elementsell_render_fio_payment_page( $data ) {
    $amount        = isset( $data['amount'] ) ? (float) $data['amount'] : 0;
    $fio_account   = isset( $data['fio_account'] ) ? sanitize_text_field( (string) $data['fio_account'] ) : '';
    $fio_bank_code = isset( $data['fio_bank_code'] ) ? sanitize_text_field( (string) $data['fio_bank_code'] ) : '2010';
    $vs            = isset( $data['vs'] ) ? sanitize_text_field( (string) $data['vs'] ) : '';
    $payment_uid   = isset( $data['payment_uid'] ) ? sanitize_text_field( (string) $data['payment_uid'] ) : '';
    $qr_url        = isset( $data['qr_url'] ) ? esc_url( (string) $data['qr_url'] ) : '';
    $confirm_url   = admin_url( 'admin-post.php' );
    ?>
    <!doctype html>
    <html lang="cs">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>QR platba</title>
        <style>
            body {
                font-family: Arial, sans-serif;
                background: #fff;
                margin: 0;
                padding: 40px 20px;
                color: #333;
            }

            .payment-container {
                text-align: center;
                padding: 30px;
                background-color: #f9f9f9;
                border-radius: 8px;
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.10);
                max-width: 600px;
                margin: 0 auto;
            }

            .qr-code img {
                max-width: 100%;
                height: auto;
                border-radius: 10px;
                box-shadow: 0 4px 8px rgba(0, 0, 0, 0.10);
            }

            .transfer-title {
                font-size: 18px;
                font-weight: bold;
                color: #333;
                margin-top: 40px;
                margin-bottom: 10px;
            }

            .payment-details {
                background-color: #fff;
                padding: 20px;
                border-radius: 8px;
                box-shadow: 0 2px 6px rgba(0, 0, 0, 0.10);
                margin-top: 20px;
                text-align: left;
            }

            .payment-details p {
                font-size: 16px;
                margin-bottom: 10px;
            }

            .payment-details strong {
                color: #34bd19;
            }

            .payment-confirm-button {
                background-color: #34bd19;
                color: white;
                font-size: 20px;
                font-weight: bold;
                padding: 20px 40px;
                border: none;
                border-radius: 10px;
                cursor: pointer;
                transition: background-color 0.3s ease, transform 0.2s ease;
                margin-top: 30px;
                display: block;
                margin-left: auto;
                margin-right: auto;
                width: auto;
                max-width: 400px;
            }

            .payment-confirm-button:hover {
                background-color: #2a9c16;
                transform: scale(1.05);
            }
        </style>
    </head>
    <body>

        <div class="payment-container">
            <div class="qr-code">
                <img alt="QR platba" src="<?php echo esc_url( $qr_url ); ?>">
            </div>

            <p class="transfer-title">Zaplaťte QR nebo převodem:</p>

            <div class="payment-details">
                <p><strong>Částka:</strong> <?php echo esc_html( number_format( $amount, 2, '.', '' ) ); ?> Kč</p>
                <p><strong>Číslo účtu:</strong> <?php echo esc_html( $fio_account . '/' . $fio_bank_code ); ?></p>
                <p><strong>Variabilní symbol:</strong> <?php echo esc_html( $vs ); ?></p>
            </div>
        </div>

        <form method="post" action="<?php echo esc_url( $confirm_url ); ?>">
            <?php wp_nonce_field( 'elementsell_fio_confirmed_' . $payment_uid ); ?>
            <input type="hidden" name="action" value="elementsell_fio_confirmed">
            <input type="hidden" name="payment_uid" value="<?php echo esc_attr( $payment_uid ); ?>">
            <input type="submit" name="payment_confirmed" value="Potvrďte, že jste zaplatili" class="payment-confirm-button">
        </form>

    </body>
    </html>
    <?php
}
