/**
     * Load affiliate detail for affiliate manager
     *
     * @service affiliate read
     * @param $fields
     */
    public function affiliateDetails(Gpf_Rpc_Params $params) {
        $data = new Gpf_Rpc_Data($params);
        $search = $data->getFilters()->getFilter("id");
        if (sizeof($search) == 1) {
            $id = $search[0]->getValue();
        }
        

        $user = new Pap_Affiliates_User();
        $user->setId($id);
        try {
            $user->load();
        } catch (Gpf_DbEngine_NoRowException $e) {
            return $data;
        }
        $data->setValue("id", $user->getId());
        $data->setValue("name", $user->getFirstName()." ".$user->getLastName());
        $data->setValue("username", $user->getUserName());

        $formFields = $this->getUserFormFields();
        foreach($formFields as $record) {
            $code = $record->get('code');
            $data->setValue($code, $user->get($code));
        }

        return $data;
    }
	private function getUser() {
		$user = new Pap_Affiliates_User();
		$user->setId(Gpf_Session::getAuthUser()->getPapUserId());
		$user->load();

		return $user;
	}
 private function addUserToRecordSet(Gpf_Data_RecordSet $result, $userId) {
     $user = new Pap_Affiliates_User();
     $user->setId($userId);
     try {
         $user->load();
         $record = $result->createRecord();
         $record->loadFromObject(array_values($user->toArray()));
         $record->set("subaffiliates", 1);
         $result->add($record);
         if (strlen($user->getParentUserId())) {
             $this->addUserToRecordSet($result, $user->getParentUserId());
         }
     } catch (Exception $e) {
     }
 }
 public static function getAffiliateLink() {
     $mainSiteUrl = Gpf_Settings::get(Pap_Settings::MAIN_SITE_URL);
     $user = new Pap_Affiliates_User();
     $user->setId(Gpf_Session::getAuthUser()->getPapUserId());
     $user->load();
     if (Pap_Tracking_ClickTracker::getInstance()->getLinkingMethod() == Pap_Tracking_ClickTracker::LINKMETHOD_REDIRECT) {
         $affiliateLink = "";
     } elseif(Pap_Tracking_ClickTracker::getInstance()->getLinkingMethod() == Pap_Tracking_ClickTracker::LINKMETHOD_ANCHOR
            && Gpf_Settings::get(Pap_Settings::SUPPORT_SHORT_ANCHOR_LINKING) == GPF::YES) {
         $affiliateLink = $mainSiteUrl . "#" . $user->getRefId();
     } else {
         $affiliateLink = Pap_Tracking_ClickTracker::getInstance()->getClickUrl(null, $user, $mainSiteUrl);
     }
     return $affiliateLink;
 }
 /**
  *
  * @service affiliate_invoice read
  * @param $fields
  */
 public function previewInvoice(Gpf_Rpc_Params $params) {
     $form = new Gpf_Rpc_Form($params);
     
     $user = new Pap_Affiliates_User();
     
     $applyVat = $form->getFieldValue('applyVat');
     $payoutInvoice = $form->getFieldValue('payoutInvoice');
     
     
     $user->setId($form->getFieldValue('userid'));
     try {
         $user->load();
     } catch (Gpf_Exception $e) {
         $this->invoiceHtml = $this->_("You have to select user");
         return $this;
     }
     
     $currency = Pap_Common_Utils_CurrencyUtils::getDefaultCurrency();
     $payout = new Pap_Common_Payout($user, $currency, 1, 123456);
     $payout->setApplyVat($applyVat);
     $payout->generateInvoice($payoutInvoice);
     $this->invoiceHtml = $payout->getInvoice(); 
     return $this;
 }
    public function sendInviteMail(Pap_Common_Campaign $campaign, $userID) {
        if(Gpf::NO == Gpf_Settings::get(Pap_Settings::AFF_NOTIFICATION_CAMPAIGN_INVITATION)){
            return;
        }

        $affiliate = new Pap_Affiliates_User();
        $affiliate->setId($userID);
        try {
            $affiliate->load();

            $mail = new Pap_Mail_InviteToCampaign();
            $mail->setCampaign($campaign);
            $mail->setUser($affiliate);
            $mail->addRecipient($affiliate->getEmail());
            $mail->send();
        } catch (Gpf_Exception $e) {
        }
    }
    private function createTestAffiliateUser() {
        $affiliateUser = new Pap_Affiliates_User();
        $affiliateUser->setId('11111111');
        $affiliateUser->setDateInserted(Gpf_Common_DateUtils::now());
        $affiliateUser->setRefId("testaff");
        $affiliateUser->setPassword($this->account->getPassword());
        $affiliateUser->setUserName(Pap_Branding::DEMO_AFFILIATE_USERNAME);
        $affiliateUser->setFirstName("Test");
        $affiliateUser->setLastName("Affiliate");
        $affiliateUser->setAccountId($this->account->getId());
        $affiliateUser->setStatus(Gpf_Db_User::APPROVED);
        $affiliateUser->set('dateapproved', Gpf_Common_DateUtils::Now());
        $affiliateUser->save();

        $this->setQuickLaunchSettings($affiliateUser->getAccountUserId(), 'showDesktop');
        Gpf_Settings::set(Pap_Settings::DEFAULT_AFFILIATE_PANEL_THEME, Pap_Branding::DEFAULT_AFFILIATE_PANEL_THEME);
    }
 private function assignParent(Pap_Affiliates_User $affiliate) {
     if ($affiliate->getParentUser() == null && ($parentUserId = Gpf_Settings::get(Pap_Settings::ASSIGN_NON_REFERRED_AFFILIATE_TO)) != '') {
         try {
             $parentUser = new Pap_Affiliates_User();
             $parentUser->setId($parentUserId);
             $parentUser->load();
             $affiliate->setParentUserId($parentUser->getId());
         } catch (Gpf_Exception $e) {
         }
         Gpf_Plugins_Engine::extensionPoint('PostAffiliate.AffiliateForm.assignParent', $affiliate);
     }
 }
    private function insertUser($record) {
    	$user = new Pap_Affiliates_User();
    	$user->setId($record->get('userid'));
    	$user->setRefId(($record->get('refid') != '' ? $record->get('refid') : $record->get('userid')));
    	$user->setPassword($record->get('rpassword'));
    	$user->setUserName($record->get('username'));
    	$user->setFirstName($record->get('name'));
    	$user->setLastName($record->get('surname'));
    	$user->setAccountId(Pap3Compatibility_Migration_Pap3Constants::DEFAULT_ACCOUNT_ID);
    	$user->setDateInserted($record->get('dateinserted'));
    	if ($record->get('minimumpayout') != NULL) {
    		$user->setMinimumPayout($record->get('minimumpayout'));
    	} else {
    		$user->setMinimumPayout(Gpf_Settings::get(Pap_Settings::PAYOUTS_MINIMUM_PAYOUT_SETTING_NAME));
    	}
    	if($record->get('dateapproved') != null && $record->get('dateapproved') != '') {
    		$user->setDateApproved($record->get('dateapproved'));
    	}
    	if (Pap3Compatibility_Migration_Pap3Constants::translateStatus($record->get('rstatus')) == Pap_Common_Constants::STATUS_APPROVED && 
    	$user->getDateApproved() == null) {
    		$actualDate = new Gpf_DateTime();
    		$user->setDateApproved($actualDate->toDateTime());
    	}
    	$user->setStatus(Pap3Compatibility_Migration_Pap3Constants::translateStatus($record->get('rstatus')));
    	$user->setType('A');
        $user->set('numberuserid',1);
        
    	$this->setAffiliateField($user, $record, 'street');
    	$this->setAffiliateField($user, $record, 'city');
    	$this->setAffiliateField($user, $record, 'company_name');
    	$this->setAffiliateField($user, $record, 'state');
    	$this->setAffiliateField($user, $record, 'zipcode');
    	$this->setAffiliateField($user, $record, 'weburl');
    	$this->setAffiliateField($user, $record, 'phone');
    	$this->setAffiliateField($user, $record, 'fax');
    	$this->setAffiliateField($user, $record, 'tax_ssn');
    	$this->setAffiliateField($user, $record, 'country');
    	$this->setAffiliateField($user, $record, 'data1');
    	$this->setAffiliateField($user, $record, 'data2');
    	$this->setAffiliateField($user, $record, 'data3');
    	$this->setAffiliateField($user, $record, 'data4');
    	$this->setAffiliateField($user, $record, 'data5');

    	$user->setSendNotification(false);
    	$user->setPayoutOptionId($this->savePayoutData($record->get('userid')));
    	$user->save();
    	
    	// handle parent id
        $parentUserId = $record->get('parentuserid');
        if($parentUserId != '') {
            $updateBuilder = new Gpf_SqlBuilder_UpdateBuilder();
            $updateBuilder->from->add(Pap_Db_Table_Users::getName());
            $updateBuilder->set->add(Pap_Db_Table_Users::PARENTUSERID, $parentUserId);
            $updateBuilder->where->add(Pap_Db_Table_Users::ID, '=', $record->get('userid'));
            try {
                $updateBuilder->executeOne();
            } catch (Gpf_Exception $e) {
                Pap3Compatibility_Migration_OutputWriter::log("<br/>Error setting parentuserid: ".$e->getMessage());
            }
        }
        
    	
    	$this->countUsers++;
    }
    /**
     * @param array $payoutOptionData
     */
    private function processPayoutOption($payoutOptionData, $row) {
        $user = new Pap_Affiliates_User();
        $user->setId($payoutOptionData[Pap_Db_Table_UserPayoutOptions::USERID]);
        try {
            $user->load();

            $payoutOption = new Pap_Db_PayoutOption();
            $payoutOption->setID($user->getPayoutOptionId());
            $payoutOption->load();

            $payoutField = new Gpf_Db_FormField();
            $payoutField->setFormId($payoutOption->getFormId());
            $payoutField->setCode($payoutOptionData[Gpf_Db_Table_FormFields::CODE]);
            $payoutField->loadFromData(array(Gpf_Db_Table_FormFields::FORMID, Gpf_Db_Table_FormFields::CODE));

            $userPayoutOption = new Pap_Db_UserPayoutOption();
            $userPayoutOption->setUserId($payoutOptionData[Pap_Db_Table_UserPayoutOptions::USERID]);
            $userPayoutOption->setFormFieldId($payoutField->getId());
            $userPayoutOption->setValue($payoutOptionData[Pap_Db_Table_UserPayoutOptions::VALUE]);
            $userPayoutOption->save();
            $this->incrementSuccessfulCount();
            $this->logger->debug('Data from line: ' . $this->getFile()->getActualCSVLineNumber() . ' was inserted.');
        } catch (Gpf_Exception $e) {
        	$this->logError('Payout option', $row, $e);
        	$this->appendOutputMessage($this->getSaveErrorMessage($this->getFile()->getActualCSVLineNumber(), $e->getMessage()));
            $this->incrementWrongCount();
        }
    }