<?php
//--------------------------------------------------------------------------
function compare($a, $b) {
    if ($a[$_REQUEST['sortby']] == $b[$_REQUEST['sortby']]) return 0;
    $ret =  ($a[$_REQUEST['sortby']] > $b[$_REQUEST['sortby']]) ? -1 : 1;
    if ($_REQUEST['sortorder'] == 'asc') $ret = $ret * -1;
    return $ret;
}

class Affiliate_Scripts_Bl_ImpClicksStatistics
{
    function Affiliate_Scripts_Bl_ImpClicksStatistics() {
    }
    
    //--------------------------------------------------------------------------

    function initResults(&$result) {
        $sql = "select userid, name, surname, rstatus from wd_g_users ".
               " where deleted="._q(0)." and rtype="._q(USERTYPE_USER);
        
        $rs = QCore_Sql_DBUnit::execute($sql, __FILE__, __LINE__);
        if (!$rs) {
            QUnit_Messager::setErrorMessage(L_G_DBERROR);
            return;
        }

        while(!$rs->EOF)
        {
            $result[$rs->fields['userid']] = 
                array('userid'       => $rs->fields['userid'],
                      'name'         => $rs->fields['name']." ".$rs->fields['surname'],
                      'rstatus'      => $rs->fields['rstatus'],
                      'imps_all'     => 0,
                      'imps_unique'  => 0,
                      'clicks'       => 0,
                      'sales'        => 0,
                      'clicks_imps'  => 0,
                      'sales_clicks' => 0,
                      'commission'   => 0,
                      'totalcost'    => 0);
                      
            $rs->MoveNext(); 
        }
        
        $result['summaries'] = 
            array('imps_all'     => 0,
                  'imps_unique'  => 0,
                  'clicks'       => 0,
                  'sales'        => 0,
                  'clicks_imps'  => 0,
                  'sales_clicks' => 0,
                  'commission'   => 0,
                  'totalcost'    => 0);
    }
    
    //--------------------------------------------------------------------------
    
    function getImpressionStats(&$result, $conditions)
    {
        $CampaignID = $conditions['CampaignID'];
        $d1 = $conditions['day1'];
        $m1 = $conditions['month1'];
        $y1 = $conditions['year1'];
        $d2 = $conditions['day2'];
        $m2 = $conditions['month2'];
        $y2 = $conditions['year2'];
        
        $sql = 'select affiliateid, 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 = ' where i.bannerid=b.bannerid ';
        
        if($d1 != '' && $m1 != '' && $y1 != '') {
            $where .= " and (".sqlToDays('i.dateimpression')." >= ".sqlToDays("$y1-$m1-$d1").")".
                      " and (".sqlToDays('i.dateimpression')." <= ".sqlToDays("$y2-$m2-$d2").")";
        }
        if($CampaignID != '' && $CampaignID != '_') {
            $where .= " and b.campaignid="._q($CampaignID);
        }
        
        $groupBy = ' group by affiliateid';
        
        $rs = QCore_Sql_DBUnit::execute($sql.$where.$groupBy, __FILE__, __LINE__);
        if (!$rs) {
            QUnit_Messager::setErrorMessage(L_G_DBERROR);
            return;
        }

        while(!$rs->EOF)
        {
            if (isset($result[$rs->fields['affiliateid']])) {
                $result[$rs->fields['affiliateid']]['imps_all']     = $rs->fields['all_imps_count'];
                $result[$rs->fields['affiliateid']]['imps_unique']  = $rs->fields['unique_imps_count'];
                
                $result['summaries']['imps_all']     += $rs->fields['all_imps_count'];
                $result['summaries']['imps_unique']  += $rs->fields['unique_imps_count'];
            }
         
            $rs->MoveNext();   
        }
               
    }
    
    //--------------------------------------------------------------------------
    
    function getTransactionStats(&$result, $conditions)
    {
        $CampaignID = $conditions['CampaignID'];
        $d1 = $conditions['day1'];
        $m1 = $conditions['month1'];
        $y1 = $conditions['year1'];
        $d2 = $conditions['day2'];
        $m2 = $conditions['month2'];
        $y2 = $conditions['year2'];
	
	//-------------------------------------------------------
	//added by AdAstra - inicializes new Variables
	$TransactionType = $conditions['TransactionType'];
	$Status = $conditions['Status'];
	$dateSelectMode = $conditions['dateSelectMode'];
	
	//------------------------------------------------------
        
        $sql = 'select affiliateid, '.
               ' sum(if(t.transtype='.TRANSTYPE_CLICK.',count,0)) as clicks,'.
               ' sum(if(t.transtype='.TRANSTYPE_LEAD.' or t.transtype='.TRANSTYPE_SALE.',count,0)) as sales,'.
               ' sum(commission) as commission, sum(totalcost) as totalcost '.
               ' from wd_pa_transactions t, wd_pa_campaigncategories cc';
               
        $where = ' where t.campcategoryid=cc.campcategoryid and t.rstatus<>'.AFFSTATUS_SUPPRESSED;

        //------------------------------------------------------------------------------
        //added switch between date_inserted and date_approved, date_inserted is default
	switch( $dateSelectMode ){
	    case '2':
		if($d1 != '' && $m1 != '' & $y1 != '' ) {
		    $where .= " and (".sqlToDays('t.dateapproved')." >= ".sqlToDays("$y1-$m1-$d1").")".
			      " and (".sqlToDays('t.dateapproved')." <= ".sqlToDays("$y2-$m2-$d2").")";
		}
		break;
	
	    default:
		if($d1 != '' && $m1 != '' && $y1 != '') {
    		    $where .= " and (".sqlToDays('t.dateinserted')." >= ".sqlToDays("$y1-$m1-$d1").")".
        	              " and (".sqlToDays('t.dateinserted')." <= ".sqlToDays("$y2-$m2-$d2").")";
	        }
		break;
		
	}
	//-------------------------------------------------------------------------------
	
	
        if($CampaignID != '' && $CampaignID != '_') {
            $where .= " and cc.campaignid="._q($CampaignID);
        }
	
	//------------------------------------------------------------------------------
	//added Status and TransationType check
	
	//status:
	if( is_array( $Status ) ){
	    if( count( $Status ) > 0 ){
		$where .= " and t.rstatus in (".implode( ',' , $Status).")";
	    }
	    else{
		$where .= " and t.rstatus is NULL";	    
	    }
	}
	else{
	    if( $Status != '' && $Status != '_' ){
		$where .= " and t.rstatus="._q($Status);
	    }
	}
	//transation type:
	if( is_array( $TransactionType ) ){
	    if( count( $TransactionType ) > 0){
		$where .= " and t.transtype in (".implode( ',' , $TransactionType ).")";
	    }
	    else{
		$where .= " and t.transtype = NULL";
	    }
	}
	else{
	    if( $TransactionType != '' && $TransactionType != '_' ){
		$where .= " and t.transtype = "._q($TransactionType);
	    }
	}
	
	
        //------------------------------------------------------------------------------
        $groupBy = ' group by affiliateid';
	
        $rs = QCore_Sql_DBUnit::execute($sql.$where.$groupBy, __FILE__, __LINE__);
        if (!$rs) {
            QUnit_Messager::setErrorMessage(L_G_DBERROR);
            return;
        }

        while(!$rs->EOF)
        {
            if (isset($result[$rs->fields['affiliateid']])) {
                $result[$rs->fields['affiliateid']]['clicks']     = $rs->fields['clicks'];
                $result[$rs->fields['affiliateid']]['sales']      = $rs->fields['sales'];
                $result[$rs->fields['affiliateid']]['commission'] = $rs->fields['commission'];
                $result[$rs->fields['affiliateid']]['totalcost']  = $rs->fields['totalcost'];
                
                $result['summaries']['clicks']     += $rs->fields['clicks'];
                $result['summaries']['sales']      += $rs->fields['sales'];
                $result['summaries']['commission'] += $rs->fields['commission'];
                $result['summaries']['totalcost']  += $rs->fields['totalcost'];
            }
         
            $rs->MoveNext();   
        }
               
    }
    
    //--------------------------------------------------------------------------
    
    function computeFields(&$result) {
        if (count($result) < 1) return;
        
        foreach ($result as $userId => $data) {
            $result[$userId]['clicks_imps']  = ($data['imps_unique'] == 0) ? 0 : 100*$data['clicks']/$data['imps_unique'];
            $result[$userId]['sales_clicks'] = ($data['clicks'] == 0) ? 0 : 100*$data['sales']/$data['clicks'];
        }
    }
    
    
    
    //--------------------------------------------------------------------------
    
    function sortData(&$result, $conditions)
    {
        uasort($result, "compare");
    }
    
    //--------------------------------------------------------------------------
    
    function roundData(&$result)
    {
        if (count($result) < 1) return;
        
        foreach ($result as $userId => $data) {
            $result[$userId]['clicks_imps']  = _rnd($data['clicks_imps']);
            $result[$userId]['sales_clicks'] = _rnd($data['sales_clicks']);
        }
    }
    
    //--------------------------------------------------------------------------
    
    function getImpClicksStatistics($conditions)
    {
        $result = array();
        
        $this->initResults($result);
        
        $this->getImpressionStats($result, $conditions);
        
        $this->getTransactionStats($result, $conditions);
        
        $this->computeFields($result);
               
        $this->sortData($result, $conditions);
        
        $this->roundData($result);
        
        return $result;
    }
}
?>
