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

jimport('joomla.user.helper');

class ModAlNewsletterHelper
{
    public static function insertUser($name, $email)
    {
        $db = JFactory::getDbo();

        $query = "SELECT u_emails_id, nUserID, newsletter FROM cl_hlusers.u_emails WHERE email = '{$email}'";
        $db->setQuery($query);
        $existingUser = $db->loadObject();

        if (!empty($existingUser)) {
            if ($existingUser->newsletter == 1)
                return true;

            $db->getQuery(true);
            $query = "UPDATE cl_hlusers.u_emails SET newsletter = 1 WHERE u_emails_id = '{$existingUser->u_emails_id}'";
            $db->setQuery($query);
            $db->execute();

            return true;
        }

        $old_db = (JFactory::getLanguage()->getTag() == 'hu-HU' ? "clusers" : "clusers_eng");
        $ctrID  = (JFactory::getLanguage()->getTag() == 'hu-HU' ? 36 : 0);

        $user               = new stdClass();
        $user->strName      = $name;
        $user->strEMail     = $email;
        $user->nUserType    = 0;
        $user->nUserStatus  = 0;
        $user->nUserProf    = 0;
        $user->old_db       = $old_db;
        $user->nSchoolID    = 0;
        $user->nCtrID       = $ctrID;

        JFactory::getDbo()->insertObject('cl_hlusers.users', $user);

        $nUserID = $db->insertid();

        $history                = new stdClass();
        $history->nUserID       = $nUserID;
        $history->nTopicID      = (JFactory::getLanguage()->getTag() == 'hu-HU' ? 38 : 150);
        $history->dateEvent     = date('Y-m-d');
        $history->insertDate    = date('Y-m-d H:i:s');
        $history->strPlace      = 'web';
        $history->nManagerID    = 36;

        JFactory::getDbo()->insertObject('cl_hlusers.u_history', $history);

        $emails             = new stdClass();
        $emails->email      = $email;
        $emails->nUserID    = $nUserID;
        $emails->default    = 1;
        $emails->active     = 1;
        $emails->deleted    = 0;
        $emails->newsletter = 1;

        JFactory::getDbo()->insertObject('cl_hlusers.u_emails', $emails);

        return true;
    }
}
