<?php
class Customer {
  private $customer_id;
  private $firstname;
  private $lastname;
  private $email;
  private $telephone;
  private $fax;
  private $newsletter;
  private $customer_group_id;
  private $address_id;
  private $data_nascimento;
  private $sexo;
  private $cpf;
  private $rg;
  private $cnpj;
  private $razao_social;
  private $inscricao_estadual;
  private $id_futura;
  private $tipo_pessoa;
  private $efutura_id;
  private $approved;
  private $interests_remember;
  private $interests_date;
  private $registry;
  
  public function __construct($registry) {
    $this->registry = $registry;
    $this->config = $registry->get('config');
    $this->db = $registry->get('db');
    $this->request = $registry->get('request');
    $this->session = $registry->get('session');
    
    if (isset($this->session->data['customer_id'])) {
      $customer_query     = $this->db->query("SELECT * FROM " . DB_PREFIX . "customer WHERE customer_id = '" . (int)$this->session->data['customer_id'] . "' AND status = '1'");
      
      if ($customer_query->num_rows) {
        $this->customer_id = $customer_query->row['customer_id'];
        $this->firstname = $customer_query->row['firstname'];
        $this->lastname = $customer_query->row['lastname'];
        $this->email = $customer_query->row['email'];
        $this->telephone = $customer_query->row['telephone'];
        $this->fax = $customer_query->row['fax'];
        $this->newsletter = $customer_query->row['newsletter'];
        $this->customer_group_id = $customer_query->row['customer_group_id'];
        $this->address_id = $customer_query->row['address_id'];
        if($this->config->get('fields_register_brazil_status')){
          $this->data_nascimento    = $customer_query->row['data_nascimento'];
          $this->sexo               = $customer_query->row['sexo'];
          $this->cpf                = $customer_query->row['cpf'];
          $this->rg                 = $customer_query->row['rg'];
          $this->cnpj               = $customer_query->row['cnpj'];
          $this->razao_social       = $customer_query->row['razao_social'];
          $this->inscricao_estadual = $customer_query->row['inscricao_estadual'];
        }
        $this->id_futura          = $customer_query->row['id_futura'];
        $this->interests_remember = $customer_query->row['interests_remember'];
        $this->interests_date     = $customer_query->row['interests_date'];
        
        if(($customer_query->row['cpf']) && ($customer_query->row['cpf'] != '')){
          $this->tipo_pessoa = 'F';
        } else {
          $this->tipo_pessoa = 'J';
        }
        
        $this->efutura_id = $customer_query->row['id_futura'];// recuperar id futura
        $this->approved = $customer_query->row['approved'];
        
        //removi pra não ficar incluindo tanto registro na change.
        //como a nipo é especifica e salva o carrinho a toda inclusao de item, não tem problema em comentar
        //verificar solucao pra outras lojas também...
        //ByMatheus
        //$this->db->query("UPDATE " . DB_PREFIX . "customer SET cart = '" . $this->db->escape(isset($this->session->data['cart']) ? serialize($this->session->data['cart']) : '') . "', wishlist = '" . $this->db->escape(isset($this->session->data['wishlist']) ? serialize($this->session->data['wishlist']) : '') . "', ip = '" . $this->db->escape($this->request->server['REMOTE_ADDR']) . "' WHERE customer_id = '" . (int)$this->customer_id . "'");
        
        $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "customer_ip WHERE customer_id = '" . (int)$this->session->data['customer_id'] . "' AND ip = '" . $this->db->escape($this->request->server['REMOTE_ADDR']) . "'");
        
        if (!$query->num_rows) {
          $this->db->query("INSERT INTO " . DB_PREFIX . "customer_ip SET customer_id = '" . (int)$this->session->data['customer_id'] . "', ip = '" . $this->db->escape($this->request->server['REMOTE_ADDR']) . "', date_added = NOW()");
        }
      } else {
        $this->logout();
      }
    }
  }
  
  public function login($email, $password, $override = false) {
    if ($override) {
      $customer_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "customer where LOWER(email) = '" . $this->db->escape(utf8_strtolower($email)) . "' AND status = '1'");
    } else {
      if($this->config->get('config_new_pattern_purchase')){
        $customer_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "customer WHERE LOWER(email) = '" . $this->db->escape(utf8_strtolower($email)) . "' AND (password = SHA1(CONCAT(salt, SHA1(CONCAT(salt, SHA1('" . $this->db->escape($password) . "'))))) OR password = '" . $this->db->escape(md5($password)) . "') AND status = '1'");
      }else{
        $customer_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "customer WHERE LOWER(email) = '" . $this->db->escape(utf8_strtolower($email)) . "' AND (password = SHA1(CONCAT(salt, SHA1(CONCAT(salt, SHA1('" . $this->db->escape($password) . "'))))) OR password = '" . $this->db->escape(md5($password)) . "') AND status = '1' AND approved = '1'");
      }
    }
    
    if ($customer_query->num_rows) {
      $this->session->data['customer_id'] = $customer_query->row['customer_id'];
      
      if ($customer_query->row['cart'] && is_string($customer_query->row['cart'])) {
        $cart = unserialize($customer_query->row['cart']);
        
        foreach ($cart as $key => $value) {
          if (!array_key_exists($key, $this->session->data['cart'])) {
            $this->session->data['cart'][$key] = $value;
          }
        }
      }
      
      if ($customer_query->row['wishlist'] && is_string($customer_query->row['wishlist'])) {
        if (!isset($this->session->data['wishlist'])) {
          $this->session->data['wishlist'] = array();
        }
        
        $wishlist = unserialize($customer_query->row['wishlist']);
        
        foreach ($wishlist as $product_id) {
          if (!in_array($product_id, $this->session->data['wishlist'])) {
            $this->session->data['wishlist'][] = $product_id;
          }
        }
      }
      
      $this->customer_id = $customer_query->row['customer_id'];
      $this->firstname = $customer_query->row['firstname'];
      $this->lastname = $customer_query->row['lastname'];
      $this->email = $customer_query->row['email'];
      $this->telephone = $customer_query->row['telephone'];
      $this->fax = $customer_query->row['fax'];
      $this->newsletter = $customer_query->row['newsletter'];
      $this->customer_group_id = $customer_query->row['customer_group_id'];
      $this->address_id = $customer_query->row['address_id'];
      if($this->config->get('fields_register_brazil_status')){
        $this->data_nascimento    = $customer_query->row['data_nascimento'];
        $this->sexo               = $customer_query->row['sexo'];
        $this->cpf                = $customer_query->row['cpf'];
        $this->rg                 = $customer_query->row['rg'];
        $this->cnpj               = $customer_query->row['cnpj'];
        $this->razao_social       = $customer_query->row['razao_social'];
        $this->inscricao_estadual = $customer_query->row['inscricao_estadual'];
      }
      $this->efutura_id = $customer_query->row['id_futura'];// recuperar id futura
      $this->approved =  $customer_query->row['approved'];
	  
	  $this->interests_remember = $customer_query->row['interests_remember'];
      $this->interests_date     = $customer_query->row['interests_date'];
      
      //alterei para não dar update desnecessário e ficar congestionando a change_efutura
      if($customer_query->row['ip'] != $this->db->escape($this->request->server['REMOTE_ADDR'])){
        $this->db->query("UPDATE " . DB_PREFIX . "customer SET ip = '" . $this->db->escape($this->request->server['REMOTE_ADDR']) . "' WHERE customer_id = '" . (int)$this->customer_id . "'");
      }
      
      return true;
    } else {
      return false;
    }
  }
  
  public function logout() {
    
    //removi pra não ficar incluindo tanto registro na change.
    //como a nipo é especifica e salva o carrinho a toda inclusao de item, não tem problema em comentar
    //verificar solucao pra outras lojas também...
    //ByMatheus
    //$this->db->query("UPDATE " . DB_PREFIX . "customer SET cart = '" . $this->db->escape(isset($this->session->data['cart']) ? serialize($this->session->data['cart']) : '') . "', wishlist = '" . $this->db->escape(isset($this->session->data['wishlist']) ? serialize($this->session->data['wishlist']) : '') . "' WHERE customer_id = '" . (int)$this->customer_id . "'");
    
    unset($this->session->data['customer_id']);
    
    $this->customer_id = '';
    $this->firstname = '';
    $this->lastname = '';
    $this->email = '';
    $this->telephone = '';
    $this->fax = '';
    $this->newsletter = '';
    $this->customer_group_id = '';
    $this->address_id = '';
    $this->efutura_id = '';
    $this->approved = '';
    
    setcookie('user_logado', '');
    
  }
  
  public function getIdFutura(){
    return $this->efutura_id;
  }
  
  public function isLogged() {
    return $this->customer_id;
  }
  
  public function getId() {
    return $this->customer_id;
  }
  
  public function getFirstName() {
    return $this->firstname;
  }
  
  public function getLastName() {
    return $this->lastname;
  }
  
  public function getEmail() {
    return $this->email;
  }
  
  public function getTelephone() {
    return $this->telephone;
  }
  
  public function getFax() {
    return $this->fax;
  }
  
  public function getNewsletter() {
    return $this->newsletter;
  }
  
  public function getCustomerGroupId() {
    return $this->customer_group_id;
  }
  
  public function getAddressId() {
    return $this->address_id;
  }
  
  public function getApproved() {
    return $this->approved;
  }
  
  public function getDataNascimento() {
    return $this->data_nascimento;
  }
  
  public function getSexo() {
    return $this->sexo;
  }
  
  public function getCpf() {
    return $this->cpf;
  }
  
  public function getRg() {
    return $this->rg;
  }
  
  public function getCnpj() {
    return $this->cnpj;
  }
  
  public function getRazaoSocial() {
    return $this->razao_social;
  }
  
  public function getInscricaoEstadual() {
    return $this->inscricao_estadual;
  }
  
  public function getBalance() {
    $query = $this->db->query("SELECT SUM(amount) AS total FROM " . DB_PREFIX . "customer_transaction WHERE customer_id = '" . (int)$this->customer_id . "'");
    
    return $query->row['total'];
  }
  
  public function getID_Futura() {
    return $this->id_futura;
  }
  
  public function getTipo_pessoa() {
    return strtoupper($this->tipo_pessoa);
  }

  public function getInterestsRemember() {
    return $this->interests_remember;
  }
  
  public function getInterestsDate() {
    return $this->interests_date;
  }
  
  public function getRewardPoints() {
    $query = $this->db->query("SELECT SUM(points) AS total FROM " . DB_PREFIX . "customer_reward WHERE customer_id = '" . (int)$this->customer_id . "'");
    
    return $query->row['total'];
  }
  
  public function getInterestsArea($customer_id) {
     $layoutId = array () ;
     $modules  = array () ;
     $config   = array () ;
     $load = $this->registry->get('load');
     $load->model('account/customer');
     $interest =  $load->model_account_customer->getInterestsCustomer($customer_id);
     if ($this->config->get('lpbc_module_interests')) {
       $configModules = $this->config->get('lpbc_module') ;
     }
  
     if(isset($configModules)){
       foreach ($configModules as $key => $value) {
         if(!in_array($value['layout_id'], $layoutId)){
          $layoutId[] = $value['layout_id'];
          $config[$value['layout_id']] = array(
            'dm'           => $value['dm'],
            'limit'        => $value['limit'],
            'image_width'  => $value['image_width'],
            'image_height' => $value['image_height'],
            'position'     => $value['position']
          ); 
         }         
       }
       
       foreach ($layoutId as $key => $value) {
         foreach ($interest as $intKey => $intValue) {
           $modules[] = array(
             'category_id'  => $intValue['category_id'],
             'layout_id'    => $value,
             'dm'           => $config[$value]['dm'],
             'limit'        => $config[$value]['limit'],
             'image_width'  => $config[$value]['image_width'],
             'image_height' => $config[$value]['image_height'],
             'position'     => $config[$value]['position'],
             'status'       => 1,
             'sort_order'   => $this->config->get('lpbc_module_interests_order') ? $this->config->get('lpbc_module_interests_order') : 1
           );  
         }
       }

     }
     
     return $modules;
  }  
  
}
?>
