<?php

class Produto_CulturamunicipiossubvencaoController extends Agro_Controller_Action {

    public function indexAction() {
        $session = new Zend_Session_Namespace('cultura');

        if ($this->getRequest()->isPost()) {
            $this->save($this->getRequest()->getPost());
        }

        $this->view->estados = $this->getEstados();
        $this->view->checked = $this->getModel()->relacionados($this->getRequest()->getParam('id'));

        $this->view->id = $this->getRequest()->getParam('id');
        $this->view->title = "Produto » Cadastro » Culturas » Municípios Subvenção";
        $this->view->back = '/produto/cultura';
    }

    public function save(array $post) {

        try {
            $this->getModel()->save($post['municipios'],$this->getRequest()->getParam('id'));
            $this->view->showMessage(MSG_SUCCESS, 'success');
        } catch (Exception $e) {
            $this->view->showMessage(MSG_ERROR, 'error');
        }
    }

    private function getEstados() {
        $Estados = new Produto_Model_Estados();
        return $Estados->fetchAll("ds_nome_estado != 'NULO'", "ds_nome_estado");
    }

    public function getModel() {
        return new Produto_Model_CulturasMunicipiosSubvencao();
    }

    public function importamunicipiosAction() {
        $this->getHelper('layout')->disableLayout();
        $this->getHelper('ViewRenderer')->setNoRender();

        $result = array();
        $Adapter = new Zend_File_Transfer_Adapter_Http();
        $Adapter->setDestination(APPLICATION_PATH.'/upload_files/temp/');
        $file = $Adapter->getFileInfo();

        if(!$Adapter->receive($file['municipios_csv']['name'])) {
            $result['status'] = 'Erro ao importar municípios';
        } else {
            $extensao = explode('.',$file['municipios_csv']['name']);
            if($extensao['1'] == 'csv') {
                $arquivo = fopen(APPLICATION_PATH.'/upload_files/temp/' . $file['municipios_csv']['name'], 'r');
                while (($dados = fgetcsv($arquivo, 0, ';')) != false) {
                    array_push($result, $dados[0]);
                }
                array_shift($result);
                fclose($arquivo);

                if ($this->getModel()->save($result, $this->getRequest()->getParam('id'))) {
                    $message['status'] = "Importação efetuada com sucesso!";
                } else {
                    $message['status'] == "Somente são aceitos arquivos .csv!";
                }
            } else {
                $message['status'] = "Somente são aceitos arquivos .csv!";
            }
        }

        $this->getResponse()->setBody(Zend_Json::encode($message));
    }
}
