<?php
class ModelAccountAddress extends Model {
	public function addAddress($data) {

		$this->load->helper('Ftr_sql');

			$dataAdress = array();
			$dataAdress[] = (int)$this->customer->getId();
			$dataAdress[] = ucwords($data['firstname']);
			$dataAdress[] = ucwords($data['lastname']);
			$dataAdress[] = '';
			$dataAdress[] = '';
			$dataAdress[] = ucwords($data['address_1']);
			$dataAdress[] = substr(ucwords($data['address_2']), 0, 60);
			$dataAdress[] = preg_replace('/([^0-9])/i','',$data['postcode']);
			$dataAdress[] = ucwords($data['city']);
			$dataAdress[] = $data['zone_id'];
			$dataAdress[] = (isset($data['country_id']) && $data['country_id']!='') ? $data['country_id'] : Type_PaisId::Tp_Brasil;
			$dataAdress[] = ($data['apelido']!='') ? ucwords($data['apelido']) : substr(ucwords($data['address_2']), 0, 80);
			$dataAdress[] = preg_replace('/([^0-9])/i','',$data['numero']);
			$dataAdress[] = ucwords($data['complemento']);
			$dataAdress[] = ucwords($data['tipo_logradouro']);
			$dataAdress[] = (isset($data['logradouro']) && $data['logradouro']!='')  ? ucwords($data['logradouro']) : ucwords($data['address_1']);
			$dataAdress[] = (isset($data['codigo_municipio']) && $data['codigo_municipio']!='') ? $data['codigo_municipio'] : NULL;

			$sqlInsert = Ftr_sql::generateInsert('oc_address',
			['customer_id', 'firstname', 'lastname', 'company', 'company_id', 'address_1', 'address_2',
			 'postcode', 'city', 'zone_id','country_id', 'apelido', 'numero', 'complemento', 'tipo_logradouro',
			 'logradouro', 'codigo_municipio']);

			$this->db->executeSql($sqlInsert, $dataAdress);

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

			if (!empty($data['default'])) {
				$this->db->query("UPDATE " . DB_PREFIX . "customer SET address_id = '" . (int)$address_id . "' WHERE customer_id = '" . (int)$this->customer->getId() . "'");
			}

			return $address_id;
	}

	public function editAddress($address_id, $data) {

		$this->load->helper('Ftr_sql');

			$dataAdress = array();
			$dataAdress[] = ucwords($data['firstname']);
			$dataAdress[] = ucwords($data['lastname']);
			$dataAdress[] = '';
			$dataAdress[] = '';
			$dataAdress[] = ucwords($data['address_1']);
			$dataAdress[] = substr(ucwords($data['address_2']), 0, 60);
			$dataAdress[] = preg_replace('/([^0-9])/i','',$data['postcode']);
			$dataAdress[] = ucwords($data['city']);
			$dataAdress[] = $data['zone_id'];
			$dataAdress[] = (isset($data['country_id']) && $data['country_id']!='') ? $data['country_id'] : Type_PaisId::Tp_Brasil;
			$dataAdress[] = ucwords($data['apelido']);
			$dataAdress[] = preg_replace('/([^0-9])/i','',$data['numero']);
			$dataAdress[] = ucwords($data['complemento']);
			$dataAdress[] = ucwords($data['tipo_logradouro']);
			$dataAdress[] = (isset($data['logradouro']) && $data['logradouro']!='')  ? ucwords($data['logradouro']) : ucwords($data['address_1']);
			$dataAdress[] = (isset($data['codigo_municipio']) && $data['codigo_municipio']!='') ? $data['codigo_municipio'] : NULL;

			$sqlAddress = Ftr_sql::generateUpdate('oc_address',
			['firstname', 'lastname', 'company', 'company_id', 'address_1', 'address_2',
			 'postcode', 'city', 'zone_id','country_id', 'apelido', 'numero', 'complemento', 'tipo_logradouro',
			 'logradouro', 'codigo_municipio'],
			 'customer_id = ' . (int)$this->customer->getId().' AND address_id = '.$address_id);

			$this->db->executeSql($sqlAddress, $dataAdress);

			if (!empty($data['default'])) {
				$this->db->query("UPDATE " . DB_PREFIX . "customer SET address_id = '" . (int)$address_id . "' WHERE customer_id = '" . (int)$this->customer->getId() . "'");
			}
	}

	public function deleteAddress($address_id) {
		$this->db->query("DELETE FROM " . DB_PREFIX . "address WHERE address_id = '" . (int)$address_id . "' AND customer_id = '" . (int)$this->customer->getId() . "'");
	}

  public function getCountryByZone($zone_id) {
		$query = $this->db->query("SELECT DISTINCT (COUNTRY_ID) as pais FROM " . DB_PREFIX . "zone WHERE zone_id = '" . (int)$zone_id . "'");
		if (isset($query->row['pais'])){
            return $query->row['pais'];
    }
	}

	public function getSiglaByZone($zone_id) {
		$query = $this->db->query("SELECT DISTINCT (code) as sigla FROM " . DB_PREFIX . "zone WHERE zone_id = '" . (int)$zone_id . "'");
		if (isset($query->row['sigla'])){
            return $query->row['sigla'];
    }
	}

	public function getAddress($address_id) {


        if($this->config->get('listapresente_status')){
            $address_query = $this->db->query("SELECT DISTINCT * FROM " . DB_PREFIX . "address WHERE address_id = '" . (int)$address_id . "'");
        }else{
            $address_query = $this->db->query("SELECT DISTINCT * FROM " . DB_PREFIX . "address WHERE address_id = '" . (int)$address_id . "' AND customer_id = '" . (int)$this->customer->getId() . "'");
        }

		if ($address_query->num_rows) {
			$country_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "country` WHERE country_id = '" . (int)$address_query->row['country_id'] . "'");

			if ($country_query->num_rows) {
				$country = $country_query->row['name'];
                // arrumando a exibição do país, porque sempre salva no formato internacional, mas só funciona no Brasil (°_°)
				$country_pt = Type_mktCountryIso3::getNickFromValue($country_query->row['iso_code_3'])??'';
				$iso_code_2 = $country_query->row['iso_code_2'];
				$iso_code_3 = $country_query->row['iso_code_3'];
				$address_format = $country_query->row['address_format'];
			} else {
				$country = '';
                $country_pt = '';
				$iso_code_2 = '';
				$iso_code_3 = '';
				$address_format = '';
			}

			$zone_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE zone_id = '" . (int)$address_query->row['zone_id'] . "'");

			if ($zone_query->num_rows) {
				$zone = $zone_query->row['name'];
				$zone_code = $zone_query->row['code'];
			} else {
				$zone = '';
				$zone_code = '';
			}

			$address_data = array(
				'firstname'      => $address_query->row['firstname'],
				'lastname'       => $address_query->row['lastname'],
				'company'        => $address_query->row['company'],
				'company_id'     => $address_query->row['company_id'],
				'address_1'      => $address_query->row['address_1'],
				'address_2'      => $address_query->row['address_2'],
				'apelido'     => $address_query->row['apelido'],
				'numero'      => $address_query->row['numero'],
				'complemento' => $address_query->row['complemento'],
				'postcode'       => $address_query->row['postcode'],
				'city'           => $address_query->row['city'],
				'zone_id'        => $address_query->row['zone_id'],
				'zone'           => $zone,
				'zone_code'      => $zone_code,
				'country_id'     => $address_query->row['country_id'],
				'country'        => $country,
				'country_pt'     => $country_pt,
				'iso_code_2'     => $iso_code_2,
				'iso_code_3'     => $iso_code_3,
				'address_format' => $address_format,
				'tipo_logradouro' => $address_query->row['tipo_logradouro'],
				'logradouro' => $address_query->row['logradouro'],
				'codigo_municipio' => $address_query->row['codigo_municipio']
			);

			return $address_data;
		} else {
			return false;
		}
	}


	public function getAddressCustomer($customer_id) {

    $address_query = $this->db->query("SELECT DISTINCT * FROM " . DB_PREFIX . "address WHERE  customer_id = '" . (int)$customer_id . "'");

		if ($address_query->num_rows) {
			$country_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "country` WHERE country_id = '" . (int)$address_query->row['country_id'] . "'");

			if ($country_query->num_rows) {
				$country = $country_query->row['name'];
				$iso_code_2 = $country_query->row['iso_code_2'];
				$iso_code_3 = $country_query->row['iso_code_3'];
				$address_format = $country_query->row['address_format'];
			} else {
				$country = '';
				$iso_code_2 = '';
				$iso_code_3 = '';
				$address_format = '';
			}

			$zone_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE zone_id = '" . (int)$address_query->row['zone_id'] . "'");

			if ($zone_query->num_rows) {
				$zone = $zone_query->row['name'];
				$zone_code = $zone_query->row['code'];
			} else {
				$zone = '';
				$zone_code = '';
			}

			$address_data = array(
				'firstname'      => $address_query->row['firstname'],
				'lastname'       => $address_query->row['lastname'],
				'company'        => $address_query->row['company'],
				'company_id'     => $address_query->row['company_id'],
				'address_1'      => $address_query->row['address_1'],
				'address_2'      => $address_query->row['address_2'],
				'apelido'     => $address_query->row['apelido'],
				'numero'      => $address_query->row['numero'],
				'complemento' => $address_query->row['complemento'],
				'postcode'       => $address_query->row['postcode'],
				'city'           => $address_query->row['city'],
				'zone_id'        => $address_query->row['zone_id'],
				'zone'           => $zone,
				'zone_code'      => $zone_code,
				'country_id'     => $address_query->row['country_id'],
				'country'        => $country,
				'iso_code_2'     => $iso_code_2,
				'iso_code_3'     => $iso_code_3,
				'tipo_logradouro' => $address_query->row['tipo_logradouro'],
        'logradouro'      => $address_query->row['logradouro'],
        'codigo_municipio'=> $address_query->row['codigo_municipio'],
				'address_format' => $address_format
			);

			return $address_data;
		} else {
			return false;
		}
	}


    public function getAddressesLista($cliente_id) {
        $address_data = array();
        $query = $this->db->query("SELECT a.`address_id`,
                                          a.`customer_id`,
                                          a.`firstname`,
                                          a.`lastname`,
                                          a.`company`,
                                          a.`company_id`,
                                          a.`numero`,
                                          a.`complemento`,
					  															a.`apelido`,
                                          a.`address_1`,
                                          a.`address_2`,
                                          a.`city`,
                                          a.`postcode`,
                                          a.`country_id`,
                                          a.`zone_id`
                                    FROM " . DB_PREFIX . "address a
                                        INNER JOIN " . DB_PREFIX . "customer c ON a.address_id = c.address_id
                                    WHERE a.customer_id = '" . (int)$cliente_id . "'");
        foreach ($query->rows as $result) {
            $country_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "country` WHERE country_id = '" . (int)$result['country_id'] . "'");

            if ($country_query->num_rows) {
                $country = $country_query->row['name'];
                $iso_code_2 = $country_query->row['iso_code_2'];
                $iso_code_3 = $country_query->row['iso_code_3'];
                $address_format = $country_query->row['address_format'];
            } else {
                $country = '';
                $iso_code_2 = '';
                $iso_code_3 = '';
                $address_format = '';
            }

            $zone_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE zone_id = '" . (int)$result['zone_id'] . "'");

            if ($zone_query->num_rows) {
                $zone = $zone_query->row['name'];
                $zone_code = $zone_query->row['code'];
            } else {
                $zone = '';
                $zone_code = '';
            }

            $address_data[$result['address_id']] = array(
                'address_id'     => $result['address_id'],
                'firstname'      => $result['firstname'],
                'lastname'       => $result['lastname'],
                'company'        => $result['company'],
                'company_id'     => $result['company_id'],
                'address_1'      => $result['address_1'],
                'address_2'      => $result['address_2'],
								'numero'         => $result['numero'],
								'apelido'        => $result['apelido'],
								'complemento'    => $result['complemento'],
                'postcode'       => $result['postcode'],
                'city'           => $result['city'],
                'zone_id'        => $result['zone_id'],
                'zone'           => $zone,
                'zone_code'      => $zone_code,
                'country_id'     => $result['country_id'],
                'country'        => $country,
                'iso_code_2'     => $iso_code_2,
                'iso_code_3'     => $iso_code_3,
                'address_format' => $address_format
            );
        }

        return $address_data;
    }


	public function getAddresses() {
		$address_data = array();

		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "address WHERE customer_id = '" . (int)$this->customer->getId() . "'");

		foreach ($query->rows as $result) {
			$country_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "country` WHERE country_id = '" . (int)$result['country_id'] . "'");

			if ($country_query->num_rows) {
				$country = $country_query->row['name'];
                // arrumando a exibição do país, porque sempre salva no formato internacional, mas só funciona no Brasil (°_°)
                $country_pt = Type_mktCountryIso3::getNickFromValue($country_query->row['iso_code_3'])??'';
				$iso_code_2 = $country_query->row['iso_code_2'];
				$iso_code_3 = $country_query->row['iso_code_3'];
				$address_format = $country_query->row['address_format'];
			} else {
				$country = '';
                $country_pt = '';
				$iso_code_2 = '';
				$iso_code_3 = '';
				$address_format = '';
			}

			$zone_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE zone_id = '" . (int)$result['zone_id'] . "'");

			if ($zone_query->num_rows) {
				$zone = $zone_query->row['name'];
				$zone_code = $zone_query->row['code'];
			} else {
				$zone = '';
				$zone_code = '';
			}

			$address_data[$result['address_id']] = array(
				'address_id'     => $result['address_id'],
				'firstname'      => $result['firstname'],
				'lastname'       => $result['lastname'],
				'company'        => $result['company'],
				'company_id'     => $result['company_id'],
				'address_1'      => $result['address_1'],
				'address_2'      => $result['address_2'],
				'apelido'     => $result['apelido'],
				'numero'      => $result['numero'],
				'complemento' => $result['complemento'],
				'postcode'       => $result['postcode'],
				'city'           => $result['city'],
				'zone_id'        => $result['zone_id'],
				'zone'           => $zone,
				'zone_code'      => $zone_code,
				'country_id'     => $result['country_id'],
				'country'        => $country,
				'country_pt'     => $country_pt,
				'iso_code_2'     => $iso_code_2,
				'iso_code_3'     => $iso_code_3,
				'address_format' => $address_format,
        'codigo_municipio' => $result['codigo_municipio'],
        'tipo_logradouro' => $result['tipo_logradouro'],
        'logradouro' => $result['logradouro']
			);
		}

		return $address_data;
	}

	public function getTotalAddresses() {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "address WHERE customer_id = '" . (int)$this->customer->getId() . "'");

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