<?php
QUnit_Global::includeClass('QUnit_Countries');
QUnit_Global::includeClass('QCore_Bl_Accounts');
QUnit_Global::includeClass('Affiliate_Scripts_Bl_Signup');
QUnit_Global::includeClass('Affiliate_Scripts_Bl_Registrator');
QUnit_Global::includeClass('Affiliate_Merchants_Bl_ForcedMatrix');
QUnit_Global::includeClass('QCore_EmailTemplates');
QUnit_Global::includeClass('QCore_Bl_Communications');
QUnit_Global::includeClass('QCore_Sql_Table_Users');

class Affiliate_Scripts_Bl_AccountAddNew {

    function Affiliate_Scripts_Bl_AccountAddNew() {
        $this->account = QUnit_Global::newObj('QCore_Sql_Table_Accounts');
        $this->accountSettings = QUnit_Global::newObj('QCore_Sql_Table_AccountsSettings');
        $this->user = QUnit_Global::newObj('QCore_Sql_Table_Users');
    }
            
    function getErrorMessage() {
        return QUnit_Messager::getErrorMessage();
    }
    
    function addErrorMessage($msg) {
        QUnit_Messager::setErrorMessage($msg);
    }
        
    function addOkMessage($msg) {
        QUnit_Messager::setOkMessage($msg);
    }
    //--------------------------------------------------------------------------

    function checkForm($edit = false) {        
        $correct = true;
                
        if($this->settings['Glob_acct_signup_force_acceptance'] == "1") {
            if(!isset($_POST['tos']) || $_POST['tos'] !== "1") {
                $this->addErrorMessage(L_G_TOSAGREE); 
                $correct = false;
            }
        }        
        if($this->account->check() === false) {
            $correct = false;
        }
        
        if($this->user->check() === false) {
            $correct = false;
        }
        
        if($this->accountSettings->check() === false) {
            $correct = false;
        }
        
        if($this->checkAccountExists() === false) {
            $correct = false;            
        }
        
        if($this->checkUserExists() === false) {
            $correct = false;            
        }
        
        if($this->checkPassword() === false) {
            $correct = false;            
        }
                
        return $correct;
    }

    function checkPassword() {
        if(empty($_POST['pwd1'])) {
            $this->addErrorMessage(L_G_PWD1EMPTY);
            return false;            
        }
        if(empty($_POST['pwd2'])) {
            $this->addErrorMessage(L_G_PWD2EMPTY);
            return false;            
        }
        if($_POST['pwd1'] != $_POST['pwd2']) {
            $this->addErrorMessage(L_G_PWDDONTMATCH);
            return false;            
        }
        return true;
    }
            
    function checkAccountExists() {        
        if(QCore_Bl_Accounts::checkAccountExists('', $this->account->getColumn('name')) === true) {
            $this->addErrorMessage(L_G_ACCOUNTEXISTS);
            return false;
        }         
        return true;
    } 
    
    function checkUserExists() {
        if(QCore_Bl_Users::checkUserExists('', $this->user->getColumn('username')) === true) {
            $this->addErrorMessage(L_G_UNAMEEXISTS);
            return false;
        }
        return true;
    }
        
    function loadSettings() {
        $settings = QCore_Settings::getAccountSettings(SETTINGTYPE_ACCOUNT, '');
        $this->settings = array_merge($settings, QCore_Settings::getGlobalSettings());
    }

    //--------------------------------------------------------------------------    
    
    function setMandatoryFields($arr, &$obj, $prefix = 'Glob_acct_signup_') {
        foreach($arr as $key => $val) {
            if($this->settings[$prefix.$key.'_mandatory'] == "true") {
                $obj->setNeeded($key, true);
            } else {
                $obj->setNeeded($key, false); 
            }
        }  
    }
    
    function setDataFieldsCaption() {
        for($i=1;$i<=5;$i++) {
            $this->accountSettings->setCaption("data$i", $this->settings["Glob_acct_signup_data{$i}_name"]);
        }
    }
    
    //--------------------------------------------------------------------------

    function setStatus() {
        $this->user->setColumn('rstatus', $this->getStatus());
    }
    
    function getStatus() {
        $approval = $this->settings['Glob_adminapproval'];       
        if($approval == APPROVE_AUTOMATIC) {
            $status = AFFSTATUS_APPROVED;
        } else if($approval == APPROVE_MANUAL) {
            $status = AFFSTATUS_NOTAPPROVED;
        } else {
            $status = AFFSTATUS_NOTAPPROVED;
        }
        return $status;
    }
        
       
    function fillAccount() {
        $accountId = QCore_Sql_DBUnit::createUniqueID('wd_g_accounts', 'accountid');
        $this->account->setColumn('accountid', $accountId);
        $this->account->setColumn('name', $_POST['account_name']);
        $this->account->setColumn('description', $_POST['account_description']);
        $this->account->setColumn('dateinserted', strftime('%y-%m-%d %H:%M:%S', time()));
        $this->account->setColumn('rstatus', $this->getStatus());            
        $this->setMandatoryFields(array('description'), $this->account, 'Glob_acct_signup_account_');        
    }
    
    function fillUser() {
        $this->user->setColumn('username', $_POST['username']);
        $this->user->setColumn('rtype', USERTYPE_ADMIN);
        $this->user->setColumn('dateinserted', strftime('%y-%m-%d %H:%M:%S', time()));
        $this->user->setColumn('deleted', '0');
        $this->user->setColumn('product', PRODUCT_AFFILIATE);
        $this->user->setColumn('userprofileid', 'userpro1');        
        $this->user->setColumn('accountid', $this->account->getColumn('accountid'));
        $this->user->setColumn('name', $_POST['name']);
        $this->user->setColumn('surname', $_POST['surname']);
        
        $this->user->setColumn('rpassword', $_POST['pwd1']);
        $userId = QCore_Sql_DBUnit::createUniqueID('wd_g_users', 'userid');
        $this->user->setColumn('userid', $userId);
        $this->user->setColumn('refid', $userId);        
        $this->user->setColumn('rstatus', "0");        
    }
    
    function fillAccountSettings() {
        $this->accountSettings->fillColumnsFromArray($_POST);
        $this->setDataFieldsCaption();
        $this->setMandatoryFields($_POST, $this->accountSettings);               
    }
     
    //--------------------------------------------------------------------------
    
    function process() {        
        $this->loadSettings();
        $this->fillAccount();
        $this->fillAccountSettings();
        $this->fillUser();      
        
        if($this->checkForm() == false) {
            return false;
        }
                        
        if($this->createAccountDir() == false) {
            return false;
        }
        
        if($this->save() == false) {
            return false;
        }
        
        
        return true;
    }
    
    function save() {
        if($this->account->insert() == false) {
            return false;
        }
        if($this->user->insert() == false) {
            return false;
        }
        if($this->accountSettings->saveSettings($this->account->getColumn('accountid')) == false) {
            return false;
        }        
        return true;
    }
    
    function createAccountDir() {
                
        if(!isset($this->settings['Glob_accounts_dir']) || $this->settings['Glob_accounts_dir'] == '') {
            $this->addErrorMessage(L_G_ACCOUNTSDIRNOTCONFIGURED);
            return false;
        }
        
        $accountsDir = $this->settings['Glob_accounts_dir'];
        
        if(!file_exists($accountsDir)) {
            $this->addErrorMessage(L_G_ACCOUNTSDIRNOTEXISTS.": ".$accountsDir);
            return false;
        }
        
        if(!is_writable($accountsDir)) {
            $this->addErrorMessage(L_G_ACCOUNTSDIRNOTWRITABLE.": ".$accountsDir);
            return false;
        }
        
        if(!mkdir($accountsDir.'/'.$this->account->getColumn('accountid'), 0755)) {
            $this->addErrorMessage(L_G_ACCOUNTSDIRCANNOTCREATE.": ".$accountsDir);
            return false;            
        }
        
        return true;        
    }
        
}
?>
