<?php

/*
 * ==========================================================
 * PAY.PHP
 * ==========================================================
 *
 * Payment page
 *
 */

if (!file_exists(__DIR__ . '/config.php')) {
    die();
}
require_once(__DIR__ . '/functions.php');
if (CRPAY_CLOUD) {
    crpay_cloud_load();
}

$logo = crpay_settings_get('logo-pay');
$minify = isset($_GET['debug']) ? false : (CRPAY_CLOUD || crpay_settings_get('minify'));
$invoice_form = false;
$invoice_get = crpay_sanatize_string(crpay_isset($_GET, 'invoice'));
if ($invoice_get) {
    $transaction_id = crpay_encryption($invoice_get, false);
    if ($transaction_id) {
        if (isset($_GET['download'])) {
            $invoice = crpay_transactions_invoice($transaction_id);
			die($invoice ? '<script>document.location = "' . $invoice . '"</script>' : 'Transaction not found or not confirmed.');
        }
        $transaction = crpay_transactions_get($transaction_id);
        if ($transaction) {
            if ($transaction['status'] != 'P') {
                $invoice_form = '<div class="crpay-main crpay-billing-page">' . crpay_transactions_invoice_form(true) . '<div id="crpay-generate-invoice" class="crpay-btn">' . crpay_('View Invoice') . '</div></div>';
                $invoice_form .= '<style>.crpay-main { text-align: center; } .crpay-main > #crpay-generate-invoice.crpay-btn { margin-top: 30px !important; }</style>';
                $invoice_form .= '<script>
                             (function () {
                                 let _ = window._query;
                                 let billing = ' . ($transaction['billing'] ? $transaction['billing'] : '_.storage(\'crpay-billing\')') . ';
                                 _(\'body\').on(\'click\', \'#crpay-generate-invoice\', function () {
                                     let billing_details = CRYPTOPayment.checkout.getBillingDetails(_(\'#crpay-billing\'));
                                     if (billing_details) {
                                        CRYPTOPayment.ajax(\'invoice-user\', {
                                            encrypted_transaction_id: "' . $invoice_get . '",
                                            billing_details: billing_details
                                        }, (response) => {
                                            if (response && response.includes(\'http\')) {
                                                _.storage(\'crpay-billing\', billing_details);
                                                window.open(response);
                                            } else {
                                                alert(JSON.stringify(response));
                                            }
                                        });
                                     }
                                 });
                                 if (billing) {
                                    for (var key in billing) {
                                        _(\'#crpay-billing\').find(`#crpay-billing [name="${key}"]`).val(billing[key]);
                                    }
                                 }
                             }());
                             </script>';
            } else {
                die('Transaction not confirmed.');
            }
        } else {
            die('Transaction not found.');
        }
    } else {
        die('Transaction ID not found.');
    }
}

$code_transaction = '';
if (isset($_GET['id']) && !isset($_GET['demo'])) {
    $transaction = crpay_transactions_get(crpay_encryption(crpay_sanatize_string($_GET['id']), false));
    $fiat_redirect = '';
    if (!$transaction) {
        die('Transaction not found.');
    }
    if ($transaction['status'] != 'P') {
        die('Transaction not in pending status.');
    }
    if (crpay_crypto_is_fiat($transaction['cryptocurrency'])) {

        $fiat_redirect = 'document.location = "' . crpay_checkout_url($transaction['amount_fiat'], $transaction['cryptocurrency'], $transaction['currency'], CRPAY_URL . '/vendor/cryptd/pay.php?id=' . crpay_sanatize_string($_GET['id']), $transaction['id'], $transaction['title']) . '";';
    }

    $_GET['checkout_id'] = 'custom-pay-page';
	
    $code_transaction = '<script>CRYPTOPayment.checkout.storageTransaction("custom-pay-page", "delete"); CRYPTOPayment.checkout.storageTransaction("custom-pay-page", { id: ' . $transaction['id'] . ', amount: "' . $transaction['amount'] . '", to: "' . $transaction['to'] . '", cryptocurrency: "' . $transaction['cryptocurrency'] . '", external_reference: "' . $transaction['external_reference'] . '", vat: "' . $transaction['vat'] . '", encrypted: "' . crpay_encryption($transaction) . '", min_confirmations: ' . crpay_settings_get_confirmations($transaction['cryptocurrency'], $transaction['amount']) . ', prevent_cancel: true });' . $fiat_redirect . '</script>';
}
if (crpay_settings_get('css-pay')) {
    $code_transaction .= PHP_EOL . '<link rel="stylesheet" href="' . crpay_settings_get('css-pay') . '?v=' . CRPAY_VERSION . '" media="all" />';
}
$favicon = CRPAY_CLOUD ? CLOUD_ICON : ($logo ? crpay_settings_get('logo-icon-url', CRPAY_URL . 'media/icon.png') : CRPAY_URL . 'media/icon.png');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
    <title>
        <?php crpay_e(crpay_settings_get('form-title', 'Payment method')) ?>
    </title>
	<?php
	if (isset($_GET['lang'])) {
		echo '<script>var CRPAY_LANGUAGE = "' . substr(crpay_sanatize_string($_GET['lang']), 0, 2) . '";</script>';
	}
	?>
	<!DOCTYPE html>
	<html>
	<head>
		<meta charset="utf-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no" />
		<title>Cryptopayment</title>
		<link rel="shortcut icon" type="image/<?php echo strpos($favicon, '.png') ? 'png' : 'svg'; ?>" href="<?php echo $favicon; ?>" />
		<script id="cryptopayment" src="<?php echo CRPAY_URL . 'js/client' . ($minify ? '.min' : '') . '.js?v=' . CRPAY_VERSION; ?>"></script>
		<?php

		echo $code_transaction; // Assuming $code_transaction needs escaping
		?>
		<style>
			body {
				text-align: center;
				padding: 100px 0;
			}

			.crpay-main {
				text-align: left;
				margin: auto;
			}

			.crpay-pay-logo {
				text-align: center;
			}

			.crpay-pay-logo img {
				margin: 0 auto 30px auto;
				max-width: 200px;
			}
		</style>
	</head>
	<body style="display: none">
		<?php

		if ($logo) {
			echo '<div class="crpay-pay-logo"><img src="' . crpay_settings_get('logo-url') . '" alt="" /></div>';
		}
		if ($invoice_form) {

			echo $invoice_form;
		} else {
			crpay_checkout_direct();
			echo crpay_settings_get('pay-text'); // Assuming pay-text needs escaping
		}
		?>
	     <script>(function () { setTimeout(() => { document.body.style.removeProperty('display') }, 50) }())</script>

	</body>
	</html>