<?php
/*
 * ==========================================================
 * INIT.PHP
 * ==========================================================
 *
 * This file loads and initializes payments
 *
 */

if (!file_exists(__DIR__ . '/config.php')) {
    die();
}

require_once(__DIR__ . '/functions.php');

if (isset($_POST['data'])) {
    $_POST = json_decode($_POST['data'], true); // Using WordPress function to handle JSON and slash issues
}

if (CRPAY_CLOUD) {
    crpay_cloud_load(); // Assuming this function is defined elsewhere
    if (floatval(crpay_settings_db('credit_balance')) < 0) {
        crpay_cloud_credit_email(-1);
        die('no-credit-balance');
    }
}

if (isset($_POST['init'])) {
    crpay_checkout_init(); // Assuming this function initializes checkout
}

if (isset($_POST['checkout'])) {
    crpay_checkout($_POST['checkout']); // Assuming this function handles checkout process
}


function crpay_checkout_init() {
    $qr_color = crpay_settings_get('color-2');
    if ($qr_color) {
        if (strpos($qr_color, '#') !== false) {
            $qr_color = substr($qr_color, 1);
        } else {
            $qr_color = str_replace(['rgb(', ')', ',', ' '], ['', '', '-', ''], $qr_color);
        }
    } else {
        $qr_color = '23413e';
    }
    $language = crpay_language();
    $translations = $language ? file_get_contents(__DIR__ . '/../../resources/languages/client/' . $language . '.json') : '{}';
    $settings = [
        'qr_code_color' => $qr_color,
        'countdown' => crpay_settings_get('refresh-interval', 60),
        'webhook' => crpay_settings_get('webhook-url'),
        'redirect' => crpay_settings_get('payment-redirect'),
        'vat_validation' => crpay_settings_get('vat-validation'),
        'names' => crpay_crypto_name(),
        'cryptocurrencies' => crpay_get_cryptocurrency_codes()
    ];
    if (defined('CRPAY_EXCHANGE')) {
        $settings['exchange'] = [
            'identity_type' => crpay_settings_get('exchange-identity-type'),
            'email_verification' => crpay_settings_get('exchange-email-verification'),
            'testnet_btc' => crpay_settings_get('testnet-btc'),
            'testnet_eth' => crpay_settings_get('testnet-eth'),
            'texts' => [crpay_(crpay_settings_get('exchange-manual-payments-text-send-complete', 'The payment of {amount} will be sent to the provided payment details:'))],
            'url_rewrite_checkout' => CRPAY_CLOUD ? 'checkout/' : crpay_settings_get('url-rewrite-checkout')
        ];
    }
    if (defined('CRPAY_SHOP')) {
        $settings['shop'] = true;
    }

    $translations_escaped = ($translations);
    $settings_escaped = (json_encode($settings, JSON_INVALID_UTF8_IGNORE | JSON_UNESCAPED_UNICODE));

    echo 'var CRPAY_TRANSLATIONS = ' . ($translations_escaped) . '; var CRPAY_URL = "' . (CRPAY_URL) . '"; var CRPAY_SETTINGS = ' . ($settings_escaped) . ';';
}

function crpay_checkout_custom_fields() {
    $code = '';
    $custom_fields = crpay_settings_get_repeater(['checkout-custom-field-type', 'checkout-custom-field-name', 'checkout-custom-field-required']);

    for ($i = 0; $i < count($custom_fields); $i++) {
        $type = $custom_fields[$i][0];
        $field_name = $custom_fields[$i][1];

        if ($field_name) {
            if ($type != 'select') {
                $code .= '<div class="crpay-input crpay-input-' . ($type) . '"><span>' . (crpay_($field_name)) . '</span>';
            }

            switch ($type) {
                case 'text':
                    $code .= '<input name="' . ($field_name) . '" type="text"' . ($custom_fields[$i][2] ? ' required' : '') . '>';
                    break;
                case 'checkbox':
                    $code .= '<input name="' . ($field_name) . '" type="checkbox"' . ($custom_fields[$i][2] ? ' required' : '') . '>';
                    break;
                case 'textarea':
                    $code .= '<textarea name="' . ($field_name) . '"' . ($custom_fields[$i][2] ? ' required' : '') . '></textarea>';
                    break;
                case 'select':
                    $select_values = explode(':', $field_name);
                    $code .= '<div class="crpay-input crpay-input-select"><span>' . (crpay_($select_values[0])) . '</span><select name="' . ($select_values[0]) . '"' . ($custom_fields[$i][2] ? ' required' : '') . '><option value=""></option>';
                    for ($j = 1; $j < count($select_values); $j++) {
                        $code .= '<option value="' . (str_replace('"', '\'', $select_values[$j])) . '">' . (crpay_($select_values[$j])) . '</option>';
                    }
                    $code .= '</select>';
                    break;
            }
            $code .= '</div>';
        }
    }

    if ($code) {
        echo '<div class="crpay-custom-fields"><div class="crpay-title">' . (crpay_(crpay_settings_get('checkout-custom-fields-title', 'Information'))) . '</div>' . ($code) . '</div>';
    }
}

function crpay_checkout($settings) {
    $checkout_id = $settings['checkout_id'];
    $custom = strpos($checkout_id, 'custom') !== false;
    $cryptocurrencies = crpay_get_cryptocurrency_codes();
    $cryptocurrencies_code = '';
    $collapse = crpay_settings_get('collapse');
    $body_classes = '';
    if (!$custom) {
        $settings = crpay_checkout_get($checkout_id);
    }
    if (!$settings) {
        die();
    }
    $title = ($custom && !empty($settings['title'])) || (empty($settings['hide_title']) && !crpay_settings_get('hide-title'));
    $image = crpay_isset($settings, 'image');
    $currency_code = empty($settings['currency']) ? crpay_settings_get('currency', 'USD') : $settings['currency'];
    if (crpay_settings_get('stripe-active') || crpay_settings_get('verifone-active')) {
        $cryptocurrencies_code .= '<div data-cryptocurrency="' . (crpay_settings_get('stripe-active') ? 'stripe' : 'verifone') . '" class="crpay-flex"><img src="' . CRPAY_URL . 'media/icon-cc.svg" alt="' . crpay_('Credit or debit card') . '" /><span>' . crpay_('Credit or debit card') . '</span></div>';
    }
    if (crpay_settings_get('paypal-active')) {
        $cryptocurrencies_code .= '<div data-cryptocurrency="paypal" class="crpay-flex"><img src="' . CRPAY_URL . 'media/icon-pp-2.svg" alt="PayPal" /><span>PayPal</span></div>';
    }
    if (crpay_settings_get('ln-node-active')) {
        $cryptocurrencies_code .= '<div data-cryptocurrency="btc_ln" class="crpay-flex"><img src="' . CRPAY_URL . 'media/icon-btc_ln.svg" alt="Bitcoin Lightning Network" /><span>Bitcoin<span class="crpay-label">Lightning <div>Network</div></span></span><span>BTC</span></div>';
    }
    if ($title) {
        $title = crpay_isset($settings, 'title', crpay_settings_get('form-title'));
        if ($title) {
            $title = '<div class="crpay-top crpay-checkout-top"><div><div class="crpay-title">' . crpay_($title) . '</div><div class="crpay-text">' . crpay_render_text(empty($settings['description']) ? crpay_settings_get('form-description', '') : $settings['description']) . '</div></div></div>';
        }
    }
    if ($image) {
        $image = '<div class="crpay-background-image" style="background-image: url(\'' . CRPAY_URL . 'uploads' . crpay_cloud_path_part() . '/' . $image . '\')"></div>';
    }
    foreach ($cryptocurrencies as $value) {
        for ($i = 0; $i < count($value); $i++) {
            $cryptocurrency_code = $value[$i];
            if (crpay_settings_get_address($cryptocurrency_code)) {
                $cryptocurrencies_code .= '<div data-cryptocurrency="' . $cryptocurrency_code . '"' . (crpay_crypto_is_custom_token($cryptocurrency_code) ? ' data-custom-coin="' . crpay_get_custom_tokens()[$cryptocurrency_code]['type'] . '"' : '') . ' class="crpay-flex"><img src="' . crpay_crypto_get_image($cryptocurrency_code) . '" alt="' . strtoupper($cryptocurrency_code) . '" /><span>' . crpay_crypto_name($cryptocurrency_code, true) . crpay_crypto_get_network($cryptocurrency_code, true, true) . '</span><span>' . strtoupper(crpay_crypto_get_base_code($cryptocurrency_code)) . '</span></div>';
            }
        }
    }
    $checkout_price = floatval($settings['price']);
    if ($checkout_price == -1) {
        $checkout_price = '';
    }
    $checkout_start_price = $checkout_price;
    $checkout_type = empty($_POST['payment_page']) ? crpay_isset($settings, 'type', 'I') : 'I';
    $checkout_type = crpay_isset(['I' => 'inline', 'L' => 'link', 'P' => 'popup', 'H' => 'hidden'], $checkout_type, $checkout_type);
    echo '<!-- Cryptopayment - https://cryptopayment.network -->';
    if ($checkout_type == 'popup') {
        echo '<div class="crpay-btn crpay-btn-popup"><img src="' . (CRPAY_URL) . 'media/icon-cryptos.svg" alt="" />' . (crpay_(crpay_settings_get('button-text', 'Pay now'))) . '</div><div class="crpay-popup-overlay"></div>';
    }
    $css = false;
    $color_1 = crpay_settings_get('color-1');
    $color_2 = crpay_settings_get('color-2');
    $color_3 = crpay_settings_get('color-3');
    $vat = crpay_settings_get('vat');
    if ($vat && $checkout_price) {
        $vat_details = crpay_vat($checkout_price, false, $currency_code);
        $checkout_price = $vat_details[0];
        $vat = '<span class="crpay-vat" data-country="' . $vat_details[3] . '" data-country-code="' . $vat_details[2] . '" data-amount="' . $vat_details[1] . '" data-percentage="' . $vat_details[5] . '">' . $vat_details[4] . '</span>';
    }
    if ($color_1) {
        $css = '.crpay-payment-methods>div:hover .crpay-label,.crpay-payment-methods>div:hover,.crpay-btn.crpay-btn-border:hover, .crpay-btn.crpay-btn-border:active { border-color: ' . $color_1 . '; color: ' . $color_1 . '; }';
        $css .= '.crpay-complete-cnt>i, .crpay-failed-cnt>i,.crpay-payment-methods>div:hover span+span,.crpay-clipboard:hover,.crpay-tx-cnt .crpay-loading:before,.crpay-input-btn .crpay-btn.crpay-loading:before,.crpay-loading:before,.crpay-btn-text:hover,.crpay-input input[type="checkbox"]:checked:before,.crpay-link:hover,.crpay-link:active,.crpay-underline:hover,.crpay-underline:active,.crpay-complete-cnt .crpay-link:hover { color: ' . $color_1 . '; }';
        $css .= '.crpay-tx-status,.crpay-select ul li:hover,.crpay-underline:hover:after { background-color: ' . $color_1 . '; }';
        $css .= '.crpay-input input:focus, .crpay-input input.crpay-focus, .crpay-input select:focus, .crpay-input select.crpay-focus, .crpay-input textarea:focus, .crpay-input textarea.crpay-focus { border-color: ' . $color_1 . '; box-shadow: 0 0 5px rgb(0 0 0 / 20%);';
    }
    if ($color_2) {
        $css .= '.crpay-box { color: ' . $color_2 . '; }';
    }
    if ($color_3) {
        $css .= '.crpay-text,.crpay-payment-methods>div span+span { color: ' . $color_3 . '; }';
        $css .= '.crpay-btn.crpay-btn-border { border-color: ' . $color_3 . '; color: ' . $color_3 . '; }';
    }
    if ($css) {
		echo '<style>' . ($css) . '</style>';
    }
    $shop_code = defined('CRPAY_SHOP') ? crpay_shop_checkout_init($checkout_id) : '';
    if (crpay_is_rtl(crpay_language())) {
        $body_classes .= ' crpay-rtl';
    }
    ?>
<div class="crpay-main crpay-start crpay-<?php echo ($checkout_type . $body_classes); ?>"
     data-checkout-id="<?php echo ($checkout_id); ?>"
     data-currency="<?php echo ($currency_code); ?>"
     data-price="<?php echo ($checkout_price); ?>"
     data-external-reference="<?php echo (crpay_isset($settings, 'external_reference', crpay_isset($settings, 'external-reference', ''))); ?>"
     data-title="<?php echo (str_replace('"', '', crpay_isset($settings, 'title', ''))); ?>"
     data-note="<?php echo (str_replace('"', '', crpay_isset($settings, 'note', ''))); ?>"
     data-redirect="<?php echo (crpay_isset($settings, 'redirect', '')); ?>"
     data-start-price="<?php echo ($checkout_start_price); ?>">
	<?php
        if ($checkout_type == 'popup') {
            echo '<i class="crpay-popup-close crpay-icon-close"></i>';
        }
        ?>
        <div class="crpay-cnt crpay-box">
            <?php 

			echo  $image . $title ?>
            <div class="crpay-body">
                <div id="crpay-error-message" class="crpay-error crpay-text"></div>
                <div class="crpay-flex crpay-amount-fiat<?php echo $checkout_price ? '' : ' crpay-donation' ?>">
                    <div class="crpay-title">
                        <?php
                        crpay_e($checkout_price ? 'Total' : 'Amount');
                        if (!$checkout_price) {
                            echo '<div class="crpay-text">' . (crpay_(crpay_settings_get('user-amount-text', 'Pay what you want'))) . '</div>';
                        }
                        ?>
                    </div>
                    <div class="crpay-title">
                        <?php echo ($checkout_price) ? (strtoupper($currency_code)) . ' <span class="crpay-amount-fiat-total">' . (crpay_decimal_number($checkout_price)) . '</span>' . ($vat) : '<div class="crpay-input" id="user-amount"><span>' . (strtoupper($currency_code)) . '</span><input type="number" min="0" /></div>' ?>
                    </div>
                </div>
                <?php
                echo ($shop_code);
                crpay_checkout_custom_fields();
                if (crpay_settings_get('invoice-active')) {
					
					// Escape the code using wp_kses
                    echo crpay_transactions_invoice_form();
                }
                ?>
                <div class="crpay-payment-methods-cnt">
                    <div <?php echo $collapse ? 'class="crpay-collapse"' : '' ?>>
                        <div class="crpay-payment-methods">
                            <?php 
						
							// Escape the code using wp_kses
							echo $cryptocurrencies_code;
							 ?>
                        </div>
                        <?php
                        if ($collapse) {
                            echo '<div class="crpay-btn-text crpay-collapse-btn"><i class="crpay-icon-arrow-down"></i>' . (crpay_('All cryptocurrencies')) . '</div>';
                        }
                        ?>
                    </div>
                </div>
            </div>
        </div>
        <div class="crpay-pay-cnt crpay-box">
            <div class="crpay-top">
                <div class="crpay-pay-top-main">
                    <div class="crpay-title">
                        <?php crpay_e(crpay_settings_get('form-payment-title', 'Send payment')) ?>
                        <div class="crpay-flex">
                            <div class="crpay-countdown crpay-toolip-cnt">
                                <div data-countdown="<?php crpay_settings_get('refresh-interval', 60) ?>"></div>
                                <span class="crpay-toolip">
                                    <?php crpay_e('Checkout timeout') ?>
                                </span>
                            </div>
                            <div class="crpay-btn crpay-btn-border crpay-back">
                                <i class="crpay-icon-back"></i>
                                <?php crpay_e('Back') ?>
                            </div>
                        </div>
                    </div>
                    <?php 

					echo '<div class="crpay-text">' . crpay_render_text(crpay_settings_get('form-payment-description', '')) . '</div>' ?>
                </div>
                <div class="crpay-pay-top-back">
                    <div class="crpay-title">
                        <?php crpay_e('Are you sure?') ?>
                    </div>
                    <div class="crpay-text">
                        <?php crpay_e('This transaction will be cancelled. If you already sent the payment please wait.') ?>
                    </div>
                    <div id="crpay-confirm-cancel" class="crpay-btn crpay-btn-border crpay-btn-red">
                        <?php crpay_e('Yes, I\'m sure') ?>
                    </div>
                    <div id="crpay-abort-cancel" class="crpay-btn crpay-btn-border crpay-back">
                        <?php crpay_e('Cancel') ?>
                    </div>
                </div>
            </div>
            <div class="crpay-body">
                <div class="crpay-flex">
                    <?php
                    if (!crpay_settings_get('disable-qrcode')) {
                        echo '<img class="crpay-qrcode" src="" alt="QR code" />';
                    }
                    ?>
                    <div class="crpay-flex crpay-qrcode-text">
                        <img src="" alt="" />
                        <div class="crpay-text"></div>
                    </div>
                </div>
                <div class="crpay-flex crpay-pay-address">
                    <div>
                        <div class="crpay-text"></div>
                        <div class="crpay-title"></div>
                    </div>
                    <i class="crpay-icon-copy crpay-clipboard crpay-toolip-cnt">
                        <span class="crpay-toolip">
                            <?php crpay_e('Copy to clipboard') ?>
                        </span>
                    </i>
                </div>
                <div class="crpay-flex crpay-pay-amount">
                    <div>
                        <div class="crpay-text">
                            <?php crpay_e('Total amount') ?>
                        </div>
                        <div class="crpay-title"></div>
                    </div>
                    <div class="crpay-flex">
                        <?php
                        if (crpay_settings_get('metamask')) {
                            echo '<div id="metamask" class="crpay-btn crpay-btn-img crpay-hidden"><img src="' . (CRPAY_URL) . 'media/metamask.svg" alt="MetaMask" />MetaMask</div>';
                        }
                        ?>
                        <i class="crpay-icon-copy crpay-clipboard crpay-toolip-cnt">
                            <span class="crpay-toolip">
                                <?php crpay_e('Copy to clipboard') ?>
                            </span>
                        </i>
                    </div>
                </div>
            </div>
        </div>
        <div class="crpay-tx-cnt crpay-box">
            <div class="crpay-loading"></div>
            <div class="crpay-title">
                <?php crpay_e('Payment received') ?>
            </div>
            <div class="crpay-flex">
                <div class="crpay-tx-status"></div>
                <div class="crpay-tx-confirmations">
                    <span></span>
                    /
                </div>
                <div>
                    <?php crpay_e('confirmations') ?>
                </div>
            </div>
        </div>
        <div class="crpay-complete-cnt crpay-box">
            <i class="crpay-icon-check"></i>
            <div class="crpay-title">
                <?php crpay_e(crpay_settings_get('success-title', 'Payment completed')) ?>
            </div>
            <div class="crpay-text">
                <span>
                    <?php 

					
					echo crpay_render_text(crpay_settings_get('success-description', 'Thank you for your payment')) ?>
                </span>
                <span>
                    <?php echo crpay_render_text(crpay_settings_get('order-processing-text', 'We are processing the order, please wait...')) ?>
                </span>
            </div>
        </div>
        <div class="crpay-failed-cnt crpay-box">
            <i class="crpay-icon-close"></i>
            <div class="crpay-title">
                <?php crpay_e(crpay_settings_get('failed-title', 'No payment')) ?>
            </div>
            <div class="crpay-text">
                <?php echo crpay_render_text(crpay_settings_get('failed-text', 'We didn\'t detect a payment. If you have already paid, please contact us.')) ?>
            </div>
            <div class="crpay-text">
                <?php crpay_e('Your transaction ID is:') ?>
                <span id="crpay-expired-tx-id"></span>
            </div>
            <div class="crpay-btn crpay-btn-border ">
                <?php crpay_e('Retry') ?>
            </div>
        </div>
        <div class="crpay-underpayment-cnt crpay-box">
            <i class="crpay-icon-close"></i>
            <div class="crpay-title">
                <?php crpay_e(crpay_settings_get('underpayment-title', 'Underpayment')) ?>
            </div>
            <div class="crpay-text">
                <?php echo crpay_render_text(crpay_settings_get('underpayment-description', 'We have detected your payment but the amount is less than requested and the transaction cannot be completed, please contact us.')) ?>
                <?php crpay_e('Your transaction ID is:') ?><span id="crpay-underpaid-tx-id"></span>
            </div>
        </div>

    </div>
<?php } ?>