<?php

class ModelExtensionAccountCombine extends Model {
	
	private $settings = array(
		'version' => 20180801,
		'status' => 0,
		'allow_own_aff' => 1,
		'_fields' => array('website', 'tax', 'payment', 'company'),
		'_payment_methods' => array('paypal', 'cheque', 'bank'),
		'_payment_method_fields' => array(
			'bank' => array('name', 'branch_number', 'swift_code', 'account_name','account_number')		
		),		
		'fields' => array(
		),
		'rform' => array(
			'affiliate' => 'c',
			'website_textarea' => 0,
			'agreement' => 0,
		),
		'cform' => array(
			'affiliate' => 'n',
			'website_textarea' => 0,
			'agreement' => 0,
		),
		'customer_group_id' => 0,		
		'own_parent' => 0
	);
	
	private $_settings_preprocessed = false;
	private $name = 'module_account_combine';
	
	private $_has_mta = -1;
	
	public function setAllCustomerGroup($customer_group_id) {
		$this->db->query("UPDATE " . DB_PREFIX . "customer SET customer_group_id = '" . (int)$customer_group_id . "' WHERE customer_id IN (SELECT customer_id FROM " . DB_PREFIX . "customer_affiliate)");
		return $this->db->countAffected();
	}

	public function getCurrentVersion() {
		$_cv = $this->config->get($this->name . '_version');
		if(!$_cv) return 0;
		return intval($_cv);
	}
	
	public function fixVersion($force = false) {
		if($force === false && $this->getCurrentVersion() >= $this->settings['version']) return false;
		$this->load->model('setting/setting');
		$curset = $this->model_setting_setting->getSetting($this->name);
		$s = $this->getDefaultSettings();
		$len = strlen($this->name) + 1;
		foreach($curset as $k => $v) {
			$k = substr_replace($k, '', 0, $len);
			if(isset($s[$k]) && $k != 'version') $s[$k] = $v;
		}
		$_settings = array();
		foreach($s as $k => $v) {
			$_settings[$this->name . '_' . $k] = $v;				
		}
		$this->model_setting_setting->editSetting($this->name, $_settings);		
		return true;
	}
	
	public function getDefaultSettings() {
		if($this->_settings_preprocessed === false)  {
			foreach($this->settings['_fields'] as $f) {
				$this->settings['fields'][$f] = 'y';
				$this->settings['rform']['show_' . $f] = 1;
				$this->settings['cform']['show_' . $f] = 0;
			}
			foreach($this->settings['_payment_methods'] as $f) {
				$this->settings['fields']['use_' . $f] = 1;
			}
			$this->settings['fields']['payment_default'] = $this->settings['_payment_methods'][0];
			foreach($this->settings['_payment_method_fields'] as $method => $fields) {
				if(is_array($fields)) {
					$this->settings['fields'][$method] = array();
					foreach($fields as $f) {
						$this->settings['fields'][$method][$f] = 1;
					}
				} else if(!$fields) {
					$this->settings['fields'][$method] = 0;
				}
			}
			$this->_settings_preprocessed = true;
		}
		return $this->settings;	
	}
	
	public function getName() {
		return $this->name;
	}

	
}
