<?php
QUnit_Global::includeClass('QCore_Bl_IpCountry');

class Affiliate_Scripts_Bl_GeoStatistics
{
    var $blIpCountry;
    var $countryList;
    
    //------------------------------------------------------------------------
    
    function Affiliate_Scripts_Bl_GeoStatistics() {
        $this->blIpCountry = QUnit_Global::newObj('QCore_Bl_IpCountry');
        $this->countryList = $this->blIpCountry->getCountriesAsArray();
        $this->countryList['__'] = array("countrycode" => '__', "countryname" => 'Unknown');
    }
    
    //------------------------------------------------------------------------
    
    function getGeoStats($AffiliateID,
                           $CampaignID,
                           $reportType,
                           $d1='',$m1='',$y1='',$d2='',$m2='',$y2='',
                           $AccountID='',
                           $settings = '')
    {
        if(is_object($GLOBALS['Auth']))
        {
            if($AccountID == '')
            {
                $AccountID = $GLOBALS['Auth']->getAccountID();
            }
            if($settings == '')
            {
                $settings = array();
                $settings['Aff_support_signup_commissions'] = $GLOBALS['Auth']->getSetting('Aff_support_signup_commissions');
                $settings['Aff_support_referral_commissions'] = $GLOBALS['Auth']->getSetting('Aff_support_referral_commissions');
                $settings['Aff_support_cpm_commissions'] = $GLOBALS['Auth']->getSetting('Aff_support_cpm_commissions');
                $settings['Aff_support_click_commissions'] = $GLOBALS['Auth']->getSetting('Aff_support_click_commissions');
                $settings['Aff_support_sale_commissions'] = $GLOBALS['Auth']->getSetting('Aff_support_sale_commissions');
                $settings['Aff_support_lead_commissions'] = $GLOBALS['Auth']->getSetting('Aff_support_lead_commissions');
                $settings['Aff_support_recurring_commissions'] = $GLOBALS['Auth']->getSetting('Aff_support_recurring_commissions');
            }
        }
        
        $GeoData = $this->initResults($reportType);

        $GeoData = $this->getImpressionStats($AffiliateID, 
                                                                             '',            // BannerID
                                                                             $CampaignID,
                                                                             $reportType,
                                                                             $d1,$m1,$y1,
                                                                             $d2,$m2,$y2,
                                                                             $AccountID,
                                                                             $GeoData);

        $GeoData = $this->getTransactionsStats($AffiliateID, 
                                                                             $CampaignID,
                                                                             $reportType,
                                                                             $d1,$m1,$y1,
                                                                             $d2,$m2,$y2,
                                                                             $AccountID,
                                                                             $GeoData,
                                                                             $settings);
		
        return $GeoData;
    }

    //------------------------------------------------------------------------
    
    function initResults($reportType)
    {
        $GeoData = array();
        
        return $GeoData;
    }
    
    //------------------------------------------------------------------------
    
    function getImpressionStats($AffiliateID, $BannerID, $CampaignID, $reportType, $d1,$m1,$y1, $d2,$m2,$y2, $AccountID, $GeoData)
    {
        $sql = "select country, sum(all_imps_count) as all_imps_count, sum(unique_imps_count) as unique_imps_count". 
                   " from wd_pa_impressions i, wd_pa_banners b".
                   " where i.bannerid=b.bannerid".
                   " and i.accountid="._q($AccountID);
                   
        if($BannerID != '_' && $BannerID != '')
        {
            $sql .= " and i.bannerid="._q($BannerID);
        }
        if($AffiliateID != '_' && $AffiliateID != '')
        {
            $sql .= " and i.affiliateid="._q($AffiliateID);
        }
        if($d1 != '' && $m1 != '' && $y1 != '')
        {
            $sql .= " and (".sqlToDays('i.dateimpression')." >= ".sqlToDays("$y1-$m1-$d1").")".
                    " and (".sqlToDays('i.dateimpression')." <= ".sqlToDays("$y2-$m2-$d2").")";
        }
        if($CampaignID != '_' && $CampaignID != '')
        {
            $sql .= " and b.campaignid="._q($CampaignID);
        }
        $sql .= " group by country";
        
        $rs = QCore_Sql_DBUnit::execute($sql, __FILE__, __LINE__);
        if (!$rs)
            return false;
        
        $blIpCountry = QUnit_Global::newObj('QCore_Bl_IpCountry');
        while(!$rs->EOF)
        {
        	if($rs->fields['country'] == '') {
        		$rs->fields['country'] = '__';
        	}
        	$GeoData = $this->checkCountryExists($GeoData, $rs->fields['country']);
        	
            $GeoData['imps_all'][$rs->fields['country']] += $rs->fields['all_imps_count'];
            $GeoData['imps_unique'][$rs->fields['country']] += $rs->fields['unique_imps_count'];

            $rs->MoveNext();
        }
        
        return $GeoData;
    }
    
    //------------------------------------------------------------------------
    
    function getTransactionsStats($AffiliateID, $CampaignID, $reportType, $d1,$m1,$y1, $d2,$m2,$y2, $AccountID, $GeoData, $settings)
    {
        // build sql
        $sql = "select sum(count) as count, t.transtype as transtype, sum(t.commission) as commission, t.countrycode as country ";
        $sqlAll = "select sum(count) as count, t.transtype as transtype, sum(t.commission) as commission ";
        
        $where = " from wd_pa_transactions t, wd_g_users a, wd_pa_campaigncategories cc".
               " where t.campcategoryid=cc.campcategoryid ".
               " and t.affiliateid=a.userid and a.deleted=0 ".
               " and a.rtype="._q(USERTYPE_USER).
               " and a.rstatus="._q(AFFSTATUS_APPROVED).
               " and t.accountid="._q($GLOBALS['Auth']->getAccountID()).
               " and t.transkind=".TRANSKIND_NORMAL.
               " and t.rstatus<>".AFFSTATUS_SUPPRESSED;
        $where2 = '';
        if($AffiliateID != '_' && $AffiliateID != '')
        {
            $where2 .= " and t.affiliateid="._q($AffiliateID);
        }
        if($d1 != '' && $m1 != '' && $y1 != '')
        {
            $where2 .= " and (".sqlToDays('t.dateinserted')." >= ".sqlToDays("$y1-$m1-$d1").")".
                    " and (".sqlToDays('t.dateinserted')." <= ".sqlToDays("$y2-$m2-$d2").")";
        }
        if($CampaignID != '_' && $CampaignID != '')
        {
            $where2 .= " and cc.campaignid="._q($CampaignID);
        }
        $groupby = " group by t.transtype, t.countrycode";
	    $rs = QCore_Sql_DBUnit::execute($sql.$where.$where2.$groupby, __FILE__, __LINE__);
        if (!$rs)
            return false;
            
        while(!$rs->EOF)
        {
        	if($rs->fields['country'] == '') {
        		$rs->fields['country'] = '__';
        	}
        	$GeoData = $this->checkCountryExists($GeoData, $rs->fields['country']);
        	
            switch($rs->fields['transtype'])
            {
                case TRANSTYPE_CPM: 	$GeoData['cpm'][$rs->fields['country']] += $rs->fields['count'];
                					 	break;
                case TRANSTYPE_CLICK: 	$GeoData['clicks'][$rs->fields['country']] += $rs->fields['count'];
                						break;
                case TRANSTYPE_LEAD: 	$GeoData['leads'][$rs->fields['country']] += $rs->fields['count'];
                						break;
                case TRANSTYPE_SALE: 	$GeoData['sales'][$rs->fields['country']] += $rs->fields['count'];
                						break;
            }

            $rs->MoveNext();
        }
        
        // get revenues
        if($settings != '')
        {
            $allowedTransactions = array();

            if($settings['Aff_support_signup_commissions'] == 1) $allowedTransactions[] = TRANSTYPE_SIGNUP;
            if($settings['Aff_support_referral_commissions'] == 1) $allowedTransactions[] = TRANSTYPE_REFERRAL;
            if($settings['Aff_support_cpm_commissions'] == 1) $allowedTransactions[] = TRANSTYPE_CPM;
            if($settings['Aff_support_click_commissions'] == 1) $allowedTransactions[] = TRANSTYPE_CLICK;
            if($settings['Aff_support_sale_commissions'] == 1) $allowedTransactions[] = TRANSTYPE_SALE;
            if($settings['Aff_support_lead_commissions'] == 1) $allowedTransactions[] = TRANSTYPE_LEAD;
            if($settings['Aff_support_recurring_commissions'] == 1) $allowedTransactions[] = TRANSTYPE_RECURRING;
            
            if(count($allowedTransactions) > 0)
            {
                $where2 .= " and t.transtype in (".implode(',', $allowedTransactions).")";
            }
        }        

        $rs = QCore_Sql_DBUnit::execute($sql.$where.$where2.$groupby, __FILE__, __LINE__);
        if (!$rs)
            return false;

        while(!$rs->EOF)
        {
        	if($rs->fields['country'] == '') {
        		$rs->fields['country'] = '__';
        	}
        	$GeoData = $this->checkCountryExists($GeoData, $rs->fields['country']);
        	
            $GeoData['revenue'][$rs->fields['country']] += $rs->fields['commission'];

            $rs->MoveNext();
        }
        
        if($CampaignID == '_' || $CampaignID == '')
        {
            // process non-campaign transactions in time range
            $where = " from wd_pa_transactions t, wd_g_users a".
                      " where (t.campcategoryid Is Null or t.campcategoryid='' or t.campcategoryid='0')".
                      " and t.affiliateid=a.userid and a.deleted=0 ".
                      " and a.rtype="._q(USERTYPE_USER).
                      " and a.rstatus="._q(AFFSTATUS_APPROVED).
                      " and t.accountid="._q($GLOBALS['Auth']->getAccountID()).
                      " and t.transkind=".TRANSKIND_NORMAL.
                      " and t.rstatus<>".AFFSTATUS_SUPPRESSED;

            $rs = QCore_Sql_DBUnit::execute($sql.$where.$where2.$groupby, __FILE__, __LINE__);
            if (!$rs)
            return false;
            
            while(!$rs->EOF)
            {
            	if($rs->fields['country'] == '') {
	        		$rs->fields['country'] = '__';
        		}
        		$GeoData = $this->checkCountryExists($GeoData, $rs->fields['country']);
        		
                $GeoData['revenue'][$rs->fields['country']] += $rs->fields['commission'];
                
                $rs->MoveNext();
            }
            
        }
        
        if ( ( ($GeoData['cpm']['__'] != 0) || ($GeoData['clicks']['__'] != 0) || ($GeoData['leads']['__'] != 0) || ($GeoData['sales']['__'] != 0) || ($GeoData['revenue']['__'] != 0) ) && ($GeoData['foundcountries']['__'] == null) ) {
        	$GeoData['foundcountries'][$rs->fields['country']] = array('countrycode' => '__', 'countryname' => 'Unknown');
        }
        
        return $GeoData;
    }
    
    //------------------------------------------------------------------------

    function checkSomeTransImpsExistedLastYear($affiliateID = '')
    {
        $year = date('Y') - 1;
        
        $sql = "select * from wd_pa_transactions where accountid="._q($GLOBALS['Auth']->getAccountID()).
               " and (".sqlToDays('dateinserted')." >= ".sqlToDays("$y1-$m1-$d1").")".
               " and (".sqlToDays('dateinserted')." <= ".sqlToDays("$y2-$m2-$d2").")";
               
        if($affiliateID != '')
        {
            $sql .= " and affiliateid="._q($affiliateID);
        }

        $rs = QCore_Sql_DBUnit::execute($sql.$sqlTransType.$where.$groupby, __FILE__, __LINE__);
        if (!$rs || $rs->EOF)
            return false;

        return true;
    }
    
    //------------------------------------------------------------------------
    
    function checkCountryExists($GeoData, $countrycode) {
    	if($GeoData['foundcountries'][$countrycode] == null) {
    		if ($this->countryList[$countrycode] == null) {
       			$GeoData['foundcountries'][$countrycode] = array('countrycode' => $countrycode, 'countryname' => $countrycode);
    		} else {
    			$GeoData['foundcountries'][$countrycode] = array('countrycode' => $countrycode, 'countryname' => $this->countryList[$countrycode]['countryname']);
    		}
       		
       		$GeoData['imps_all'][$countrycode] = 0;
           	$GeoData['imps_unique'][$countrycode] = 0;
           	$GeoData['cpm'][$countrycode] = 0;
       		$GeoData['clicks'][$countrycode] = 0;
       		$GeoData['leads'][$countrycode] = 0;
       		$GeoData['sales'][$countrycode] = 0;
       		$GeoData['revenue'][$countrycode] = 0;
       	}
	   	return $GeoData;
    }
}
?>
