<?php
declare(strict_types=1);
ob_start();

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

define('ROOT', $_SERVER['DOCUMENT_ROOT']);
session_start();

if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

include_once ROOT . '/sys/db.php';
include_once ROOT . '/sys/sys.php';

$title = 'Покупка трафика';
if (!empty($_GET['type']) && $_GET['type'] == 'adv') {
    $title = 'Заказ текстовой рекламы';
}

require_once ROOT . '/sys/head.php';

$sett = $pdo->query('SELECT * FROM `sett` LIMIT 1')->fetch();
$isd = $sett['cena'] ?? 0;

$id_shop_payeer = $sett['id_payeer'];
$wallet_yoo = $sett['wallet_yoo'];
$ism = 365;
$min_url = 5;
$max_url = 50;
$min_name_adv = 3;
$max_name_adv = 52;
$id_hash = uniqid();
$userId = $_SESSION['user_id'] ?? '0';
$error = [];
$url = $_POST['url'] ?? null;
$name = $_POST['name'] ?? null;
$days = $_POST['days'] ?? null;
$captcha = $_POST['captcha'] ?? null;

$list_pay = [
    'yoomoney' => 'ЮMoney',
    'payeer' => 'Payeer'
];

$errorMessages = [
    'payment_system_missing' => "Платежная система отсутствует!",
    'link_banned' => 'Ссылка запрещена!',
    'fields_missing' => 'Похоже вы что-то пропустили...',
    'invalid_url' => 'Это не ссылка',
    'url_length' => "Предельная длина URL {$min_url}-{$max_url}",
    'name_length' => "Предельная длина названия {$min_name_adv}-{$max_name_adv}",
    'days_limit' => 'Предельное количество дней 1-' . $ism,
    'invalid_captcha' => 'Неверная капча',
    'payment_error' => 'Ошибка оплаты. Попробуйте ещё раз.',
    'link_added' => 'Ссылка успешно добавлена!',
    'platform_added' => 'Площадка успешно размещена!',
    'view' => 'ПОСМОТРЕТЬ',
    'view_order' => 'Просмотр Заказа',
    'csrf_error' => 'Неверный CSRF токен'
];

if (!empty($days)) {

    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $error[] = $errorMessages['csrf_error'];
    }

    $count = $isd * $days;
    $expire = date('Y-m-d H:i:s', strtotime("+$days days"));

    if (!array_key_exists($_POST['mode'], $list_pay)) {
        $error[] = $errorMessages['payment_system_missing'];
    }

    $haystack = json_decode($sett['black_links']);
    
    $pos = check_url($url, $haystack);
    if ($pos !== false) {
        $error[] = $errorMessages['link_banned'];
    }

    if (empty($error)) {
        switch ($_POST['mode']) {
            case 'yoomoney':
                $form_data = [
                    'receiver' => $wallet_yoo,
                    'quickpay-form' => 'button',
                    'paymentType' => 'PC',
                    'sum' => $count,
                    'label' => $id_hash,
                    'successURL' => 'https://' . $_SERVER['HTTP_HOST'] . '/pay?success=' . (isset($_POST['submit_adv']) ? 'adv' : 'iframe')
                ];

                $url_redirect = 'https://yoomoney.ru/quickpay/confirm';
                break;

            case 'payeer':
                $desc = base64_encode('"Оплата счета №' . $id_hash);

                $m_amount = number_format($count, 2, '.', '');

                $arHash = [
                    $id_shop_payeer, $id_hash, $m_amount, 'RUB', $desc
                ];

                $arParams = [
                    'success_url' => 'https://' . $_SERVER['HTTP_HOST'] . '/pay?success=' . (isset($_POST['submit_adv']) ? 'adv' : 'iframe'),
                    'fail_url' => 'https://' . $_SERVER['HTTP_HOST'] . '/pay/?error'
                ];

                $key_params = $sett['key_payeer'];
                $m_params = urlencode(base64_encode(openssl_encrypt(json_encode($arParams), 'AES-256-CBC', $key_params, OPENSSL_RAW_DATA)));
                $arHash[] = $sett['key_payeer'];

                $sign = strtoupper(hash('sha256', implode(':', $arHash)));
                $form_data = [
                    'm_shop' => $id_shop_payeer,
                    'm_orderid' => $id_hash,
                    'm_amount' => $m_amount,
                    'm_curr' => 'RUB',
                    'm_desc' => $desc,
                    'm_sign' => $sign,
                    'm_process' => 'send',
                ];

                $url_redirect = 'https://payeer.com/merchant/';
                break;
        }
    } else {
        $_SESSION['err'] = $error;
        header('Location: /pay/?type=' . (isset($_POST['submit_adv']) ? 'adv' : 'iframe'));
        die;
    }
}

if (filter_has_var(INPUT_POST, 'submit')) {

    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $error[] = $errorMessages['csrf_error'];
    }

    if (empty($url) || empty($days) || empty($captcha)) {
        $error[] = $errorMessages['fields_missing'];
    }

    if (!filter_var($url, FILTER_VALIDATE_URL)) {
        $error[] = $errorMessages['invalid_url'];
    }

    if (mb_strlen($url) < $min_url || mb_strlen($url) > $max_url) {
        $error[] = $errorMessages['url_length'];
    }

    if ($days < 1 || $days > $ism) {
        $error[] = $errorMessages['days_limit'];
    }

    if (!isset($_SESSION['view']['captcha']) || $_SESSION['view']['captcha'] != $captcha) {
        $error[] = $errorMessages['invalid_captcha'];
    }

    if (empty($error)) {
        $sql = "INSERT INTO `iframe` (
                    `url`, `summa`, `days`, `expire`, `id_hash`, `type_pay`
                ) VALUES (?, ?, ?, ?, ?, ?)";
        $sQuery = $pdo->prepare($sql);
        $sQuery->execute([
            $url, $count, $days, $expire, $id_hash, $_POST['mode']
        ]);

        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));

        header('Location: ' . $url_redirect . '?' . http_build_query($form_data));
        die;
    }
    $_SESSION['err'] = $error;
    header('Location: /pay?type=iframe');
    die;
}

if (filter_has_var(INPUT_POST, 'submit_adv')) {

    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $error[] = $errorMessages['csrf_error'];
    }

    if (empty($url) || empty($name) || empty($days) || empty($captcha)) {
        $error[] = $errorMessages['fields_missing'];
    }

    if (!filter_var($url, FILTER_VALIDATE_URL)) {
        $error[] = $errorMessages['invalid_url'];
    }

    if (mb_strlen($url) < $min_url || mb_strlen($url) > $max_url) {
        $error[] = $errorMessages['url_length'];
    }

    if (mb_strlen($name) < $min_name_adv || mb_strlen($name) > $max_name_adv) {
        $error[] = $errorMessages['name_length'];
    }

    if ($days < 1 || $days > $ism) {
        $error[] = $errorMessages['days_limit'];
    }

    if (!isset($_SESSION['view']['captcha']) || $_SESSION['view']['captcha'] != $captcha) {
        $error[] = $errorMessages['invalid_captcha'];
    }

    if (empty($error)) {
        $sql = "INSERT INTO `reklama` (
                `url`, `name`, `days`, `summa`, `expire`, `user_id`, `id_hash`, `type_pay`
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";

        $sQuery = $pdo->prepare($sql);
        $sQuery->execute([
            $url, $name, $days, $count, $expire, $userId, $id_hash, $_POST['mode']
        ]);

        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));

        header('Location: ' . $url_redirect . '?' . http_build_query($form_data));
        die;
    }

    $_SESSION['err'] = $error;
    header('Location: /pay?type=adv');
    die;
}
?>

    <div class="bg-index"><br>
        <div class="title-page">
            <h2 style="color: #fff;"><?= $title; ?></h2>
        </div>
        <div class="container">
            <center>
                <p class="text-light" style="position: relative;z-index: 99;">Внимательно заполняйте поля</p>
            </center>
            <br><br><br>
        </div>
    </div>

    <div class="container">
        <div class="row">
            <div class="col-lg-4 col-md-3"></div>
            <div class="col-lg-4 col-md-6">
                <div class="alert bg-light stat" style="margin-top: -55px;">
                    <?php if (!empty($_SESSION['err'])): ?>
                        <div class="alert alert-danger">
                            <?php foreach ($_SESSION['err'] as $err): ?>
                                <div><?= $err; ?></div>
                            <?php endforeach; ?>
                        </div>
                        <?php unset($_SESSION['err']); ?>
                    <?php endif; ?>

                    <?php if (!empty($_REQUEST['success'])): ?>
                        <div class="alert alert-success">
                            <?php if ($_REQUEST['success'] == 'adv'): ?>
                                <div><?= $errorMessages['link_added']; ?> <a href="/"><b><u><?= $errorMessages['view']; ?></u></b></a></div>
                            <?php else: ?>
                                <div><?= $errorMessages['platform_added']; ?></div>
                                <div class="text-center">
                                    <a href="/iframe"><input value="<?= $errorMessages['view_order']; ?>" type="submit"
                                                             class="btn btn-primary"></a>
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>

                    <?php if (isset($_REQUEST['error'])): ?>
                        <div class="text-center"><span style="color: red"><?= $errorMessages['payment_error']; ?></span>
                        </div>
                    <?php endif; ?>

                    <?php if (!empty($_GET['type']) && $_GET['type'] == 'adv'): ?>
                        <h5>Заказ партнёрской рекламы</h5>
                        <hr>
                        <form method="post">
                            <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token']; ?>">
                            <div class="form-group">
                                <label>URL сайта[<?= $max_url; ?>]:</label>
                                <input id="url" name="url" type="text" maxlength="<?= $max_url; ?>" class="form-control"
                                       placeholder="https://" value="https://"/>
                                <p id="err" style="color:red; font-size: small; display: none"><?= $errorMessages['link_banned']; ?></p>
                            </div>
                            <div class="form-group">
                                <label>Название ссылки[<?= $max_name_adv; ?>]:</label>
                                <input name="name" type="text" maxlength="<?= $max_name_adv; ?>" class="form-control"
                                       placeholder="Софтпортал для Программистов"/>
                            </div>
                            <div class="form-group">
                                <label>Количество дней[1-<?= $ism; ?>]:</label>
                                <input name="days" type="number" min="1" max="<?= $ism; ?>" class="form-control"
                                       value="20"/>
                            </div>
                            <div class="form-group">
                                <img src="/captcha/captcha-st/captcha.php" alt="Captcha" style="margin-bottom: 10px;">
                                <input name="captcha" type="text" class="form-control" placeholder="Введите капчу"
                                       required>
                            </div>
                            <div class="form-group">
                                <b>Стоимость размещения в день:
                                    <span style="text-decoration:line-through"><u><font color="red">500</font></u></span> <?= $isd; ?> руб.
                                </b>
                            </div>

                            <div class="form-group">
                                <b>Оплата через:</b><br/>
                                <select name="mode">
                                    <?php foreach ($list_pay as $id => $name): ?>
                                        <option value="<?= $id; ?>"><?= $name; ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <div class="form-group">
                                <input id="send" type="submit" name="submit_adv" value="Перейти к оплате"
                                       class="btn btn-primary btn-block"
                                       title="НАЖИМАЯ КНОПКУ, ВЫ АВТОМАТИЧЕСКИ СОГЛАШАЕТЕСЬ С НИЖЕ ПЕРЕЧИСЛЕННЫМИ ПРАВИЛАМИ!!!"/>
                            </div>
                        </form>
                    <?php else: ?>
                        <h5>Покупка iFrame трафика</h5>
                        <hr>
                        <form method="post">
                            <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token']; ?>">
                            <div class="form-group">
                                <label>URL сайта[<?= $max_url; ?>]:</label>
                                <input id="url" name="url" type="text" maxlength="<?= $max_url; ?>" class="form-control"
                                       value="https://"/>
                                <p id="err" style="color:red; font-size: small; display: none"><?= $errorMessages['link_banned']; ?></p>
                            </div>
                            <div class="form-group">
                                <label>Количество дней[1-<?= $ism; ?>]:</label>
                                <input name="days" type="number" min="1" max="<?= $ism; ?>" class="form-control"
                                       value="7"/>
                            </div>
                            <div class="form-group">
                                <img src="/captcha/captcha-st/captcha.php" alt="Captcha" style="margin-bottom: 10px;">
                                <input name="captcha" type="text" class="form-control" placeholder="Введите капчу"
                                       required>
                            </div>
                            <div class="form-group">
                                <b>Стоимость размещения в день: <?= $isd; ?> руб.</b>
                            </div>

                            <div class="form-group">
                                <b>Оплата через:</b><br/>
                                <select name="mode">
                                    <?php foreach ($list_pay as $id => $name): ?>
                                        <option value="<?= $id; ?>"><?= $name; ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="form-group">
                                <input id="send" type="submit" name="submit" value="Перейти к оплате"
                                       class="btn btn-primary btn-block"
                                       title="НАЖИМАЯ КНОПКУ, ВЫ АВТОМАТИЧЕСКИ СОГЛАШАЕТЕСЬ С ПРАВИЛАМИ!!!"/>
                            </div>
                        </form>
                    <?php endif; ?>
                </div>
            </div>
            <div class="col-lg-4 col-md-3"></div>
        </div>
    </div>

    <script>
        window.onload = function () {
            let link = document.getElementById('url');

            link.onchange = () => {
                let link_id = link.value;

                fetch('/api/api.php', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                    body: new URLSearchParams({ 'key': link_id}).toString()
                })
                    .then(res => res.json())
                    .then(data => {
                        if (data === 200) {
                            document.getElementById('err').style.display = 'none';
                            document.getElementById('send').disabled = false;
                        } else {
                            document.getElementById('err').style.display = 'block';
                            document.getElementById('send').disabled = true;
                            return false;
                        }
                    })
                    .catch(error => console.error('Ошибка:', error));
            };
        };
    </script>
<?php
include_once ROOT . '/sys/foot.php';