<?php
require_once($_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/main/include/prolog_admin_before.php');
$APPLICATION->SetTitle(("Модуль mibazarow_pushsender_main"));
require($_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/main/include/prolog_admin_after.php");

use Bitrix\Main\Loader;
use Bitrix\Main\Config\Option;

Loader::includeModule('mibazarow.pushsender');

if (
    (!empty($_POST['PU_NAME'])) and
    (!empty($_POST['PU_MESS'])) and
    (!empty(bitrix_sessid_post()))
) {
    $jsonString = Option::get('mibazarow.pushsender', 'firibase_json');
    $token = \mibazarow\pushsender\FirebaseToken::getAccessToken($jsonString);

    // URL для отправки уведомлений
    $url = 'https://fcm.googleapis.com/v1/projects/ru-tech-bxstore/messages:send';

    $message = [
        "message" => [
            'topic' => 'main_topik',
            "notification" => [
                'title' => $_POST['PU_NAME'],
                'body' => $_POST['PU_MESS'],
            ]
        ]
    ];

    // Заголовки запроса
    $headers = [
        'Authorization: Bearer ' . $token, // Токен доступа
        'Content-Type: application/json'
    ];

    // Инициализация cURL
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($message));

    // Execute curl session
    $result = curl_exec($ch);
    if ($result === FALSE) {
        echo 'Ошибка: ' . curl_error($ch);
    }
//    echo '<pre>';
//    print_r($result);
//    echo '</pre>';
    curl_close($ch);
    echo 'Отправлено';

    // Закрытие cURL
    curl_close($ch);
}
?>


    <form class="form_push" name="iblock_add" action="<?= POST_FORM_ACTION_URI ?>" method="post"
          enctype="multipart/form-data">
        <?= bitrix_sessid_post() ?>
        <table class="nopadding" width="500" id="tbFILTER_MASKS">
            <tbody>
            <tr>
                <td nowrap="" style="padding-bottom: 10px;">
                    <input required type="text" value="" style="width: 100%;" name="PU_NAME" placeholder="Заголовок">
                </td>
            </tr>
            <tr>
                <td nowrap="" style="padding-bottom: 10px;">
                <textarea id="message" name="PU_MESS" style="width: 100%;" rows="4" cols="50" required
                          placeholder="Сообщение"></textarea>
                </td>
            </tr>
            <tr>
                <td nowrap="" style="padding-bottom: 3px;">
                    <input type="submit" value="Отправить">
                </td>
            </tr>
            </tbody>
        </table>
    </form>


<?php


require($_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/main/include/epilog_admin.php');
