<?php

class Seguro_ItensseguradoscarController extends Agro_Controller_Action
{
    const UPLOAD_PATH = APPLICATION_PATH.'/upload_files/documento_car_manual';

    public function listacarmanualAction()
	{
		$this->getHelper('layout')->disableLayout();

		$idProposta = $this->getRequest()->getParam('idProposta');

		try {
			if (empty($idProposta) || !filter_var($idProposta, FILTER_VALIDATE_INT)) {
				throw new Exception('ID proposta inválido.', 1);
			}

			$modelItemSeguradoCar = new Seguro_Model_ItensSeguradosCAR();
            $map = $modelItemSeguradoCar->mapItemSeguradoCarsByProposta($idProposta, true, true, 'nr_item_segurado');

            foreach ($map as $key => $cars) {
                if (!file_exists(self::UPLOAD_PATH. '/'. $cars[0]['ds_arquivo_car_manual'])) {
                    $map[$key][0]['ds_arquivo_car_manual'] = '';
                }
            }

			$this->view->map = json_encode($map);
            
		} catch (Exception $e) {
			$this->view->mensagemErro = $e->getCode() == 1 ? $e->getMessage() : 'Erro ao listar CARs manuais.';
		}
	}
    
    public function salvarcarmanualAction()
    {
        $this->isAjax();

        try {
            $numeroCar = $this->getRequest()->getParam('numeroCar');
            $idProposta = $this->getRequest()->getParam('idProposta');
            $numerosItens = $this->getRequest()->getParam('numerosItens');
            
            Agro_Db_Table_Abstract::getDefaultAdapter()->beginTransaction();

            if (empty($idProposta) || !filter_var($idProposta, FILTER_VALIDATE_INT)) {
                throw new Exception('ID proposta inválido.', 1);
            }

            if (empty($numerosItens)) {
                throw new Exception('Nenhum CAR selecionado.', 1);
            }

            if (!is_array($numerosItens)) {
                throw new Exception('Itens inválidos.', 1);
            }

            if (empty($_FILES)) {
                throw new Exception('Nenhum documento anexado.', 1);
            }

            $cars = (new Seguro_Service_SalvarCarManual())->executar(
                (int) $idProposta,
                Agro_Util::carUnmask($numeroCar),
                $numerosItens
            );
            
            Agro_Db_Table_Abstract::getDefaultAdapter()->commit();

            $retorno = [
                'erro' => false,
                'mapNumeroItemSeguradoToCar' => $cars,
                'mensagem' => 'Documentos anexados com sucesso.'
            ];
        } catch (Exception $e) {
            Agro_Db_Table_Abstract::getDefaultAdapter()->rollback();
            $retorno = [
                'erro' => true,
                'mensagem' => $e->getCode() == 1 ? $e->getMessage() : 'Erro ao salvar CAR manual.'
            ];
        }

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

    public function validacarsmanuaisAction()
    {
        $this->isAjax();
        
        try {
            $idProposta = $this->getRequest()->getParam('idProposta');
            $mapNumeroItemCar = $this->getRequest()->getParam('carsManuais') ?? [];

            if (empty($idProposta) || !filter_var($idProposta, FILTER_VALIDATE_INT)) {
                throw new Exception('ID proposta inválido.', 1);
            }

            if (empty($mapNumeroItemCar)) {
                 $retorno = [
                    'erro' => false,
                    'errosMapeadosPorNumeroItem' => []
                ];
            }

            $mapNumeroItemCar = array_map(function($car) {
                return Agro_Util::carUnmask($car);
            }, $mapNumeroItemCar);
            
            $errosMapeadosPorNumeroItem = (new Seguro_Service_ValidarCars())->executar($idProposta, $mapNumeroItemCar);

            $retorno = [
                'erro' => !empty($errosMapeadosPorNumeroItem),
                'errosMapeadosPorNumeroItem' => $errosMapeadosPorNumeroItem
            ];
        } catch (Exception $e) {
            $retorno = [
                'erro' => true,
                'mensagem' => $e->getCode() == 1 ? $e->getMessage() : 'Erro ao validar documentos vinculados.',
            ];
        }

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

    public function aprovarcarAction()
    {
        $this->isAjax();
        
        try {
            $params = $this->getRequest()->getParams();
            
            if (empty($params['idProposta']) || !filter_var($params['idProposta'], FILTER_VALIDATE_INT)) {
                throw new Exception('Proposta informada inválida.', 1);
            }

            if (empty($params['numeroItem']) || !filter_var($params['numeroItem'], FILTER_VALIDATE_INT)) {
                throw new Exception('Número item informado inválido.', 1);
            }
            
            $modelCar = new Seguro_Model_ItensSeguradosCAR();
            $map = $modelCar->mapItemSeguradoCarsByProposta(
                (int) $params['idProposta'],
                true,
                true,
                'nr_item_segurado'
            );
            
            if (!array_key_exists($params['numeroItem'], $map)) {
                throw new Exception('CAR não encontrado.', 1);
            }

            $modelCar->update([
                'fl_car_manual_aprovado' => true
            ], 'id = ' . $map[$params['numeroItem']][0]['id_car']);

            $retorno = [
                'erro' => false,
                'mensagem' => 'CAR aprovado com sucesso.'
            ];
        } catch(Exception $e) {
            $retorno = [
                'erro' => true,
                'mensagem' => $e->getCode() == 1 ? $e->getMessage() : 'Erro ao aprovar CAR.',
            ];
        }

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