<?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;

class RaffleInscription extends ProblemBase {

    protected static $fieldnames = [];
    protected static $fieldtypes = [];
    protected static $count = -1;
    protected static $tablename = '#__alpha_userpoints_raffle_inscriptions';
    protected static $updatetable = '#__alpha_userpoints_raffle_inscriptions';
    protected static $keyname = 'id';

    public function __construct(int $id = 0) {
        parent::__construct();
        if ($id) {
            $this->getOneRow($id);
        }
    }

    public static function withRaffleID (int $id) : array {
        $db = SQL::getInstance();
        $db->setQuery(sprintf("SELECT id, userid as uid FROM `%s` WHERE raffleid = %d", self::$tablename, $id));
        return $db->loadObjectList();
    }

    public static function selectedUsers (int $raffleID) : array {
        $db = SQL::getInstance();
        $query = "SELECT ari.userid AS uid, ari.ticket, u.name, u.username, u.email FROM #__alpha_userpoints_raffle_inscriptions AS ari "
            . " LEFT JOIN (SELECT id, name, username, email FROM #__users) AS u ON ari.userid = u.id "
            . " WHERE ari.raffleid = $raffleID";
        $db->setQuery($query);
        return (array) $db->loadObjectList();
    }

    public static function countByUserRaffle (int $userID, int $raffleID) : int {
        $db = SQL::getInstance();
        $db->setQuery(sprintf("SELECT COUNT(*) FROM `%s` WHERE userid = %d AND raffleid = %d", self::$tablename, $userID, $raffleID));
        return $db->loadResult();
    }
}
