<?php
class ModelAccountCustomer extends Model {

				public function getTotalCustomersByCnpjCpf($dados){

					$sql = "SELECT * FROM " . DB_PREFIX . "customer where ";

					if(strlen($dados)>11){
						$sql.= " cnpj = '".$this->db->escape($dados)."' ";
					}else{
						$sql.= " cpf = '".$this->db->escape($dados)."' ";
					}

					$query = $this->db->query($sql);

					return $query->row;

				}

	public function addCustomer($data) {
		if (isset($data['customer_group_id']) && is_array($this->config->get('config_customer_group_display')) && in_array($data['customer_group_id'], $this->config->get('config_customer_group_display'))) {
			$customer_group_id = $data['customer_group_id'];
		} else {
			$customer_group_id = $this->config->get('config_customer_group_id');
		}
		
		if( isset($this->request->post['inscricao_estadual']) && ((utf8_strlen(trim($data['inscricao_estadual'])) > 0)) && $this->config->get('config_customer_group_id_cinscricao') ){
		  $customer_group_id = $this->config->get('config_customer_group_id_cinscricao');
		}elseif($this->config->get('config_customer_group_id_sinscricao')){
		  $customer_group_id = $this->config->get('config_customer_group_id_sinscricao');
		}		

		$this->load->model('account/customer_group');

		$customer_group_info = $this->model_account_customer_group->getCustomerGroup($customer_group_id);


				if ($this->config->get('fields_register_brazil_status')){
					if ($data['data_nascimento'] == ""){
						$dataparts[0] = "00";
						$dataparts[1] = "00";
						$dataparts[2] = "0000";
					}else{
						$dataparts = explode("/",$data['data_nascimento']);
					}

					$data['firstname']          = ucwords($data['firstname']);
					$data['lastname']           = ucwords($data['lastname']);
					$data['email']              = strtr(strtolower($data['email']),"ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÜÚÞß","àáâãäåæçèéêëìíîïðñòóôõö÷øùüúþÿ");
					$data['telephone']          = preg_replace('/([^0-9])/i','',$data['telephone']);
					$data['celular']            = preg_replace('/([^0-9])/i','',$data['celular']);
					$data['fax']                = preg_replace('/([^0-9])/i','',$data['fax']);
					/*$data['cpf']                = preg_replace('/([^0-9])/i','',$data['cpf']);
					$data['rg']                 = preg_replace('/([^0-9])/i','',$data['rg']);*/


					if(isset($data['cpf'])){
						$data['cpf']               = preg_replace('/([^0-9])/i','',$data['cpf']);
					}
					else{
					   $data['cpf'] = '';
					}

					if(isset($data['rg'])){
						$data['rg']               = preg_replace('/([^0-9])/i','',$data['rg']);
					}
					else{
					   $data['rg'] = '';
					}

					if(isset($data['cnpj'])){
						$data['cnpj']               = preg_replace('/([^0-9])/i','',$data['cnpj']);
					}
					else{
					   $data['cnpj'] = '';
					}

					if(isset($data['perfil'])){
						$data['perfil']             = $data['perfil'];
					}
					else{
						$data['perfil'] = '';
					}

					if(isset($data['contribuinte'])){
						$data['contribuinte']		= $data['contribuinte'];
					}
					else {
					   $data['contribuinte'] = '';
					}

					if(isset($data['inscricao_estadual'])){
						$data['inscricao_estadual'] = preg_replace('/([^a-z0-9])/i','',$data['inscricao_estadual']);
					}
					else{
                        $data['inscricao_estadual'] = '';
					}
          
					$this->db->query("INSERT INTO " . DB_PREFIX . "customer SET store_id = '" . (int)$this->config->get('config_store_id') . "', firstname = '" . $this->db->escape($data['firstname']) . "', lastname = '" . $this->db->escape($data['lastname']) . "', email = '" . $this->db->escape($data['email']) . "', telephone = '" . $this->db->escape($data['telephone']) . "', celular = '" . $this->db->escape($data['celular']) . "', fax = '" . $this->db->escape($data['fax']) . "', salt = '" . $this->db->escape($salt = substr(md5(uniqid(rand(), true)), 0, 9)) . "', password = '" . $this->db->escape(sha1($salt . sha1($salt . sha1($data['password'])))) . "', newsletter = '" . (isset($data['newsletter']) ? (int)$data['newsletter'] : 0) . "', customer_group_id = '" . (int)$customer_group_id . "', ip = '" . $this->db->escape($this->request->server['REMOTE_ADDR']) . "', status = '1', approved = '" . (int)!$customer_group_info['approval'] . "', date_added = NOW(), cpf = '" . $this->db->escape($data['cpf']) . "', rg = '" . $this->db->escape($data['rg']) . "', cnpj = '" . $this->db->escape($data['cnpj']) . "', perfil = '" . $this->db->escape($data['perfil']) . "' ,contribuinte = 'S'  , razao_social = '" . $this->db->escape($data['razao_social']) . "', inscricao_estadual = '" . $this->db->escape($data['inscricao_estadual']) . "', data_nascimento = '" . $this->db->escape($dataparts[2]."-".$dataparts[1]."-".$dataparts[0]) . "', sexo = '" . $this->db->escape($data['sexo']) . "', interests_remember= '" . 0 . "', interests_date= '" . date('Y-m-d') . "', token='' ");
				}else{
					$this->db->query("INSERT INTO " . DB_PREFIX . "customer SET store_id = '" . (int)$this->config->get('config_store_id') . "', firstname = '" . $this->db->escape($data['firstname']) . "', lastname = '" . $this->db->escape($data['lastname']) . "', email = '" . $this->db->escape($data['email']) . "', telephone = '" . $this->db->escape($data['telephone']) . "', fax = '" . $this->db->escape($data['fax']) . "', salt = '" . $this->db->escape($salt = substr(md5(uniqid(rand(), true)), 0, 9)) . "', password = '" . $this->db->escape(sha1($salt . sha1($salt . sha1($data['password'])))) . "', newsletter = '" . (isset($data['newsletter']) ? (int)$data['newsletter'] : 0) . "', customer_group_id = '" . (int)$customer_group_id . "', ip = '" . $this->db->escape($this->request->server['REMOTE_ADDR']) . "', status = '1', approved = '" . (int)!$customer_group_info['approval'] . "', date_added = NOW()");
				}


        $customer_id = $this->db->getLastId();
        
        if (isset($data['categories'])) {
          $data['categories']['customer_id'] = $customer_id;
          $this->addInterests($data['categories']);
        }

				if ($this->config->get('fields_register_brazil_status')){
					$data['apelido']   = ucwords($data['apelido']);
					$data['firstname'] = ucwords($data['firstname']);
					$data['lastname']  = ucwords($data['lastname']);
					$data['address_1'] = ucwords($data['address_1']);
					$data['address_2'] = ucwords($data['address_2']);
					$data['city']      = ucwords($data['city']);
					$data['numero']    = preg_replace('/([^0-9])/i','',$data['numero']);
					$data['postcode']  = preg_replace('/([^0-9])/i','',$data['postcode']);

					$this->db->query("INSERT INTO " . DB_PREFIX . "address SET customer_id = '" . (int)$customer_id . "', firstname = '" . $this->db->escape($data['firstname']) . "', lastname = '" . $this->db->escape($data['lastname']) . "', company = '" . $this->db->escape($data['company']) . "', company_id = '" . $this->db->escape($data['company_id']) . "', tax_id = '" . $this->db->escape($data['tax_id']) . "', apelido = '" . $this->db->escape($data['apelido']) . "', address_1 = '" . $this->db->escape($data['address_1']) . "', numero = '" . $this->db->escape($data['numero']) . "', address_2 = '" . $this->db->escape($data['address_2']) . "', complemento = '" . $this->db->escape($data['complemento']) . "', city = '" . $this->db->escape($data['city']) . "', postcode = '" . $this->db->escape($data['postcode']) . "', country_id = '" . (int)$data['country_id'] . "', zone_id = '" . (int)$data['zone_id'] . "'");
				}else{
					$this->db->query("INSERT INTO " . DB_PREFIX . "address SET customer_id = '" . (int)$customer_id . "', firstname = '" . $this->db->escape($data['firstname']) . "', lastname = '" . $this->db->escape($data['lastname']) . "', company = '" . $this->db->escape($data['company']) . "', company_id = '" . $this->db->escape($data['company_id']) . "', tax_id = '" . $this->db->escape($data['tax_id']) . "', address_1 = '" . $this->db->escape($data['address_1']) . "', address_2 = '" . $this->db->escape($data['address_2']) . "', city = '" . $this->db->escape($data['city']) . "', postcode = '" . $this->db->escape($data['postcode']) . "', country_id = '" . (int)$data['country_id'] . "', zone_id = '" . (int)$data['zone_id'] . "'");
				}


		$address_id = $this->db->getLastId();

      	$this->db->query("UPDATE " . DB_PREFIX . "customer SET address_id = '" . (int)$address_id . "' WHERE customer_id = '" . (int)$customer_id . "'");

		$this->language->load('mail/customer');

		$subject = sprintf($this->language->get('text_subject'), $this->config->get('config_name'));

		$message = sprintf($this->language->get('text_welcome'), $this->config->get('config_name')) . "\n\n";

		if (!$customer_group_info['approval']) {
			$message .= $this->language->get('text_login') . "\n";
		} else {
			$message .= $this->language->get('text_approval') . "\n";
		}

		$message .= $this->url->link('account/login', '', 'SSL') . "\n\n";
		$message .= $this->language->get('text_services') . "\n\n";
		$message .= $this->language->get('text_thanks') . "\n";
		$message .= $this->config->get('config_name');

		$mail = new Mail();
		$mail->protocol = $this->config->get('config_mail_protocol');
		$mail->parameter = $this->config->get('config_mail_parameter');
		$mail->hostname = $this->config->get('config_smtp_host');
		$mail->username = $this->config->get('config_smtp_username');
		$mail->password = $this->config->get('config_smtp_password');
		$mail->port = $this->config->get('config_smtp_port');
		$mail->timeout = $this->config->get('config_smtp_timeout');
		$mail->setTo($data['email']);
		$mail->setFrom($this->config->get('config_email'));
		$mail->setSender($this->config->get('config_name'));
		$mail->setSubject(html_entity_decode($subject, ENT_QUOTES, 'UTF-8'));
		$mail->setText(html_entity_decode($message, ENT_QUOTES, 'UTF-8'));
		$mail->send();

		// Send to main admin email if new account email is enabled
		if ($this->config->get('config_account_mail')) {
			$message  = $this->language->get('text_signup') . "\n\n";
			$message .= $this->language->get('text_website') . ' ' . $this->config->get('config_name') . "\n";
			$message .= $this->language->get('text_firstname') . ' ' . $data['firstname'] . "\n";
			$message .= $this->language->get('text_lastname') . ' ' . $data['lastname'] . "\n";
			$message .= $this->language->get('text_customer_group') . ' ' . $customer_group_info['name'] . "\n";

			if ($data['company']) {
				$message .= $this->language->get('text_company') . ' '  . $data['company'] . "\n";
			}

			$message .= $this->language->get('text_email') . ' '  .  $data['email'] . "\n";
			$message .= $this->language->get('text_telephone') . ' ' . $data['telephone'] . "\n";

			$mail->setTo($this->config->get('config_email'));
			$mail->setSubject(html_entity_decode($this->language->get('text_new_customer'), ENT_QUOTES, 'UTF-8'));
			$mail->setText(html_entity_decode($message, ENT_QUOTES, 'UTF-8'));
			$mail->send();

			// Send to additional alert emails if new account email is enabled
			$emails = explode(',', $this->config->get('config_alert_emails'));

			foreach ($emails as $email) {
				if (strlen($email) > 0 && preg_match('/^[^\@]+@.*\.[a-z]{2,6}$/i', $email)) {
					$mail->setTo($email);
					$mail->send();
				}
			}
		}
	}
  
  public function addInterests($data) {
    
    $customer_id = (int)$data['customer_id'];
    unset($data['customer_id']);
    
    $this->removeInterests($customer_id);
    
    $query = "INSERT INTO " . DB_PREFIX . "cadastro_interesses (customer_id, tipo, category_id, subcategory_id) VALUES ";
    foreach ($data as $category_id => $value) {     
      if (isset($value['status']) && $value['status']) {
        $query .= "(" . $customer_id. ", 0, " . (int)$category_id . ", null),";
      } else {
        if (is_array($value)) {
          foreach ($value as $subcategory_id => $value) {
            if ($subcategory_id != 'status' && $subcategory_id != 'customer_id') {
              $query .= "(" . $customer_id . ", 1, null, " . (int)$subcategory_id . "),";
            }
          }
        }
      }
    }
    
    $query = substr($query, 0, strlen($query) - 1);
    
    $result = $this->db->query($query);
    
    return $result;
  }
  
  public function removeInterests($customer_id = '') { 
    if (!$customer_id) {
      $customer_id = (int)$this->customer->getId();
    }  
    $query = "DELETE FROM " . DB_PREFIX . "cadastro_interesses WHERE customer_id = " . $customer_id;
    $result = $this->db->query($query);
    return $result;
  }
  
  public function getInterests() { 
    $query = "SELECT * FROM " . DB_PREFIX . "cadastro_interesses WHERE customer_id = " . (int)$this->customer->getId();
    $result = $this->db->query($query);
    return $result->rows;
  }
  
  public function getInterestsCustomer($customer_id) { 
    $query = "select case when ISNULL(ci.subcategory_id) then ci.category_id else ci.subcategory_id end as category_id from oc_cadastro_interesses ci where ci.customer_id = ".(int)$customer_id." order by ci.tipo";
    $result = $this->db->query($query);
    return $result->rows;
  }  
  
  public function setInterestsRemember($data, $customer_id = '') {
    
    if (!$customer_id) {
      $customer_id = (int)$this->customer->getId();
    }
    $result = $this->db->query("UPDATE " . DB_PREFIX . "customer SET interests_remember = '" . $data . "', interests_date = '" . date('Y-m-d') . "' WHERE customer_id = " . $customer_id);

    return $result;
  }
  
	public function editCustomer($data) {

				if ($this->config->get('fields_register_brazil_status')){
					if ($data['data_nascimento'] == ""){
						$dataparts[0] = "00";
						$dataparts[1] = "00";
						$dataparts[2] = "0000";
					}else{
						$dataparts = explode("/",$data['data_nascimento']);
					}

					$data['firstname']          = ucwords($data['firstname']);
					$data['lastname']           = ucwords($data['lastname']);
					$data['email']              = strtr(strtolower($data['email']),"ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÜÚÞß","àáâãäåæçèéêëìíîïðñòóôõö÷øùüúþÿ");
					$data['telephone']          = preg_replace('/([^0-9])/i','',$data['telephone']);
					$data['celular']            = preg_replace('/([^0-9])/i','',$data['celular']);
					$data['fax']                = preg_replace('/([^0-9])/i','',$data['fax']);
					$data['cpf']                = preg_replace('/([^0-9])/i','',$data['cpf']);
					$data['rg']                 = preg_replace('/([^0-9])/i','',$data['rg']);
					$data['cnpj']               = preg_replace('/([^0-9])/i','',$data['cnpj']);
					$data['perfil']             = $data['perfil'];
					$data['contribuinte']		= $data['contribuinte'];
					$data['inscricao_estadual'] = preg_replace('/([^a-z0-9])/i','',$data['inscricao_estadual']);

					$this->db->query("UPDATE " . DB_PREFIX . "customer SET  firstname = '" . $this->db->escape($data['firstname']) . "', lastname = '" . $this->db->escape($data['lastname']) . "', email = '" . $this->db->escape($data['email']) . "', telephone = '" . $this->db->escape($data['telephone']) . "', celular = '" . $this->db->escape($data['celular']) . "', fax = '" . $this->db->escape($data['fax']) . "', cpf = '" . $this->db->escape($data['cpf']) . "', rg = '" . $this->db->escape($data['rg']) . "', cnpj = '" . $this->db->escape($data['cnpj']) . "', perfil = '" . $this->db->escape($data['perfil']) . "' ,contribuinte = 'S'  , razao_social = '" . $this->db->escape($data['razao_social']) . "', inscricao_estadual = '" . $this->db->escape($data['inscricao_estadual']) . "', data_nascimento = '" . $this->db->escape($dataparts[2]."-".$dataparts[1]."-".$dataparts[0]) . "', sexo = '" . $this->db->escape($data['sexo']) . "' WHERE customer_id = '" . (int)$this->customer->getId() . "'");
				}else{
					$this->db->query("UPDATE " . DB_PREFIX . "customer SET firstname = '" . $this->db->escape($data['firstname']) . "', lastname = '" . $this->db->escape($data['lastname']) . "', email = '" . $this->db->escape($data['email']) . "', telephone = '" . $this->db->escape($data['telephone']) . "', fax = '" . $this->db->escape($data['fax']) . "' WHERE customer_id = '" . (int)$this->customer->getId() . "'");
				}

	}
	public function editCustomerBrasil($data) {

        if ($data['data_nascimento'] == ""){
						$dataparts[0] = "00";
						$dataparts[1] = "00";
						$dataparts[2] = "0000";
					}else{
						$dataparts = explode("/",$data['data_nascimento']);
					}


		$this->db->query("UPDATE " . DB_PREFIX . "customer SET firstname = '" . $this->db->escape($data['firstname']) . "', cadastro_confirmado ='1' ". ", data_nascimento = '" . $this->db->escape($dataparts[2]."-".$dataparts[1]."-".$dataparts[0]) . "', sexo = '" . $this->db->escape($data['sexo']) . "', lastname = '" . $this->db->escape($data['lastname']). "', perfil = '" . $this->db->escape($data['perfil']) . "' ,contribuinte = 'S' WHERE customer_id = '" . (int)$this->customer->getId() . "'");
	}


	public function editPassword($email, $password) {
      	$this->db->query("UPDATE " . DB_PREFIX . "customer SET salt = '" . $this->db->escape($salt = substr(md5(uniqid(rand(), true)), 0, 9)) . "', password = '" . $this->db->escape(sha1($salt . sha1($salt . sha1($password)))) . "' WHERE LOWER(email) = '" . $this->db->escape(utf8_strtolower($email)) . "'");
	}

	public function editNewsletter($newsletter) {
		$this->db->query("UPDATE " . DB_PREFIX . "customer SET newsletter = '" . (int)$newsletter . "' WHERE customer_id = '" . (int)$this->customer->getId() . "'");
	}

	public function getCustomer($customer_id) {
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "customer WHERE customer_id = '" . (int)$customer_id . "'");

		return $query->row;
	}

	public function getCustomerByEmail($email) {
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "customer WHERE LOWER(email) = '" . $this->db->escape(utf8_strtolower($email)) . "'");

		return $query->row;
	}

	public function getCustomerByToken($token) {
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "customer WHERE token = '" . $this->db->escape($token) . "' AND token != ''");

		$this->db->query("UPDATE " . DB_PREFIX . "customer SET token = '' WHERE token = '" . $this->db->escape($token) . "' AND token != ''");

		return $query->row;
	}

	public function getCustomers($data = array()) {
		$sql = "SELECT *, CONCAT(c.firstname, ' ', c.lastname) AS name, cg.name AS customer_group FROM " . DB_PREFIX . "customer c LEFT JOIN " . DB_PREFIX . "customer_group cg ON (c.customer_group_id = cg.customer_group_id) ";

		$implode = array();

		if (isset($data['filter_name']) && !is_null($data['filter_name'])) {
			$implode[] = "LCASE(CONCAT(c.firstname, ' ', c.lastname)) LIKE '" . $this->db->escape(utf8_strtolower($data['filter_name'])) . "%'";
		}

		if (isset($data['filter_email']) && !is_null($data['filter_email'])) {
			$implode[] = "LCASE(c.email) = '" . $this->db->escape(utf8_strtolower($data['filter_email'])) . "'";
		}

		if (isset($data['filter_customer_group_id']) && !is_null($data['filter_customer_group_id'])) {
			$implode[] = "cg.customer_group_id = '" . $this->db->escape($data['filter_customer_group_id']) . "'";
		}

		if (isset($data['filter_status']) && !is_null($data['filter_status'])) {
			$implode[] = "c.status = '" . (int)$data['filter_status'] . "'";
		}

		if (isset($data['filter_approved']) && !is_null($data['filter_approved'])) {
			$implode[] = "c.approved = '" . (int)$data['filter_approved'] . "'";
		}

		if (isset($data['filter_ip']) && !is_null($data['filter_ip'])) {
			$implode[] = "c.customer_id IN (SELECT customer_id FROM " . DB_PREFIX . "customer_ip WHERE ip = '" . $this->db->escape($data['filter_ip']) . "')";
		}

		if (isset($data['filter_date_added']) && !is_null($data['filter_date_added'])) {
			$implode[] = "DATE(c.date_added) = DATE('" . $this->db->escape($data['filter_date_added']) . "')";
		}

		if ($implode) {
			$sql .= " WHERE " . implode(" AND ", $implode);
		}

		$sort_data = array(
			'name',
			'c.email',
			'customer_group',
			'c.status',
			'c.ip',
			'c.date_added'
		);

		if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
			$sql .= " ORDER BY " . $data['sort'];
		} else {
			$sql .= " ORDER BY name";
		}

		if (isset($data['order']) && ($data['order'] == 'DESC')) {
			$sql .= " DESC";
		} else {
			$sql .= " ASC";
		}

		if (isset($data['start']) || isset($data['limit'])) {
			if ($data['start'] < 0) {
				$data['start'] = 0;
			}

			if ($data['limit'] < 1) {
				$data['limit'] = 20;
			}

			$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
		}

		$query = $this->db->query($sql);

		return $query->rows;
	}

	public function getTotalCustomersByEmail($email) {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "customer WHERE LOWER(email) = '" . $this->db->escape(utf8_strtolower($email)) . "'");

		return $query->row['total'];
	}

	public function getIps($customer_id) {
		$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "customer_ip` WHERE customer_id = '" . (int)$customer_id . "'");

		return $query->rows;
	}

	public function isBanIp($ip) {
		$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "customer_ban_ip` WHERE ip = '" . $this->db->escape($ip) . "'");

		return $query->num_rows;
	}
}
?>
