<?php
class ControllerAccountEdit extends Controller {
	private $error = array();

	public function index() {
		if (!$this->customer->isLogged()) {
			$this->session->data['redirect'] = $this->url->link('account/edit', '', 'SSL');

			$this->response->redirect($this->url->link('account/login', '', 'SSL'));
		}

		$this->load->language('account/edit');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->document->addScript('catalog/view/javascript/jquery/datetimepicker/moment.js');
		$this->document->addScript('catalog/view/javascript/jquery/datetimepicker/bootstrap-datetimepicker.min.js');
		$this->document->addStyle('catalog/view/javascript/jquery/datetimepicker/bootstrap-datetimepicker.min.css');

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

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
			$this->model_account_customer->editCustomer($this->request->post);

			$this->session->data['success'] = $this->language->get('text_success');

			// Add to activity log
			$this->load->model('account/activity');

			$activity_data = array(
				'customer_id' => $this->customer->getId(),
				'name'        => $this->customer->getFirstName() . ' ' . $this->customer->getLastName()
			);

			$this->model_account_activity->addActivity('edit', $activity_data);

			$this->response->redirect($this->url->link('account/account', '', 'SSL'));
		}

		$data['breadcrumbs'] = array();

		$data['breadcrumbs'][] = array(
			'text'      => $this->language->get('text_home'),
			'href'      => $this->url->link('common/home')
		);

		$data['breadcrumbs'][] = array(
			'text'      => $this->language->get('text_account'),
			'href'      => $this->url->link('account/account', '', 'SSL')
		);

		$data['breadcrumbs'][] = array(
			'text'      => $this->language->get('text_edit'),
			'href'      => $this->url->link('account/edit', '', 'SSL')
		);

		$data['heading_title'] = $this->language->get('heading_title');

		$data['text_your_details'] = $this->language->get('text_your_details');
		$data['text_additional'] = $this->language->get('text_additional');
		$data['text_select'] = $this->language->get('text_select');
		$data['text_loading'] = $this->language->get('text_loading');

		$data['entry_firstname'] = $this->language->get('entry_firstname');
		$data['entry_lastname'] = $this->language->get('entry_lastname');
		$data['entry_email'] = $this->language->get('entry_email');
		$data['entry_telephone'] = $this->language->get('entry_telephone');
		$data['entry_fax'] = $this->language->get('entry_fax');

		$data['button_continue'] = $this->language->get('button_continue');
		$data['button_back'] = $this->language->get('button_back');
		$data['button_upload'] = $this->language->get('button_upload');

		if (isset($this->error['warning'])) {
			$data['error_warning'] = $this->error['warning'];
		} else {
			$data['error_warning'] = '';
		}

		if (isset($this->error['firstname'])) {
			$data['error_firstname'] = $this->error['firstname'];
		} else {
			$data['error_firstname'] = '';
		}

		if (isset($this->error['lastname'])) {
			$data['error_lastname'] = $this->error['lastname'];
		} else {
			$data['error_lastname'] = '';
		}

		if (isset($this->error['email'])) {
			$data['error_email'] = $this->error['email'];
		} else {
			$data['error_email'] = '';
		}

		if (isset($this->error['telephone'])) {
			$data['error_telephone'] = $this->error['telephone'];
		} else {
			$data['error_telephone'] = '';
		}

		if (isset($this->error['custom_field'])) {
			$data['error_custom_field'] = $this->error['custom_field'];
		} else {
			$data['error_custom_field'] = array();
		}

		$data['action'] = $this->url->link('account/edit', '', 'SSL');

		if ($this->request->server['REQUEST_METHOD'] != 'POST') {
			$customer_info = $this->model_account_customer->getCustomer($this->customer->getId());
		}

		if (isset($this->request->post['firstname'])) {
			$data['firstname'] = $this->request->post['firstname'];
		} elseif (!empty($customer_info)) {
			$data['firstname'] = $customer_info['firstname'];
		} else {
			$data['firstname'] = '';
		}

		if (isset($this->request->post['lastname'])) {
			$data['lastname'] = $this->request->post['lastname'];
		} elseif (!empty($customer_info)) {
			$data['lastname'] = $customer_info['lastname'];
		} else {
			$data['lastname'] = '';
		}

		if (isset($this->request->post['email'])) {
			$data['email'] = $this->request->post['email'];
		} elseif (!empty($customer_info)) {
			$data['email'] = $customer_info['email'];
		} else {
			$data['email'] = '';
		}

		if (isset($this->request->post['telephone'])) {
			$data['telephone'] = $this->request->post['telephone'];
		} elseif (!empty($customer_info)) {
			$data['telephone'] = $customer_info['telephone'];
		} else {
			$data['telephone'] = '';
		}

		if (isset($this->request->post['fax'])) {
			$data['fax'] = $this->request->post['fax'];
		} elseif (!empty($customer_info)) {
			$data['fax'] = $customer_info['fax'];
		} else {
			$data['fax'] = '';
		}

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

		$data['custom_fields'] = $this->model_account_custom_field->getCustomFields($this->config->get('config_customer_group_id'));

		if (isset($this->request->post['custom_field'])) {
			$data['account_custom_field'] = $this->request->post['custom_field'];
		} elseif (isset($customer_info)) {
			$data['account_custom_field'] = unserialize($customer_info['custom_field']);
		} else {
			$data['account_custom_field'] = array();
		}

		$data['back'] = $this->url->link('account/account', '', 'SSL');


				$data['entry_country']       = $this->language->get('entry_country');
				$data['entry_celular']       = $this->language->get('entry_celular');
				$data['entry_tipo']          = $this->language->get('entry_tipo');
				$data['entry_tipo_fisica']   = $this->language->get('entry_tipo_fisica');
				$data['entry_tipo_juridica'] = $this->language->get('entry_tipo_juridica');
				$data['entry_cpf']           = $this->language->get('entry_cpf');
				$data['entry_rg']            = $this->language->get('entry_rg');
				$data['entry_razao']         = $this->language->get('entry_razao');
				$data['entry_cnpj']          = $this->language->get('entry_cnpj');
				$data['entry_ie']            = $this->language->get('entry_ie');
				$data['entry_im']            = $this->language->get('entry_im');
				$data['entry_nascimento']    = $this->language->get('entry_nascimento');
				$data['entry_sexo']          = $this->language->get('entry_sexo');
				$data['entry_sexo_m']        = $this->language->get('entry_sexo_m');
				$data['entry_sexo_f']        = $this->language->get('entry_sexo_f');
				$data['entry_numero']        = $this->language->get('entry_numero');
				$data['entry_complemento']   = $this->language->get('entry_complemento');

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

				if (isset($this->error['fax'])) {
					$data['error_fax'] = $this->error['fax'];
				} else {
					$data['error_fax'] = '';
				}

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

				$data['countries'] = $this->model_localisation_country->getCountries();
			
		$data['column_left'] = $this->load->controller('common/column_left');
		$data['column_right'] = $this->load->controller('common/column_right');
		$data['content_top'] = $this->load->controller('common/content_top');
		$data['content_bottom'] = $this->load->controller('common/content_bottom');
		$data['footer'] = $this->load->controller('common/footer');
		$data['header'] = $this->load->controller('common/header');

		if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/account/edit.tpl')) {
			$this->response->setOutput($this->load->view($this->config->get('config_template') . '/template/account/edit.tpl', $data));
		} else {
			$this->response->setOutput($this->load->view('default/template/account/edit.tpl', $data));
		}
	}

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

		if ((utf8_strlen(trim($this->request->post['lastname'])) < 1) || (utf8_strlen(trim($this->request->post['lastname'])) > 32)) {
			$this->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'])) {
			$this->error['email'] = $this->language->get('error_email');
		}

		if (($this->customer->getEmail() != $this->request->post['email']) && $this->model_account_customer->getTotalCustomersByEmail($this->request->post['email'])) {
			$this->error['warning'] = $this->language->get('error_exists');
		}

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

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

		$custom_fields = $this->model_account_custom_field->getCustomFields($this->config->get('config_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']])) {
				$this->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)) {
							$this->error['custom_field']['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')) {
							$this->error['custom_field']['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'])) {
							$this->error['custom_field']['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) {
									$this->error['custom_field']['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 {
						$this->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'])) {
							$this->error['custom_field']['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'])) {
								$this->error['custom_field']['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'])) {
									$this->error['custom_field']['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'])) {
										$this->error['custom_field']['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'])) {
								$this->error['custom_field']['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'])) {
									$this->error['custom_field']['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')) {
							$this->error['custom_field']['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'])) {
									$this->error['custom_field']['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)) {
											$this->error['custom_field']['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'])) {
									$this->error['custom_field']['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)) {
									$this->error['custom_field']['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)) {
											$this->error['custom_field']['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)) {
											$this->error['custom_field']['im'] = 'A Inscrição Municipal deve ter entre 3 e 32 caracteres!';
										}
									}
								}
							}
						}
					}
				} else {
					$this->error['custom_field']['country'] = $this->language->get('error_country');
				}
			
		return !$this->error;
	}
}