<?php

class Sistema_CepController extends Agro_Controller_Action {
	public $_columnList = null;

	public function init() {
		$this->view->title = "Sistema » CEP's » Cep's";
	}

	public function setBack() {
		$this->view->back = '/sistema/cep';
	}

	public function getForm() {
		return new Sistema_Form_Cep();
	}

	public function getModel() {
		return new Sistema_Model_Ceps();
	}

	public function getFilter() {
		$where = array();

		if ($this->getRequest()->getParam('ds_nome_logradouro')) {
			$where[] = array(
				'field' => 'ds_nome_logradouro',
				'operator' => 'ilike',
				'value' => '%'.$this->getRequest()->getParam('ds_nome_logradouro').'%'
			);
		}

		if ($this->getRequest()->getParam('id_bairro')) {
			$where[] = array(
				'field' => 'id_bairro',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('id_bairro')
			);
		}

		if ($this->getRequest()->getParam('id_estado')) {
			$where[] = array(
				'field' => 'id_estado',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('id_estado')
			);
		}

		if ($this->getRequest()->getParam('id_municipio')) {
			$where[] = array(
				'field' => 'm.id',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('id_municipio')
			);
		}

		if ($this->getRequest()->getParam('nr_cep')) {
		    $nr_cep = str_replace("-", "", $this->getRequest()->getParam('nr_cep'));
			$where[] = array(
				'field' => 'nr_cep',
				'operator' => '=',
				'value' => $nr_cep
			);
		}

		return $where;
	}

	public function formAction()
    {
        $parametros = $this->getRequest()->getParams();
        $dadosCepOrganizados = [];

        if (!empty($parametros)) {
            $dadosCep = explode('&', $parametros['dadoscep']);

            foreach ($dadosCep as $dados) {
                $array = explode('=', $dados);
                $dadosCepOrganizados = array_merge($dadosCepOrganizados, [$array[0] => $array[1]]);
            }
        }

        if (!empty($dadosCepOrganizados['id']) || isset($parametros['salvar'])) {
            parent::formAction();
        } else {
            $this->setBack();
            $this->view->form = $this->getForm();
            $this->view->form->populate($dadosCepOrganizados);
        }
    }
}
