<?php
QUnit_Global::includeFile("Adodb/adodb.inc.php");

class QCore_Bl_GlobalDb
{
    var $dbConnection;
    
    //--------------------------------------------------------------------------
    
    function QCore_Bl_GlobalDb() {
        if (GLOBAL_DB_ENABLED == 1) {
            $this->dbConnection =& NewADOConnection('mysql');
            $this->dbConnection->Connect(DB_HOSTNAME,DB_USERNAME,DB_PASSWORD,DB_DATABASE, true);
        }
    }
    
    //--------------------------------------------------------------------------
    
    function &getInstance() {
        static $instance;
        if (is_object($instance)) {
            return $instance;
        }
        return new QCore_Bl_GlobalDb();
    }
    
    //--------------------------------------------------------------------------
    // $params (array): userids, liteaccountid, status

    function changeUserStatus($params) {
        if (GLOBAL_DB_ENABLED != 1)
            return true;
        
        $userIDs = $params['userids'];
        if(!is_array($userIDs) || count($userIDs) < 1)
            return false;

        $chunkedUserIDs = my_array_chunk($userIDs, WD_MAX_PROCESSED_IDS);

        foreach($chunkedUserIDs as $userIDsArray)
        {
            $userIDSql = "('".implode("','", $userIDsArray)."')";

            $sql = 'update wd_c_users set userstatus='._q($params['status']).
                   ' where userid in '.$userIDSql.
                   '   and liteaccountid='._q($params['liteaccountid']);
            $rs = $this->dbConnection->Execute($sql);
            if (!$rs)
            {
                QUnit_Messager::setErrorMessage(L_G_DBERROR);
                return false;
            }
        }
    }
    
    //--------------------------------------------------------------------------
    // $params (array): userids, liteaccountid

    function deleteUser($params)
    {
        if (GLOBAL_DB_ENABLED != 1)
            return true;
            
        $userIDs = $params['userids'];
        if(!is_array($userIDs) || count($userIDs) < 1)
            return false;

        $chunkedUserIDs = my_array_chunk($userIDs, WD_MAX_PROCESSED_IDS);

        foreach($chunkedUserIDs as $userIDsArray)
        {
            $userIDSql = "('".implode("','", $userIDsArray)."')";

            $sql = 'delete from wd_c_users '.
                   ' where userid in '.$userIDSql.
                   '   and liteaccountid='._q($GLOBALS['Auth']->getSetting('AffPlanet_account_id'));
            $rs = $this->dbConnection->Execute($sql);
            if (!$rs)
            {
                QUnit_Messager::setErrorMessage(L_G_DBERROR);
                return false;
            }
        }

        return true;
    }
    
    //--------------------------------------------------------------------------
    // $params (array): userid, liteaccountid, username, refid, password

    function updateUser($params)
    {
        if (GLOBAL_DB_ENABLED != 1)
            return true;
            
        $sql = 'update wd_c_users set ';
        if ($params['username'] != '')
            $sql .= 'username='._q($params['username']).',';
        if ($params['refid'] != '')
            $sql .= 'refid='._q($params['refid']).',';
        if($params['password'] != '')
            $sql .= 'rpassword='._q($params['password']).',';
        $sql = rtrim($sql, ',');
        $sql .= ' where userid='._q($params['userid']).
                '   and liteaccountid='._q($params['liteaccountid']);

        $ret = $this->dbConnection->Execute($sql);
        
        if(!$ret)
        {
            QUnit_Messager::setErrorMessage(L_G_DBERROR);
            return false;
        }

        return true;
    }
    
    //--------------------------------------------------------------------------
    // $params (array): userid, liteaccountid, username, refid, password, type, status
    
    function insertUser($params)
    {
        if (GLOBAL_DB_ENABLED != 1)
            return true;
            
        $sql = 'insert into wd_c_users (userid, refid, '.
               'liteaccountid, username, '.
               'rpassword, usertype, userstatus)'.
               ' values('._q($params['userid']).','._q($params['refid']).','.
               _q($params['liteaccountid']).','._q($params['username']).','.
               _q($params['password']).','._q($params['type']).','._q($params['status']).')';
        
        $ret = $this->dbConnection->Execute($sql);
        if(!$ret)
        {
            QUnit_Messager::setErrorMessage(L_G_DBERROR);
            return false;
        }
        
        return true;
    }
    
    //--------------------------------------------------------------------------
    // $params (array): userid, liteaccountid, view_old
    
    function getMerchantNews($params)
    {
        if (GLOBAL_DB_ENABLED != 1)
            return true;
        
        if($params['liteaccountid'] == '') return false;

        $sql = 'select m.dateinserted, m.title, m.rtext, m.messageid, mu.rstatus '.
               'from wd_g_messages m left join wd_g_messagestousers mu on (m.messageid = mu.messageid and mu.userid='._q($params['userid']).' and mu.lid='._q($params['liteaccountid']).')'.
               'where m.active='._q('1').
               '  and m.datevalidfrom < NOW()'.
               '  and NOW() < m.datevalidto';
        if($params['userid'] != '') $sql .= '  and ((mu.userid='._q($params['userid']).' and mu.lid='._q($params['liteaccountid']).') or (mu.userid is null and m.showtoall='._q('1').'))';
        $sql .= '  and m.deleted=\'0\''.
               '  and (m.rtype='._q(MESSAGETYPE_NEWS).' or m.rtype='._q(SA_MESSAGETYPE_NEWS).')';
        if($params['view_old'] != '1')
            $sql .= '  and (mu.rstatus='._q(MESSAGESTATUS_NOT_READED).' or mu.rstatus='._q(MESSAGESTATUS_SHOW).' or (mu.rstatus is null and m.showtoall='._q('1').') )';
        $sql .= ' order by m.dateinserted desc, m.title';
        
        $rs = $this->dbConnection->Execute($sql);

        if(!$rs) {
            return array();
        }
        
        $user = $this->loadUserData($params);

        $news = array();

        while(!$rs->EOF)
        {
            $news[$rs->fields['messageid']]['messagetouserid'] = $rs->fields['messagetouserid'];
            $news[$rs->fields['messageid']]['messageid'] = $rs->fields['messageid'];
            $news[$rs->fields['messageid']]['dateinserted'] = $rs->fields['dateinserted'];
            $news[$rs->fields['messageid']]['title'] = $rs->fields['title'];
            $news[$rs->fields['messageid']]['rtext'] = $rs->fields['rtext'];
            $news[$rs->fields['messageid']]['status'] = $rs->fields['rstatus'];

            $strs = array('title' => $news[$rs->fields['messageid']]['title'],
                          'text'  => $news[$rs->fields['messageid']]['rtext']);

            $strs = $this->replaceInNews($user, $strs);

            $news[$rs->fields['messageid']]['title'] = $strs['title'];
            $news[$rs->fields['messageid']]['rtext'] = $strs['text'];

            $rs->MoveNext();
        }

        return $news;
    }
    
    //--------------------------------------------------------------------------

    function loadUserData($params)
    {
        $sql = "select accountname from wd_c_liteaccounts where liteaccountid="._q($params['liteaccountid']);
        $rs = $this->dbConnection->Execute($sql);

        if(!$rs || $rs->EOF) {
            return array();
        }
        
        $user = array('liteaccountid' => $params['liteaccountid'],
                      'accountname' => $rs->fields['accountname']);
                      
        $sql = "select name, surname from wd_g_users where userid="._q($params['userid']);
        $rs = QCore_Sql_DBUnit::execute($sql, __FILE__, __LINE__);
        if(!$rs || $rs->EOF) {
            return $user;
        }
        
        $user['name'] = $rs->fields['name'];
        $user['surname'] = $rs->fields['surname'];
        
        return $user;
    }
    
    //--------------------------------------------------------------------------

    function replaceInNews($user, $strs)
    {
        if(!is_array($strs) || count($strs) < 1) return false;

        foreach($strs as $key => $str)
        {
            $str = str_replace('$Date', date("Y-m-d"), $str);
            $str = str_replace('$Time', date("h:i:s"), $str);
            $str = str_replace('$Liteaccountid', $GLOBALS['Auth']->getLiteAccountID(), $str);
            $str = str_replace('$Name',          $user['name'].' '.$user['surname'], $str);
            $str = str_replace('$Firstname',     $user['name'], $str);
            $str = str_replace('$Surname',       $user['surname'], $str);
            $str = str_replace('$Accountname',   $user['accountname'], $str);

            $strs[$key] = $str;
        }

        return $strs;
    }
    
    //--------------------------------------------------------------------------

    function changeMessageStatus($mid, $userid, $lid, $status = MESSAGESTATUS_SHOW)
    {
        $sql = 'select messagetouserid from wd_g_messagestousers'.
               ' where messageid='._q($mid).
               '   and userid='._q($userid).
               '   and lid='._q($lid);
        $ret = $this->dbConnection->Execute($sql);
        if(!$ret) {
            QUnit_Messager::setErrorMessage(L_G_DBERROR);
            return false;
        }
        
        if ($ret->fields['messagetouserid'] != '') {        
            $sql = 'update wd_g_messagestousers set rstatus='._q($status).
                   ' where messagetouserid='._q($ret->fields['messagetouserid']);
            $ret = $this->dbConnection->Execute($sql);
            if(!$ret) {
                QUnit_Messager::setErrorMessage(L_G_DBERROR);
                return false;
            }
        } else {
            $MessagetouserID = QCore_Sql_DBUnit::createUniqueID('wd_g_messagestousers', 'messagetouserid');
            $sql = 'insert into wd_g_messagestousers '.
                   '(messagetouserid, messageid, userid, lid, email, rstatus) values '.
                   '('._q($MessagetouserID).','._q($mid).','._q($userid).','._q($lid).
                     ','._q($GLOBALS['Auth']->getUsernameForUser($userid)).','._q($status).')';
            $ret = $this->dbConnection->Execute($sql);
            if(!$ret) {
                QUnit_Messager::setErrorMessage(L_G_DBERROR);
                return false;
            }
        }

        return true;
    }
    
}

?>
