<?php

class Sistema_CorretorcomercialController extends Agro_Controller_Action
{
    public function deleteAction()
    {
        $this->isAjax();

        $retorno = ['erro' => false, 'mensagem' => 'Comercial excluído com sucesso.'];

        $adapter = Agro_Db_Table_Abstract::getDefaultAdapter();

        try {
            $adapter->beginTransaction();

            $this->getModel()->delete(
              $this->getRequest()->getParam('id_corretor'),
              $this->getRequest()->getParam('id_comercial')
            );

            $adapter->commit();
        } catch (Exception $erro) {
            $adapter->rollback();
            $retorno = ['erro' => true, 'mensagem' => 'Erro ao excluir o comercial.'];
        }

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

    public function getFilter()
    {
        $where = [];
        $where[] = array(
          'field'    => 'cc.id_corretor',
          'operator' => '=',
          'value'    => $this->getRequest()->getParam('id_corretor')
        );

        return $where;
    }

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

    public function saveAction()
    {
        $this->isAjax();
        $retorno = ['erro' => false, 'mensagem' => 'Comercial salvo com sucesso.'];
        $comercialAdicionado = false;

        $adapter = Agro_Db_Table_Abstract::getDefaultAdapter();

        try {
            $rowCorretorComercial = $this->getModel()->fetchRow([
              "id_corretor = {$this->getRequest()->getParam('corretor')}",
              "id_comercial = {$this->getRequest()->getParam('id_comercial')}",
            ]);

            if (!empty($rowCorretorComercial)) {
                $comercialAdicionado = true;
                $retorno = ['erro' => false, 'mensagem' => 'Comercial já adicionado.'];
            }

            if (!$comercialAdicionado) {

                $adapter->beginTransaction();

                $this->getModel()->save($this->getRequest()->getParams());

                $adapter->commit();
            }
        } catch (Exception $erro) {
            $adapter->rollback();
            $retorno = ['erro' => true, 'mensagem' => 'Erro ao salvar o comercial.'];
        }

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