<?php
class Affiliate_Scripts_Bl_Data
{
    var $userID = '';
    var $userType = '';
    var $errorMsg = '';
    var $currentDate = '';
    var $viewCampCategManager;
    var $recordsLimit = '';
    
    //------------------------------------------------------------------------

    function Affiliate_Scripts_Bl_Data() {
        $this->currentDate = date("Y-m-d");
        //$this->currentDate = '2006-08-06';
        //$this->currentDate = '2005-05-08';
        
        $this->recordsLimit = 10;
        $this->viewCampCategManager =& QUnit_Global::newObj('Affiliate_Merchants_Views_CampCategoriesManager');
    }

    //------------------------------------------------------------------------

    function getError() {
        return $this->errorMsg;
    }
    
    //------------------------------------------------------------------------

    function checkUser($username, $password) {
        $password = $password;
        $epassword = md5($password);
        $accountid = 'default1';

        $sql = 'select userid, accountid, rtype, rstatus '.
               'from wd_g_users '.
               'where username='._q($username).
               '  and accountid='._q($accountid);

        $sql .= ' and (rpassword like '._q('%'.$password).' or rpassword like '._q('%'.$epassword).')';

        $sql .= '  and deleted='._q('0').
                '  and rtype in ('._q(USERTYPE_USER).', '._q(USERTYPE_ADMIN).')';
        if($type == USERTYPE_USER) {
            $sql .= ' and rstatus='._q(AFFSTATUS_APPROVED);
        } elseif ($type == USERTYPE_ADMIN) {
            $sql .= ' and rstatus='._q(STATUS_ENABLED);
        }

        $rs = $GLOBALS['db']->execute($sql);
        $GLOBALS['dbrequests']++;
        if (!$rs || $rs->EOF) {
            $this->errorMsg = "User doesn't exist\n";
            return false;
        }
/*        
        if($rs->fields['rtype'] == USERTYPE_ADMIN && $rs->fields['rstatus'] != STATUS_ENABLED) {
            $this->errorMsg = "Admin is not enabled\n";
            return false;
        }
*/        
        if($rs->fields['rtype'] == USERTYPE_USER && $rs->fields['rstatus'] != AFFSTATUS_APPROVED) {
            $this->errorMsg = "Affiliate is not approved\n";
            return false;
        }
        
        $this->userID = $rs->fields['userid'];
        $this->userType = $rs->fields['rtype'];
        
        return true;
    }        

    //------------------------------------------------------------------------

    function getNotifications($params) {
        if($params['date'] != '') {
            $this->currentDate = $params['date'];
        }
        if($params['recordsLimit'] != '') {
            $this->recordsLimit = $params['recordsLimit'];
        }
        
        $data = array();
        
        if($this->userType == USERTYPE_ADMIN) {
            $data['stats'] = $this->getStats();
            $data['transactions'] = $this->getTransactions($params['lastTransId']);
            $data['signups'] = $this->getSignups($params['lastAffId']);
            $data['news'] = null;
            
        } else if ($this->userType == USERTYPE_USER) {
            $data['stats'] = $this->getStats();
            $data['transactions'] = $this->getTransactions($params['lastTransId']);
            $data['signups'] = null;
            $data['news'] = $this->getNews($params['lastNewsId']);
        }
        
        return $this->translateDataToXML($data);
    }
    
    //------------------------------------------------------------------------
    
    function getStats() {
        $stats['fordate'] = $this->currentDate;
        $stats['usertype'] = ($this->userType == USERTYPE_ADMIN ? 'merchant' :'affiliate');
        $stats['currency'] = 'U'; //$GLOBALS['Auth']->getSetting('Aff_system_currency');
        
        if($this->userType == USERTYPE_USER) {
            $balances = $this->getAffiliateBalance();
            $stats['approved'] = $balances['approved'];
            $stats['pending'] = $balances['pending'];
            $stats['declined'] = $balances['declined'];
            
            $todayStats = $this->getTodayStats($this->userID);
            
            $stats['today_clicks'] = $todayStats['clicks_approved'];
            $stats['today_impressions'] = $todayStats['impressions'];
            $stats['today_unique_impressions'] = $todayStats['unique_impressions'];
            
            $stats['today_sales_approved'] = $todayStats['sales_approved'];
            $stats['today_leads_approved'] = $todayStats['leads_approved'];
            $stats['today_sales_pending'] = $todayStats['sales_waitingapproval'];
            $stats['today_leads_pending'] = $todayStats['leads_waitingapproval'];
            $stats['today_sales_declined'] = $todayStats['sales_declined'];
            $stats['today_leads_declined'] = $todayStats['leads_declined'];
        } else if($this->userType == USERTYPE_ADMIN) {
            $affStats = $this->getAffiliateStats();
            if($affStats != false) {
                $stats['affiliates_approved'] = $affStats['affiliates_approved'];
                $stats['affiliates_pending'] = $affStats['affiliates_pending'];
                $stats['affiliates_declined'] = $affStats['affiliates_declined'];
            } else {
                $stats['affiliates_approved'] = 0;
                $stats['affiliates_pending'] = 0;
                $stats['affiliates_declined'] = 0;
            }
            
            $todayStats = $this->getTodayStats('');
            
            $stats['today_clicks'] = $todayStats['clicks_approved'];
            $stats['today_impressions'] = $todayStats['impressions'];
            $stats['today_unique_impressions'] = $todayStats['unique_impressions'];
            
            $stats['today_sales_approved'] = $todayStats['sales_approved'];
            $stats['today_leads_approved'] = $todayStats['leads_approved'];
            $stats['today_sales_pending'] = $todayStats['sales_waitingapproval'];
            $stats['today_leads_pending'] = $todayStats['leads_waitingapproval'];
            $stats['today_sales_declined'] = $todayStats['sales_declined'];
            $stats['today_leads_declined'] = $todayStats['leads_declined'];
        }
        
        return array($stats);
    }
    
    //------------------------------------------------------------------------

    function getAffiliateStats() {
        $sql = 'select count(*) as rcount, rstatus from wd_g_users '.
               'where rtype='._q(USERTYPE_USER).
               '  and accountid='._q($GLOBALS['Auth']->getAccountID()).
               '  and deleted=0'.
               ' group by rstatus';
        $rs = QCore_Sql_DBUnit::execute($sql, __FILE__, __LINE__);
        if (!$rs) {
            return false;
        }

        if($rs->EOF) {
            return false;
        }

        $approved = 0;
        $waiting = 0;
        $declined = 0;

        while(!$rs->EOF) {
            $status = $rs->fields['rstatus'];

            if($status == AFFSTATUS_APPROVED) {
                $approved = $rs->fields['rcount'];
            } else if($status == AFFSTATUS_NOTAPPROVED) {
                $waiting = $rs->fields['rcount'];
            } else if($status == AFFSTATUS_SUPPRESSED) {
                $declined = $rs->fields['rcount'];
            }

            $rs->MoveNext();
        }
        
        $data = array();
        $data['affiliates_approved'] = $approved;
        $data['affiliates_pending'] = $waiting;
        $data['affiliates_declined'] = $declined;
        
        return $data;
    }
    
    //------------------------------------------------------------------------
    
    function getTodayStats($userID) {
        $dateParts = explode('-', $this->currentDate);
        $d1 = $dateParts[2];
        $m1 = $dateParts[1];
        $y1 = $dateParts[0];
            
        $timerangeStats =& QUnit_Global::newObj('Affiliate_Scripts_Bl_TimerangeStatistics');
            
        return $timerangeStats->getTimerangeStats(
                    $userID, '', $d1, $m1, $y1, $d1, $m1, $y1,
                    'default1'
                    );            
    }
    
    //------------------------------------------------------------------------
    
    function getAffiliateBalance() {
        $conditions = array(
            'CampaignID' => '',
            'UserID' => $this->userID,
            'TransactionType' => '',
            'Status' => '',
            'page' => '',
            'rowsPerPage' => '',
            'day1' => 1,
            'month1' => 1,
            'year1' => 1980,
            'day2' => 1,
            'month2' => 1,
            'year2' => 2020
        );
        
        $saleStats =& QUnit_Global::newObj('Affiliate_Scripts_Bl_SaleStatistics');
        $transdata = $saleStats->getTransactionsSummaries($conditions);
        
        if($transdata != false) {
            return array(
                'approved' => $transdata[$this->userID]['approved'],
                'pending' => $transdata[$this->userID]['pending'],
                'declined' => $transdata[$this->userID]['reversed']);
        } else {
            return array(
                'approved' => 0,
                'pending' => 0,
                'declined' => 0);
        }
}
    
    //------------------------------------------------------------------------

    function getTransactions($lastTransId) {
        $lastDateInsertedNotified = '';
        
        if($lastTransId != '') {
            $sql = "select dateinserted from wd_pa_transactions where transid="._q($lastTransId);
            $rs = $GLOBALS['db']->execute($sql);
            $GLOBALS['dbrequests']++;
            
            if($rs && !$rs->EOF) {
                $lastDateInsertedNotified = $rs->fields['dateinserted'];
            }
        }

        $sql = "select a.userid, a.name, a.surname, a.weburl, a.username, t.transid, t.totalcost, t.orderid, t.productid, t.dateinserted, 
                t.rstatus, t.transtype, t.transkind, t.payoutstatus, t.dateapproved, t.commission, t.refererurl, t.ip, t.campcategoryid, 
                t.data1, t.data2, t.data3, t.countrycode

                from wd_pa_transactions t left join wd_pa_campaigncategories cc on t.campcategoryid=cc.campcategoryid, 
                wd_g_users a 

                where t.affiliateid=a.userid and a.accountid='default1' and t.transtype<>"._q(TRANSTYPE_CLICK)." and a.deleted=0 and a.rstatus in (2,1) 
                and TO_DAYS(t.dateinserted) >= TO_DAYS('".$this->currentDate."')";
                
        if($lastDateInsertedNotified != '') {
            $sql .= " and t.dateinserted>"._q($lastDateInsertedNotified);
        }
        
        if($this->userType == USERTYPE_USER) {
            $sql .= " and a.userid="._q($this->userID);
        }
        
        $sql .= " order by t.dateinserted LIMIT 0,".$this->recordsLimit;

        $rs = $GLOBALS['db']->execute($sql);
        $GLOBALS['dbrequests']++;
        if (!$rs || $rs->EOF) {
            return null;
        }
        
        $campaigns = $this->viewCampCategManager->getCampCategoriesAsArray();
        $campaigns[0] = array('campaignid' => 0,
            				  'name' => L_G_NOCAMPAIGN,
            				  'commtype' => TRANSTYPE_REFUND | TRANSTYPE_CHARGEBACK);
                              
        $transactions = array();
        while(!$rs->EOF) {
            $transaction = array();
                
            $transaction['userid'] = $rs->fields['userid'];
            $transaction['name'] = $rs->fields['name'];
            $transaction['surname'] = $rs->fields['surname'];
            $transaction['weburl'] = $rs->fields['weburl'];
            $transaction['username'] = $rs->fields['username'];
            $transaction['transid'] = $rs->fields['transid'];
            $transaction['totalcost'] = $rs->fields['totalcost'];
            $transaction['orderid'] = $rs->fields['orderid'];
            $transaction['productid'] = $rs->fields['productid'];
            $transaction['dateinserted'] = $rs->fields['dateinserted'];
            $transaction['rstatus'] = $rs->fields['rstatus'];
            $transaction['transtype'] = $rs->fields['transtype'];
            $transaction['transkind'] = $rs->fields['transkind'];
            $transaction['payoutstatus'] = $rs->fields['payoutstatus'];
            $transaction['dateapproved'] = $rs->fields['dateapproved'];
            $transaction['commission'] = $rs->fields['commission'];
            $transaction['refererurl'] = $rs->fields['refererurl'];
            $transaction['campcategoryid'] = $rs->fields['campcategoryid'];
            $transaction['campaign'] = $campaigns[$rs->fields['campcategoryid']];
            $transaction['data1'] = $rs->fields['data1'];
            $transaction['data2'] = $rs->fields['data2'];
            $transaction['data3'] = $rs->fields['data3'];
            $transaction['countrycode'] = $rs->fields['countrycode'];
            
            $transactions[] = $transaction;
            $rs->MoveNext();
        }
        
        return $transactions;
    }
    
    //------------------------------------------------------------------------
    
    function getSignups($lastAffId) {
        $lastDateInsertedNotified = '';
        
        if($lastAffId != '') {
            $sql = "select dateinserted from wd_g_users where userid="._q($lastAffId);
            $rs = $GLOBALS['db']->execute($sql);
            $GLOBALS['dbrequests']++;
            
            if($rs && !$rs->EOF) {
                $lastDateInsertedNotified = $rs->fields['dateinserted'];
            }
        }
        
        $sql = "select * from wd_g_users where rtype="._q(USERTYPE_USER).
                " and deleted=0 and dateinserted>="._q($this->currentDate);
        if($lastDateInsertedNotified != '') {
            $sql .= " and dateinserted>"._q($lastDateInsertedNotified);
        }
        $sql .= " order by dateinserted LIMIT 0,".$this->recordsLimit;
        
        $rs = $GLOBALS['db']->execute($sql);
        $GLOBALS['dbrequests']++;
        if (!$rs || $rs->EOF) {
            return null;
        }
        
        $signups = array();
        while(!$rs->EOF) {
            $signup = array();
            $signup['userid'] = $rs->fields['userid'];
            $signup['refid'] = $rs->fields['refid'];
            $signup['username'] = $rs->fields['username'];
            $signup['name'] = $rs->fields['name'];
            $signup['surname'] = $rs->fields['surname'];
            $signup['company_name'] = $rs->fields['company_name'];
            $signup['weburl'] = $rs->fields['weburl'];
            $signup['street'] = $rs->fields['street'];
            $signup['city'] = $rs->fields['city'];
            $signup['state'] = $rs->fields['state'];
            $signup['country'] = $rs->fields['country'];
            $signup['rstatus'] = $rs->fields['rstatus'];

            $signups[] = $signup;
            $rs->MoveNext();
        }
        
        return $signups;
    }
    
    //------------------------------------------------------------------------

    function getNews($lastNewsId) {
        $lastDateInsertedNotified = '';
        
        if($lastNewsId != '') {
            $sql = "select dateinserted from wd_g_messages where messageid="._q($lastNewsId);
            $rs = $GLOBALS['db']->execute($sql);
            $GLOBALS['dbrequests']++;
            
            if($rs && !$rs->EOF) {
                $lastDateInsertedNotified = $rs->fields['dateinserted'];
            }
        }

        $sql = "select m.messageid, m.dateinserted, m.title, m.rtext 
                from wd_g_messages m left join wd_g_messagestousers mu on (m.messageid = mu.messageid and mu.userid="._q($this->userID).")

                where m.accountid='default1' 
                and m.active=1 
                and m.datevalidfrom<NOW() and m.datevalidto>NOW()
                and (mu.userid="._q($this->userID)." or (mu.userid is null and m.showtoall='1'))
                and m.deleted='0'
                and m.rtype='2'
                and (mu.rstatus='1' or mu.rstatus='2' or (mu.rstatus is null and m.showtoall='1'))";
                
        if($lastDateInsertedNotified != '') {
            $sql .= " and m.dateinserted>"._q($lastDateInsertedNotified);
        }
        
        $sql .= " order by m.dateinserted, m.title LIMIT 0,".$this->recordsLimit;

        $rs = $GLOBALS['db']->execute($sql);
        $GLOBALS['dbrequests']++;
        if (!$rs || $rs->EOF) {
            return null;
        }
        
        $user = QCore_Bl_Users::getUserData("._q($this->userID).");
        
        $newss = array();
        while(!$rs->EOF) {
            $news = array();
            $news['messageid'] = $rs->fields['messageid'];
            $news['dateinserted'] = $rs->fields['dateinserted'];
            $news['title'] = $rs->fields['title'];
            $news['rtext'] = $rs->fields['rtext'];
            $news = QCore_Bl_Communications::replaceInNews($user, $news);

            $newss[] = $news;
            $rs->MoveNext();
        }
        
        return $newss;
    }
    
    //------------------------------------------------------------------------

    function translateDataToXML($data) {
        $this->writeSimpleXml('stats', $data['stats']);
        $this->writeSimpleXml('signup', $data['signups']);
        $this->writeSimpleXml('transaction', $data['transactions']);
        $this->writeXmlNews($data['news']);
    }
    
    //------------------------------------------------------------------------
    
    function writeSimpleXml($notificationType, $data) {
        if($data != null) {
            foreach($data as $subdata) {
                echo "<notification type=\"$notificationType\"";
                
                foreach($subdata as $k => $v) {
                    echo " $k=\""._ch($v)."\"";
                }
                
                echo " />\n";
            }
        }
    }

    //------------------------------------------------------------------------
    
    function writeXmlNews($data) {
        if($data != null) {
            foreach($data as $subdata) {
                echo "<notification type=\"news\"";
                
                foreach($subdata as $k => $v) {
                    if($k == 'rtext') continue;
                    echo " $k=\""._ch($v)."\"";
                }
                
                echo ">";
                
                echo $subdata['rtext']."</notification>\n";
            }
        }
    }
}

//------------------------------------------------------------------------

function _ch($str) {
    $str = str_replace("'", "", $str);
    $str = str_replace("&", "&amp;", $str);
    $str = str_replace("\"", "", $str);
    
    return $str;
}
?>
