<?php

/*
 * @component UserPoints
 * @copyright Copyright (C) 2015-2022 Bernard Gilly - Adrien Roussel - Martin Brampton
 * @license : GNU/GPL
 * @Website : https://remository.com
 */

namespace BlackSheepResearch\Component\UserPoints\Site\Problems;

defined('_JEXEC') or die;

use Joomla\CMS\Factory;
use Joomla\CMS\HTML\HTMLHelper;

class User extends ProblemBase {

    public static function getGroupsList(int $id = 0): string {
        $db = SQL::getInstance();
        $db->setQuery(
            'SELECT a.id AS value, a.title AS text, COUNT(DISTINCT b.id) AS level' .
            ' FROM #__usergroups AS a' .
            ' LEFT JOIN `#__usergroups` AS b ON a.lft > b.lft AND a.rgt < b.rgt' .
            ' GROUP BY a.id' .
            ' ORDER BY a.lft ASC'
        );
        foreach ($db->loadObjectList() as $group) {
            $group->text = str_repeat('- ', $group->level) . $group->text;
            $options[] = HTMLHelper::_('select.option', $group->value, $group->text);
        }
        return HTMLHelper::_('select.genericlist', ($options ?? []), 'content_items', 'class="inputbox" size="1"', 'value', 'text', $id);
    }

    public static function sendEmail(string $recipient, string $subject, string $body, bool $formatMail, bool $bcc2admin): bool {
        $mailer = Factory::getMailer();
        $app = Factory::getApplication();
        $mailer->setSender(array($app->getCfg('mailfrom'), $app->getCfg('fromname')));
        $mailer->setSubject($subject);
        $mailer->isHTML($formatMail);
        if ($formatMail) {
            $mailer->Encoding = 'base64';
        }
        $mailer->CharSet = "utf-8";
        $mailer->setBody($body);
        $mailer->addRecipient($recipient);

        if ($bcc2admin) {
            $db = SQL::getInstance();
            // get all users allowed to receive e-mail system
            $db->setQuery("SELECT `email` FROM `#__users` WHERE `sendEmail` = 1 AND `block` =0");
            foreach ((array) $db->loadObjectList() as $rowsAdmin) {
                $mailer->addBCC($rowsAdmin->email);
            }
        }
        return $mailer->Send();
    }
}
