<?php
defined('_JEXEC') or die;

jimport('joomla.user.helper');

class ModAlVoteHelper
{
    public static function getItem()
    {
        $result = array();

        $user = JFactory::getUser();

        $albumId = 4;

        try {
            $db = JFactory::getDbo();
            $query = $db->getQuery(true)
                ->select('a.*')
                ->from('www_archline_hu.jml_speasyimagegallery_albums as a')
                ->where('a.id = ' . (int) $albumId);

            $query->select('l.title AS language_title')
                ->leftJoin($db->quoteName('#__languages') . ' AS l ON l.lang_code = a.language');

            $query->select('ua.name AS author_name')
                ->leftJoin('#__users AS ua ON ua.id = a.created_by');

            // Filter by published state.
            $query->where('a.published = 1');

            $db->setQuery($query);
            $data = $db->loadObject();

            if (isset($data->id) && $data->id) {
                $data->images = self::getImages($data->id);
            }

            if (empty($data)) {
                return JError::raiseError(404, JText::_('COM_SPEASYIMAGEGALLERY_ERROR_ALBUM_NOT_FOUND'));
            }

            $user = JFactory::getUser();
            $groups = $user->getAuthorisedViewLevels();
            if (!in_array($data->access, $groups)) {
                return JError::raiseError(404, JText::_('COM_SPEASYIMAGEGALLERY_ERROR_ALBUM_NOT_AUTHORISED'));
            }

            $result[$albumId] = $data;
        } catch (Exception $e) {
            if ($e->getCode() == 404) {
                JError::raiseError(404, $e->getMessage());
            } else {
                $result[$albumId] = false;
            }
        }

        return $result[$albumId];
    }

    public static function isVoted($pictureId, $albumId, $userId)
    {
        $db = JFactory::getDbo();

        $query = "SELECT id FROM www_archline_hu.al_picture_vote 
            WHERE picture_id = {$pictureId} AND album_id = {$albumId} AND nUserID = {$userId}";
        $db->setQuery($query);
        $existingVote = $db->loadObject();

        return !empty($existingVote);
    }

    public static function getImages($album_id)
    {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select(array('a.*', 'b.picture_id', 'count(b.userID) AS voteCount'));
        $query->from($db->quoteName('www_archline_hu.jml_speasyimagegallery_images', 'a'));
        $query->join('LEFT', $db->quoteName('www_archline_hu.al_picture_vote', 'b') . ' ON ' . $db->quoteName('a.id') . ' = ' . $db->quoteName('b.picture_id'));
        $query->where($db->quoteName('a.album_id') . ' = ' . $db->quote($album_id));
        $query->where($db->quoteName('a.state') . ' = ' . $db->quote(1));
        $query->order('a.title ASC');
        $query->group($db->quoteName('a.id'));
        $db->setQuery($query);
        return $db->loadObjectList();
    }

    public static function votePicture($pictureId, $albumId, $userId, $nUserID)
    {
        $db = JFactory::getDbo();

        $query = "SELECT id FROM www_archline_hu.al_picture_vote 
            WHERE picture_id = {$pictureId} AND album_id = {$albumId} AND nUserID = {$nUserID}";
        $db->setQuery($query);
        $existingVote = $db->loadObject();

        if (!empty($existingVote))
            return false;

        $vote               = new stdClass();
        $vote->picture_id   = $pictureId;
        $vote->album_id     = $albumId;
        $vote->userID       = $userId;
        $vote->nUserID      = $nUserID;
        JFactory::getDbo()->insertObject('www_archline_hu.al_picture_vote', $vote);

        if ($nUserID != null && $nUserID != '') {
            $topic = (JFactory::getLanguage()->getTag() == 'hu-HU' ? 322 : 153);

            $query = "SELECT * FROM cl_hlusers.u_history
                WHERE nUserID = {$nUserID} AND nTopicID = {$topic} AND strPlace = 'Rendering pályázat 2023 szavazás'";
            $db->setQuery($query);
            $existingVote = $db->loadObject();

            if (empty($existingVote)) {
                $history                = new stdClass();
                $history->nUserID       = $nUserID;
                $history->nTopicID      = $topic;
                $history->dateEvent     = date('Y-m-d');
                $history->strPlace      = 'Rendering pályázat 2023 szavazás';
                $history->strInfo       = 'Rendering pályázat 2023 szavazás';
                $history->nManagerID    = 36;
                JFactory::getDbo()->insertObject('cl_hlusers.u_history', $history);
            }
        }

        return true;
    }

    public static function getWinnerPictures($album_id)
    {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select(array('a.*', 'b.*', 'count(b.userID) AS voteCount'));
        $query->from($db->quoteName('www_archline_hu.jml_speasyimagegallery_images', 'a'));
        $query->join('LEFT', $db->quoteName('www_archline_hu.al_picture_vote', 'b') . ' ON ' . $db->quoteName('a.id') . ' = ' . $db->quoteName('b.picture_id'));
        $query->where($db->quoteName('a.album_id') . ' = ' . $db->quote($album_id));
        $query->where($db->quoteName('a.state') . ' = ' . $db->quote(1));
        $query->order('count(b.userID) DESC');
        $query->group($db->quoteName('a.id'));
        $db->setQuery($query);
        $winners = $db->loadObjectList();

        for ($i = 0; $i < count($winners); $i++)
            $winners[$i]->source = json_decode($winners[$i]->images);

        return $winners;
    }
}
