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

function elementsell_handle_thepay_payment( $widget_settings = null ) {

    $uid = elementsell_generate_payment_uid();

    $order_id = elementsell_save_order([
        'payment_uid'     => $uid,
        'payment_method'  => 'thepay',
        'payment_status'  => 'created',
        'vs'              => '',
        'pay_url'         => '',
        'return_url'      => add_query_arg(
            'action',
            'elementsell_thepay_return',
            admin_url('admin-post.php')
        ),
        'widget_settings' => $widget_settings,
    ]);



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

    $is_landing_demo = is_array( $widget_settings ) && ! empty( $widget_settings['landing_demo'] );

    if ( $is_landing_demo ) {
        elementsell_save_order_field( $order_id, 'landing_demo', '1' );
    }

    try {
        if ( $is_landing_demo && function_exists( 'elementsell_resolve_thepay_credentials_for_landing_demo' ) ) {
            $thepay_credentials = elementsell_resolve_thepay_credentials_for_landing_demo( $widget_settings );

            if ( ! is_array( $thepay_credentials ) ) {
                throw new Exception( 'Chybí nastavené ThePay demo údaje pro landing.' );
            }
        } else {
            $thepay_credentials = elementsell_resolve_thepay_credentials_for_payment( $widget_settings );
        }

        $environment = $thepay_credentials['environment'];

        if (
            $is_landing_demo
            && (
                $environment !== 'demo'
                || elementsell_get_thepay_urls_for_environment( $environment )['gate_url'] !== 'https://demo.gate.thepay.cz/'
            )
        ) {
            throw new Exception( 'Landing demo musí běžet na ThePay demo prostředí.' );
        }

        if (
            is_array( $widget_settings )
            && ! $is_landing_demo
            && function_exists( 'elementsell_sync_thepay_widget_credentials_to_options' )
        ) {
            elementsell_sync_thepay_widget_credentials_to_options( $widget_settings );
        }

        elementsell_save_thepay_credentials_for_order( $order_id, $thepay_credentials );
        elementsell_save_thepay_api_urls_for_order( $order_id, $environment );

        $payment = elementsell_create_thepay_payment( $uid, $thepay_credentials );
        elementsell_sync_invoice_with_order( $order_id );

        elementsell_update_order($order_id, [
            'payment_status' => 'payment_created',
            'pay_url'        => esc_url_raw($payment['pay_url']),
            'return_url'     => esc_url_raw($payment['return_url']),
            'updated_at'     => current_time('mysql'),
        ]);

        if ( ! empty( $payment['detail_url'] ) ) {
            elementsell_save_order_field( $order_id, 'payment_detail_url', esc_url_raw( $payment['detail_url'] ) );
        }

        wp_safe_redirect( elementsell_get_thepay_picker_url( $uid ) );
        exit;

    } catch (Exception $e) {

        elementsell_update_order($order_id, [
            'payment_status' => 'failed',
            'updated_at'     => current_time('mysql'),
        ]);

        elementsell_save_order_field(
            $order_id,
            'thepay_error',
            $e->getMessage()
        );

        elementsell_save_order_field(
            $order_id,
            'thepay_exception',
            $e->__toString()
        );

        elementsell_render_thepay_error( $e->getMessage(), $is_landing_demo );
        exit;
    }
}

/**
 * @param string $uid
 * @param array|null $thepay_credentials
 * @return array
 */
function elementsell_create_thepay_payment( $uid, $thepay_credentials = null ) {

    elementsell_load_thepay_autoload();

    $amount = elementsell_get_thepay_amount();

    if ( ! is_array( $thepay_credentials ) ) {
        $thepay_credentials = elementsell_resolve_thepay_credentials_from_options();
    }

    $merchant_id  = $thepay_credentials['merchant_id'];
    $project_id   = (int) $thepay_credentials['project_id'];
    $api_password = $thepay_credentials['api_password'];
    $environment  = $thepay_credentials['environment'];

    if ( $merchant_id === '' || $project_id <= 0 || $api_password === '' ) {
        throw new Exception( 'Chybí nastavení platební brány ThePay.' );
    }

    $urls = elementsell_get_thepay_urls_for_environment( $environment );

    $client = elementsell_create_thepay_client(
        $merchant_id,
        $project_id,
        $api_password,
        $urls['api_url'],
        $urls['gate_url']
    );

    $params = new \ThePay\ApiClient\Model\CreatePaymentParams(
        $amount,
        'CZK',
        $uid,
        'cs'
    );

    $return_url = add_query_arg(
    'action',
    'elementsell_thepay_return',
    admin_url('admin-post.php')
);

    $params->setReturnUrl($return_url);
    $params->setNotifUrl($return_url);

    $response = $client->createPayment($params);

    return [
    'uid'           => $uid,
    'pay_url'       => $response->getPayUrl(),
    'detail_url'    => $response->getPaymentDetailUrl(),
    'return_url'    => $return_url,
    'api_url'       => $urls['api_url'],
    'gate_url'      => $urls['gate_url'],
    ];
}

function elementsell_load_thepay_autoload() {

    $autoload = dirname(__DIR__, 2) . '/vendor/autoload.php';

    if ( ! file_exists($autoload) ) {
        wp_die('Chybí vendor/autoload.php pro ThePay.');
    }

    require_once $autoload;
}

function elementsell_get_thepay_amount() {

    $amount = isset( $_POST['amount'] ) ? intval( $_POST['amount'] ) * 100 : 0;

    // ThePay nepřijímá 0 Kč.
    if ( $amount < 1 ) {
        throw new Exception( 'Neplatná částka.' );
    }

    return $amount;
}

function elementsell_get_thepay_urls( $environment ) {
    return elementsell_get_thepay_urls_for_environment( $environment );
}

function elementsell_create_thepay_client(
    $merchant_id,
    $project_id,
    $api_password,
    $api_url,
    $gate_url
) {
    $config = new \ThePay\ApiClient\TheConfig(
        $merchant_id,
        $project_id,
        $api_password,
        $api_url,
        $gate_url
    );

    $signature_service = new \ThePay\ApiClient\Service\SignatureService($config);
    $http_client       = new \GuzzleHttp\Client();
    $request_factory   = new \GuzzleHttp\Psr7\HttpFactory();
    $stream_factory    = new \GuzzleHttp\Psr7\HttpFactory();

    $api_service = new \ThePay\ApiClient\Service\ApiService(
        $config,
        $signature_service,
        $http_client,
        $request_factory,
        $stream_factory
    );

    return new \ThePay\ApiClient\TheClient($config, $api_service);
}

/**
 * @param string $error_message
 * @param bool   $is_landing_demo
 * @return void
 */
function elementsell_render_thepay_error( $error_message, $is_landing_demo = false ) {
    $error_message = (string) $error_message;

    // Landing demo na elementsell.cz — návštěvník není obchodník, video o implementaci je matoucí.
    if ( $is_landing_demo ) {
        $home = function_exists( 'home_url' ) ? home_url( '/' ) : '/';
        ?>
        <div style="text-align:center; font-family:Arial, sans-serif; padding:50px 20px; max-width:640px; margin:0 auto;">
            <p style="font-size:18px; color:#333;">Demo platbu se teď nepodařilo vytvořit.</p>
            <p style="font-size:14px; color:#666;"><?php echo esc_html( $error_message ); ?></p>
            <p style="margin-top:24px;">
                <a href="<?php echo esc_url( $home ); ?>" style="color:#0066cc; text-decoration:none;">Zpět na ElementSell</a>
            </p>
        </div>
        <?php
        return;
    }

    $known_error =
        strpos( $error_message, '404 Not Found' ) !== false ||
        strpos( $error_message, 'Project was not found' ) !== false ||
        strpos( $error_message, 'project_id: "0" must have minimum value: 1' ) !== false ||
        (
            strpos( $error_message, '403 Forbidden' ) !== false &&
            strpos( $error_message, 'Merchant not found' ) !== false
        ) ||
        strpos( $error_message, '400 Bad Request' ) !== false;

    if ( $known_error ) {
        ?>
        <div style="text-align:center; font-family:Arial, sans-serif; padding-top:50px;">
            <p style="font-size:18px; color:#333;">Platba nemohla být provedena, protože platební brána není správně implementována.</p>
            <p style="font-size:18px; color:#333;">Implementujte bránu podle videa:</p>

            <iframe
                src="https://player.vimeo.com/video/1029226517?autoplay=0"
                width="800"
                height="450"
                frameborder="0"
                allow="autoplay; fullscreen; picture-in-picture"
                allowfullscreen
                style="margin-top:20px;">
            </iframe>

            <p style="margin-top:30px; font-size:16px;">
                <a href="https://www.thepay.eu/cs/" target="_blank" style="color:#0066cc; text-decoration:none;">
                    Přejít na platební bránu ThePay
                </a>
            </p>
        </div>
        <?php
        return;
    }

    echo 'Chyba při vytváření platby: ' . esc_html( $error_message ) . '<br>';
    echo 'Zkontrolujte následující možnosti:<br>';
    echo '- Máte správně vyplněné ID obchodníka, ID projektu a heslo API?<br>';
    echo '- Vybrali jste správně prostředí demo/ostré?<br>';
    echo '- Je vaše IP adresa přidána v seznamu povolených IP adres v nastavení ThePay?<br>';
}