<?php
/*
 * JohnCMS NEXT Mobile Content Management System (http://johncms.com)
 *
 * For copyright and license information, please see the LICENSE.md
 * Installing the system or redistributions of files must retain the above copyright notice.
 *
 * @link        http://johncms.com JohnCMS Project
 * @copyright   Copyright (C) JohnCMS Community
 * @license     GPL-3
 */

defined('_IN_JOHNADM') or die('Error: restricted access');

/** @var Psr\Container\ContainerInterface $container */
$container = App::getContainer();

/** @var Johncms\Api\UserInterface $systemUser */
$systemUser = $container->get(Johncms\Api\UserInterface::class);

/** @var Johncms\Api\ToolsInterface $tools */
$tools = $container->get(Johncms\Api\ToolsInterface::class);

/** @var Johncms\Api\BbcodeInterface $bbcode */
$bbcode = $container->get(Johncms\Api\BbcodeInterface::class);

// Проверяем права доступа
if ($systemUser->rights < 7) {
    header('Location: http://johncms.com/?err');
    exit;
}

echo '<div class="mainblok"><div class="phdr"><a href="index.php"><b>Admin panel</b></a>&nbsp;|&nbsp;Mail delivery</div>';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $msg = isset($_POST['msgtoall']) ? $tools->checkin(mb_substr(trim($_POST['msgtoall']), 0, 5000)) : '';
    $theme = isset($_POST['theme']) ? $tools->checkin(mb_substr(trim($_POST['theme']), 0, 100)) : '';
    $me = isset($_POST['me']) ? abs(intval($_POST['me'])) : 0;
    $author = isset($_POST['author']) ? abs(intval($_POST['author'])) : 0;
    $who = isset($_POST['who']) ? $_POST['who'] : '';

    $error = [];
    if (empty($msg))
        $error[] = 'Enter your message!';
    if (empty($who))
        $error[] = 'You have not selected recipients!';
    if (in_array('all', $who) && (in_array('only_adm', $who) || in_array('only_usr', $who) || in_array('only_mans', $who) || in_array('only_girls', $who)))
        $error[] = 'Incorrectly choice of destinations! You can not simultaneously select all users and different "casts" users of the site!';
    if ((in_array('only_adm', $who) && in_array('only_usr', $who)) || (in_array('only_mans', $who) && in_array('only_girls', $who)))
        $error[] = 'Incorrect choice of destinations! You can not choose both users and administrators, or boys and girls!';

    if (!$error) {
        if (in_array('all', $who)) // All users
            $sql = "SELECT id FROM users WHERE id != $systemUser->id";
        elseif (in_array('only_adm', $who)) // administration Only
            $sql = "SELECT id FROM users WHERE rights > 0 AND id != $systemUser->id";
        elseif (in_array('only_adm', $who) && in_array('only_mans', $who)) //Only administration, specifying only pair
            $sql = "SELECT id FROM users WHERE rights > 0 AND sex = 'm' AND id != $systemUser->id";
        elseif (in_array('only_adm', $who) && in_array('only_girls', $who)) //Only administration, specifying only girls
            $sql = "SELECT id FROM users WHERE rights > 0 AND sex = 'zh' AND id != $systemUser->id";
        elseif (in_array('only_usr', $who)) // Only simple users
            $sql = "SELECT id FROM users WHERE rights = 0 AND id != $systemUser->id";
        elseif (in_array('only_usr', $who) && in_array('only_mans', $who)) // Only users with a simple refinement only pair
            $sql = "SELECT id FROM users WHERE rights = 0 AND sex = 'm' AND id != $systemUser->id";
        elseif (in_array('only_usr', $who) && in_array('only_girls', $who)) // Only users with a simple refinement only girls
            $sql = "SELECT id FROM users WHERE rights = 0 AND sex = 'zh' AND id != $systemUser->id";
        elseif (in_array('only_mans', $who)) // Только парням
            $sql = "SELECT id FROM users WHERE sex = 'm' AND id != $systemUser->id";
        elseif (in_array('only_girls', $who)) // Only boys
            $sql = "SELECT id FROM users WHERE sex = 'zh' AND id != $systemUser->id";
        else
            echo $tools->displayError('She is qualified even some mistake...', '<a href="?act=send_mail">To try one more time</a>');

        $req = $db->query($sql) or die($db->error());
        while ($res = $req->fetch())
            $arr_des[] = $res['id'];
        if ($me == 1)
            $arr_des[] = $systemUser->id;

        if (!empty($arr_des)) {
            if ($author == 1)
                $msg .= "\n\nYours faithfully, [b]$systemUser->name [/b]";
            foreach ($arr_des as $des) {
                        $db->prepare('
                          INSERT INTO `cms_mail` SET
                          `user_id` = 0,
                          `from_id` = ?,
                          `text` = ?,
                          `time` = ?,
                          `sys` = 1,
                          `them` = ?
                        ')->execute([
                            $des,
                            $msg,
                            time(),
                            $theme,
                        ]);

            }
            echo '<div class="gmenu">Broadcast Sent To ' . count($arr_des) . ' Users!</div>';
            header('Refresh:3; url=?act=broadcast');
        }
        else {
            echo $tools->displayError('Unfortunately, the selected destination does not exist...', '<a href="?act=broadcast">' . _t('The Recipients Do Not Exist. Try Again') . '</a>');
        }
    }
    else {
        echo $tools->displayError($error, '<a href="?act=broadcast">' . _t('Try Again') . '</a>');
    }
}
else {
    echo '<div class="gmenu"><form name="formmsg" action="?act=broadcast" method="post">' .
        '<p><b>Subject (100):</b></p>'  .
        '<input type="text" name="theme" value="">' .
        '<p><b>Message text (5000):</b></p>' . $bbcode->buttons('formmsg', 'msgtoall') .
        '<textarea name="msgtoall" rows="' . $systemUser->getConfig()->fieldHeight . '"></textarea>' .
        '<p><b>' . _t('Sending message to users doesnt include sending to the author. You need to select the required options') . '</b></p>' .
        '<input type="checkbox" name="me" value="1">&nbsp;' . _t('Send a copy to mailer') . '<br>' .
        '<input type="checkbox" name="who[]" value="only_adm">&nbsp;' . _t('Broadcast to administrators only') . '<br>' .
        '<input type="checkbox" name="who[]" value="only_usr">&nbsp;' . _t('Broadcast to users only') . '<br>' .
        '<input type="checkbox" name="who[]" value="all">&nbsp;' . _t('Broadcast to every members, inclusive staffs') . '<br>' .
        '<input type="checkbox" name="who[]" value="only_mans">&nbsp;' . _t('Broadcast to guys only') . '<br>' .
        '<input type="checkbox" name="who[]" value="only_girls">&nbsp;' . _t('Broadcast to ladies only') . '' .
        '<p><i>* Points "Newsletter only boys "and" girls only subscribe "can also be used as a refinement of the points" subscribe only administration "and" Send Only simple users"</i></p>' .
        '<p><b>Setup (enabled by default mapping of the distribution of the author):</b></p>' .
        '<input type="checkbox" name="author" value="1" checked>&nbsp;' . _t('Specify Author In Message As Conclusion') . '' .
        '<p><input type="submit" value="' . _t('Send Broadcast') . '"></p>' .
        '</form></div>';
}

echo '<div class="phdr"><a href="index.php">Back</a></div>';