<?php
QUnit_Global::includeClass('QCore_Settings');
QUnit_Global::includeClass('QCore_Bl_Job');

class Affiliate_Scripts_Bl_DailyReports extends QCore_Bl_Job
{
    var $blTimeStat;
    var $blUsers;
    var $blAccounts;
    var $blCommunications;
    var $blEmailTemplates;
    var $blSaleStatistics;

    function Affiliate_Scripts_Bl_DailyReports()
    {
        $this->blTimeStat =& QUnit_Global::newObj('Affiliate_Scripts_Bl_TimerangeStatistics');
        $this->blSaleStatistics = QUnit_Global::newObj('Affiliate_Scripts_Bl_SaleStatistics');
        $this->blUsers =& QUnit_Global::newObj('QCore_Bl_Users');
        $this->blAccounts =& QUnit_Global::newObj('QCore_Bl_Accounts');
        $this->blCommunications =& QUnit_Global::newObj('QCore_Bl_Communications');
        $this->blEmailTemplates =& QUnit_Global::newObj('QCore_EmailTemplates');
    }

    function process()
    {
        $countGenerated = 0;
        $countSent = 0;
        $time = time() - 3600*24;
        $d = date('d', $time);
        $m = date('m', $time);
        $y = date('Y', $time);

        $accounts = $this->blAccounts->getAccountsAsArray();
        $account_settings = QCore_Settings::getAccountsSettings();

        foreach($accounts as $account)
        {

            if (!$this->skip()) {
                if($account_settings[$account['accountid']]['Aff_email_merch_dailyreport'] == 1)
                {
                    $data = $this->blTimeStat->getTimerangeStats('', '',
                             $d, $m, $y, $d, $m, $y, $account['accountid'],
                             $account_settings[$account['accountid']]);


                    // sales list
                    $cond['TransactionType'] = TRANSTYPE_SALE;
                    $cond['day1'] = $d;
                    $cond['month1'] = $m;
                    $cond['year1'] = $y;
                    $cond['day2'] = $d;
                    $cond['month2'] = $m;
                    $cond['year2'] = $y;
		    //------------------
		    $cond['dateSelectMode'] = '1';
		    //------------------
                    $data_sales = $this->blSaleStatistics->getTransactionsStats($cond, $account['accountid']);
                    $data['sales_list'] = $this->formatTransactionList($data_sales['transactions'], $account_settings[$account['accountid']]);
                    // leads list
                    $cond['TransactionType'] = TRANSTYPE_LEAD;
                    $data_leads = $this->blSaleStatistics->getTransactionsStats($cond, $account['accountid']);
                    $data['leads_list'] = $this->formatTransactionList($data_leads['transactions'], $account_settings[$account['accountid']]);

		    //--------------------------------------------
		    //added by AdAstra
		    //select sales_list_approved and leads_list_approved
		    //sales
		    $cond['dateSelectMode'] = '2';
		    $cond['TransactionType'] = TRANSTYPE_SALE;
		    $data_sales2 = $this->blSaleStatistics->getTransactionsStats( $cond, $account['accountid'] );
		    $data['sales_list_approved'] = $this->formatTransactionList( $data_sales2['transactions'], $account_settings[$account['accountid']] );
		    //leads
		    $cond['TransactionType'] = TRANSTYPE_LEAD;
		    $data_sales2 = $this->blSaleStatistics->getTransactionsStats( $cond, $account['accountid'] );
		    $data['leads_list_approved'] = $this->formatTransactionList( $data_sales2['transactions'], $account_settings[$account['accountid']] );
		    //--------------------------------------------

                    $countGenerated++;
                    if($this->sendDailyReportToMerchant($data,
                            $account_settings[$account['accountid']]['Aff_default_lang'],
                            $account_settings[$account['accountid']]['Aff_notifications_email'],
                            $account['accountid'], $account_settings[$account['accountid']]))
                        $countSent++;
                }
                if ($this->interrupt()) return;
            }

            $user_settings = QCore_Settings::getAccountUsersSettings($account['accountid']);
            $users = $this->blUsers->getUsersUsernamesAsArray($account['accountid']);

            foreach($user_settings as $userid => $userdata)
            {
                if($this->skip())
                    continue;

                if(($userdata['Aff_email_affdailyreport'] == '1') &&
                   ($account_settings[$account['accountid']]['Aff_email_dailyreport'] == 1))
                {
                    $countGenerated++;

                    $userstats = $this->blTimeStat->getTimerangeStats(
                         $userid, '',
                         $d, $m, $y, $d, $m, $y, $account['accountid'],
                         $account_settings[$account['accountid']]);
                    
                    // sales list
                    $cond['TransactionType'] = TRANSTYPE_SALE;
                    $cond['UserID'] = $userid;
                    $cond['day1'] = $d;
                    $cond['month1'] = $m;
                    $cond['year1'] = $y;
                    $cond['day2'] = $d;
                    $cond['month2'] = $m;
                    $cond['year2'] = $y;
		    //-------------------------------
		    $cond['dateSelectMode'] = '1';
		    //-------------------------------
                    $data_sales = $this->blSaleStatistics->getTransactionsStats($cond, $account['accountid']);
                    $userstats['sales_list'] = $this->formatTransactionList($data_sales['transactions'], $account_settings[$account['accountid']]);
                    // leads list
                    $cond['TransactionType'] = TRANSTYPE_LEAD;
                    $data_leads = $this->blSaleStatistics->getTransactionsStats($cond, $account['accountid']);
                    $userstats['leads_list'] = $this->formatTransactionList($data_leads['transactions'], $account_settings[$account['accountid']]);

		    //----------------------------------------------------
		    //added by AdAstra added 2 new selects sales_approved and leads_approved
		    //sales_approved
		    $cond['dateSelectMode'] = '2';
		    $cond['TransactionType'] = TRANSTYPE_SALE;
		    $data_sales2 = $this->blSaleStatistics->getTransactionsStats( $cond, $account['accountid'] );
		    $userstats['sales_list_approved'] = $this->formatTransactionList( $data_sales2['transactions'], $account_settings[$account['accountid']] );
		    //leads_approved
		    $cond['TransactionType'] = TRANSTYPE_LEAD;
		    $data_leads2 = $this->blSaleStatistics->getTransactionsStats( $cond, $account['accountid'] );
		    $userstats['leads_list_approved'] = $this->formatTransactionList( $data_leads2['transactions'], $account_settings[$account['accountid']] );
		    //----------------------------------------------------

                    $lang = $userdata['Aff_aff_notificationlang'];
                    if($lang == '')
                        $lang = $account_settings[$account['accountid']]['Aff_default_lang'];

                    if($this->sendDailyReportToUser($userid, $users[$account['accountid']][$userid]['username'],
                                                    $userstats, $lang, $account['accountid'],
                                                    $account_settings[$account['accountid']]))
                    {
                        $countSent++;
                    }
                }

                if ($this->interrupt()) return;
            }
        }

        // log it
        LogMsg("Daily reports - generated: $countGenerated reports, sent reports: $countSent, error sending reports: ".($countGenerated - $countSent), __FILE__, __LINE__);

        $this->finish();

        return $countGenerated;
    }

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

    function sendDailyReportToMerchant(&$data, $default_lang, $notifications_email, $accountID, $settings)
    {
        QUnit_Global::includeClass('QCore_EmailTemplates');

        $emaildata = $this->blEmailTemplates->getFilledEmailMessage('', $accountID, 'AFF_EMAIL_DAILY_REP', $default_lang, $data);
        if($emaildata != false)
        {
            $params = array('accountid' => $accountID,
                            'subject' => $emaildata['subject'],
                            'text' => $emaildata['text'],
                            'message_type' => MESSAGETYPE_EMAIL,
                            'userid' => '',
                            'email' => $notifications_email,
                            'settings' => $settings
            );

            if(!$this->blCommunications->sendEmail($params)) {
                $errorMsg = "Daily report: There was a problem sending daily report email to merchant '".$notifications_email."'";
                LogError($errorMsg, __FILE__, __LINE__);
            } else {
                LogMsg("Daily report was succesfully generated and sent to merchant '".$notifications_email."'", __FILE__, __LINE__);
                return true;
            }
        }
        else
        {
          $errorMsg = "Daily report:  There was a problem generating merchant daily report email from template";
          LogError($errorMsg, __FILE__, __LINE__);
        }

        return false;
    }

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

    function sendDailyReportToUser($userID, $email, &$data, $lang, $accountID, $settings)
    {
        QUnit_Global::includeClass('QCore_EmailTemplates');
        
        $emaildata = $this->blEmailTemplates->getFilledEmailMessage($userID, $accountID, 'AFF_EMAIL_AF_DL_REP', $lang, $data);

        if($emaildata != false)
        {
            $params = array('accountid' => $accountID,
                            'subject' => $emaildata['subject'],
                            'text' => $emaildata['text'],
                            'message_type' => MESSAGETYPE_EMAIL,
                            'userid' => $userID,
                            'email' => $email,
                            'settings' => $settings
            );

            if(!$this->blCommunications->sendEmail($params)) {
                $errorMsg = "Daily report: There was a problem sending daily report email to user '$email'";
                LogError($errorMsg, __FILE__, __LINE__);
            } else {
                LogMsg("Daily report was succesfully generated and sent to user '$email'", __FILE__, __LINE__);
                return true;
            }
        }
        else
        {
          $errorMsg = "Daily report:  There was a problem generating user daily report email from template";
          LogError($errorMsg, __FILE__, __LINE__);
        }

        return false;
    }

    function formatTransactionList($transList, $settings)
    {
        $data = L_G_CREATED."\t\t\t".L_G_CAMOUNT."\t".L_G_TOTALCOST."\t".L_G_ORDERID."\t".L_G_STATUS."\n";
        foreach ($transList as $trans) {
            $data .= $trans['datecreated']."\t".
                     $this->showCurrency($trans['commission'], $settings)."\t\t".
                     $this->showCurrency($trans['totalcost'], $settings)."\t".
                     $trans['orderid']."\t\t";
            if ($trans['payoutstatus'] == AFFSTATUS_APPROVED) {
                $txt = L_G_PAID;
            } else {
                switch ($trans['rstatus']) {
                    case AFFSTATUS_NOTAPPROVED: $txt = L_G_WAITINGAPPROVAL; break;
                    case AFFSTATUS_APPROVED:    $txt = L_G_APPROVED; break;
                    case AFFSTATUS_SUPPRESSED:  $txt = L_G_SUPPRESSED; break;
                }
            }
            $data .= $txt."\n";
        }
        return $data;
    }

    function showCurrency($value, $settings) {
        return ($settings['Aff_currency_left_position'] == '1' ?
                        $settings['Aff_system_currency'].' '._rnd($value) :
                        _rnd($value).' '.$settings['Aff_system_currency']);
    }
}
?>
