<?php
class ControllerApiCustomer extends Controller {
	public function index() {
		$this->load->language('api/customer');

		// Delete past customer in case there is an error
		unset($this->session->data['customer']);

		$json = array();

		if (!isset($this->session->data['api_id'])) {
			$json['error']['warning'] = $this->language->get('error_permission');
		} else {
			// Add keys for missing post vars
			$keys = array(
				'customer_id',
				'customer_group_id',
				'firstname',
				'lastname',
				'email',
				'telephone',
				'fax'
			);

			foreach ($keys as $key) {
				if (!isset($this->request->post[$key])) {
					$this->request->post[$key] = '';
				}
			}

			// Customer
			if ($this->request->post['customer_id']) {
				$this->load->model('account/customer');

				$customer_info = $this->model_account_customer->getCustomer($this->request->post['customer_id']);

				if (!$customer_info || !$this->customer->login($customer_info['email'], '', true)) {
					$json['error']['warning'] = $this->language->get('error_customer');
				}
			}

			if ((utf8_strlen(trim($this->request->post['firstname'])) < 1) || (utf8_strlen(trim($this->request->post['firstname'])) > 32)) {
				$json['error']['firstname'] = $this->language->get('error_firstname');
			}

			if ((utf8_strlen(trim($this->request->post['lastname'])) < 1) || (utf8_strlen(trim($this->request->post['lastname'])) > 32)) {
				$json['error']['lastname'] = $this->language->get('error_lastname');
			}

			if ((utf8_strlen($this->request->post['email']) > 96) || (!preg_match('/^[^\@]+@.*.[a-z]{2,15}$/i', $this->request->post['email']))) {
				$json['error']['email'] = $this->language->get('error_email');
			}

			if ((utf8_strlen($this->request->post['telephone']) < 3) || (utf8_strlen($this->request->post['telephone']) > 32)) {
				$json['error']['telephone'] = $this->language->get('error_telephone');
			}

			// Customer Group
			if (isset($this->request->post['customer_group_id']) && is_array($this->config->get('config_customer_group_display')) && in_array($this->request->post['customer_group_id'], $this->config->get('config_customer_group_display'))) {
				$customer_group_id = $this->request->post['customer_group_id'];
			} else {
				$customer_group_id = $this->config->get('config_customer_group_id');
			}

			// Custom field validation
			$this->load->model('account/custom_field');

			$custom_fields = $this->model_account_custom_field->getCustomFields($customer_group_id);

			foreach ($custom_fields as $custom_field) {
				if (($custom_field['location'] == 'account') && $custom_field['required'] && empty($this->request->post['custom_field'][$custom_field['custom_field_id']])) {
					$json['error']['custom_field' . $custom_field['custom_field_id']] = sprintf($this->language->get('error_custom_field'), $custom_field['name']);
				}
			}


				$config_campo_celular    = $this->config->get('config_campo_celular');
				$config_campo_sexo       = $this->config->get('config_campo_sexo');
				$config_campo_nascimento = $this->config->get('config_campo_nascimento');
				$config_campo_idade      = $this->config->get('config_campo_idade');
				$config_campo_pessoa     = $this->config->get('config_campo_pessoa');
				$config_campo_rg         = $this->config->get('config_campo_rg');
				$config_campo_ie         = $this->config->get('config_campo_ie');
				$config_campo_im         = $this->config->get('config_campo_im');

				if ($config_campo_celular > 0) {
					if ($config_campo_celular == 1 || ($config_campo_celular == 2 && $this->request->post['custom_field']['celular'] != '')) {
						if ((utf8_strlen($this->request->post['custom_field']['celular']) < 3) || (utf8_strlen($this->request->post['custom_field']['celular']) > 32)) {
							$json['error']['celular'] = $this->language->get('error_celular');
						}
					}
				}

				if ($config_campo_sexo > 0) {
					if ($config_campo_sexo == 1 || ($config_campo_sexo == 2 && isset($this->request->post['custom_field']['sexo']))) {
						if (!isset($this->request->post['custom_field']['sexo']) || ($this->request->post['custom_field']['sexo'] != 'f' && $this->request->post['custom_field']['sexo'] != 'm')) {
							$json['error']['sexo'] = $this->language->get('error_sexo');
						}
					}
				}

				if ($config_campo_nascimento > 0) {
					if ($config_campo_nascimento == 1 || ($config_campo_nascimento == 2 && $this->request->post['custom_field']['nascimento'] != '')) {
						if (!preg_match('/([12][0-9]{3}-(0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|([12][0-9]{3}-(0[469]|11)-(0[1-9]|[12][0-9]|30))|([12][0-9]([02468][1235679]|[13579][01345789])-02-(0[1-9]|1[0-9]|2[0-8]))|([12][0-9]([02468][048]|[13579][26])-02-(0[1-9]|[12][0-9]))/', $this->request->post['custom_field']['nascimento'])) {
							$json['error']['nascimento'] = $this->language->get('error_nascimento');
						} else {
							if (is_numeric($config_campo_idade) && $config_campo_idade > 0) {
								$date1 = new DateTime(date('Y-m-d'));
								$date2 = new DateTime($this->request->post['custom_field']['nascimento']);
								$interval = $date1->diff($date2);
								$age = $interval->y;
								if ($age < $config_campo_idade) {
									$json['error']['nascimento'] = sprintf($this->language->get('error_idade'), $config_campo_idade);
								}
							}
						}
					}
				}

				if (isset($this->request->post['custom_field']['country_id']) && is_numeric($this->request->post['custom_field']['country_id'])) {
					$country_name = '';

					$this->load->model('localisation/country');

					$country_info = $this->model_localisation_country->getCountry($this->request->post['custom_field']['country_id']);

					if ($country_info) {
						$country_name = mb_strtolower(trim($country_info['name']), 'UTF-8');
					} else {
						$json['error']['custom_field_country'] = $this->language->get('error_country');
					}

					if ($country_name == 'brasil' || $country_name == 'brazil') {
						if (!preg_match('/^\([0-9]{2}\) [0-9]{4,5}-[0-9]{4}$/', $this->request->post['telephone'])) {
							$json['error']['telephone'] = 'Telefone inválido! Informe corretamente o DDD e o número no formato: (99) 99999-9999';
						} else {
							if (!preg_match('/^\((11|12|13|14|15|16|17|18|19|21|22|24|27|28|31|32|33|34|35|37|38|41|42|43|44|45|46|47|48|49|51|53|54|55|61|62|63|64|65|66|67|68|69|71|73|74|75|77|79|81|82|83|84|85|86|87|88|89|91|92|93|94|95|96|97|98|99)\) [0-9]{4,5}-[0-9]{4}$/', $this->request->post['telephone'])) {
								$json['error']['telephone'] = 'DDD inválido! Informe corretamente o DDD e o número no formato: (99) 99999-9999';
							}
						}

						if ($config_campo_celular > 0) {
							if ($config_campo_celular == 1 || ($config_campo_celular == 2 && $this->request->post['custom_field']['celular'] != '')) {
								if (!preg_match('/^\([0-9]{2}\) [0-9]{4,5}-[0-9]{4}$/', $this->request->post['custom_field']['celular'])) {
									$json['error']['celular'] = 'Celular inválido! Informe corretamente o DDD e o número no formato: (99) 99999-9999';
								} else {
									if (!preg_match('/^\((11|12|13|14|15|16|17|18|19|21|22|24|27|28|31|32|33|34|35|37|38|41|42|43|44|45|46|47|48|49|51|53|54|55|61|62|63|64|65|66|67|68|69|71|73|74|75|77|79|81|82|83|84|85|86|87|88|89|91|92|93|94|95|96|97|98|99)\) [0-9]{4,5}-[0-9]{4}$/', $this->request->post['telephone'])) {
										$json['error']['celular'] = 'DDD inválido! Informe corretamente o DDD e o número no formato: (99) 99999-9999';
									}
								}
							}
						}

						if ($this->request->post['fax'] != '') {
							if (!preg_match('/^\([0-9]{2}\) [0-9]{4,5}-[0-9]{4}$/', $this->request->post['fax'])) {
								$json['error']['fax'] = 'Fax inválido! Informe corretamente o DDD e o número no formato: (99) 99999-9999';
							} else {
								if (!preg_match('/^\((11|12|13|14|15|16|17|18|19|21|22|24|27|28|31|32|33|34|35|37|38|41|42|43|44|45|46|47|48|49|51|53|54|55|61|62|63|64|65|66|67|68|69|71|73|74|75|77|79|81|82|83|84|85|86|87|88|89|91|92|93|94|95|96|97|98|99)\) [0-9]{4,5}-[0-9]{4}$/', $this->request->post['fax'])) {
									$json['error']['fax'] = 'DDD inválido! Informe corretamente o DDD e o número no formato: (99) 99999-9999';
								}
							}
						}

						if (!isset($this->request->post['custom_field']['tipo']) || ($this->request->post['custom_field']['tipo'] != 'f' && $this->request->post['custom_field']['tipo'] != 'j')) {
							$json['error']['tipo'] = 'Selecione o tipo de pessoa.';
						} else {
							$this->load->model('account/customer');

							if ($this->request->post['custom_field']['tipo'] == 'f') {
								if (!$this->model_account_customer->validaCPF($this->request->post['custom_field']['cpf'])) {
									$json['error']['cpf'] = 'CPF inválido! Informe um CPF válido no formato: 999.999.999-99';
								}

								if ($config_campo_rg > 0) {
									if ($config_campo_rg == 1 || ($config_campo_rg == 2 && $this->request->post['custom_field']['rg'] != '')) {
										if ((utf8_strlen($this->request->post['custom_field']['rg']) < 3) || (utf8_strlen($this->request->post['custom_field']['rg']) > 32)) {
											$json['error']['rg'] = 'O RG deve ter entre 3 e 32 caracteres!';
										}
									}
								}
							}
							if ($this->request->post['custom_field']['tipo'] == 'j') {
								if (!$this->model_account_customer->validaCNPJ($this->request->post['custom_field']['cnpj'])) {
									$json['error']['cnpj'] = 'CNPJ inválido! Informe um CNPJ válido no formato: 99.999.999/9999-99';
								}

								if ((utf8_strlen($this->request->post['custom_field']['razao']) < 3) || (utf8_strlen($this->request->post['custom_field']['razao']) > 32)) {
									$json['error']['razao'] = 'A razão social deve ter entre 3 e 32 caracteres!';
								}

								if ($config_campo_ie > 0) {
									if ($config_campo_ie == 1 || ($config_campo_ie == 2 && $this->request->post['custom_field']['ie'] != '')) {
										if ((utf8_strlen($this->request->post['custom_field']['ie']) < 3) || (utf8_strlen($this->request->post['custom_field']['ie']) > 32)) {
											$json['error']['ie'] = 'A Inscrição Estadual deve ter entre 3 e 32 caracteres!';
										}
									}
								}

								if ($config_campo_im > 0) {
									if ($config_campo_im == 1 || ($config_campo_im == 2 && $this->request->post['custom_field']['im'] != '')) {
										if ((utf8_strlen($this->request->post['custom_field']['im']) < 3) || (utf8_strlen($this->request->post['custom_field']['im']) > 32)) {
											$json['error']['im'] = 'A Inscrição Municipal deve ter entre 3 e 32 caracteres!';
										}
									}
								}
							}
						}
					}
				} else {
					$json['error']['custom_field_country'] = $this->language->get('error_country');
				}
			
			if (!$json) {
				$this->session->data['customer'] = array(
					'customer_id'       => $this->request->post['customer_id'],
					'customer_group_id' => $customer_group_id,
					'firstname'         => $this->request->post['firstname'],
					'lastname'          => $this->request->post['lastname'],
					'email'             => $this->request->post['email'],
					'telephone'         => $this->request->post['telephone'],
					'fax'               => $this->request->post['fax'],
					'custom_field'      => isset($this->request->post['custom_field']) ? $this->request->post['custom_field'] : array()
				);

				$json['success'] = $this->language->get('text_success');
			}
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}
}