<?php

class PermisosController extends ApplicationController{

    public function initialize(){
        $this->setTemplateAfter(Session::get("layout"));
        $this->setPersistance(true);
    }

	public function indexAction(){
		$usuarios = $this->Usuarios->find();
		$this->setParamToView("usuarios",$usuarios);
        $this->setParamToView("title","Usuarios");
	}

	public function actulizaTablaAction(){
        try{
            $this->setResponse("ajax");
            $data = $this->Usuarios->find();
            $html = "";
            $html .= '<thead>';
            $html .= '<tr>';
            $html .= '<th>Documento</th>';
            $html .= '<th>Nombre</th>';
            $html .= '<th>Rol</th>';
            $html .= '<th>Area</th>';
            $html .= '<th>Estado</th>';
            $html .= '</tr>';
            $html .= '</thead>';
            $html .= '<tbody>';
            foreach($data as $reg){
                $html .= "<tr data-toggle=\"popover\" data-placement=\"top\" data-content=\"<button type='button' class='btn btn-primary' onclick='editar({$reg->getDocumento()})'>Editar</button>&nbsp;<button type='button' class='btn btn-danger' onclick='borrar({$reg->getDocumento()})'>Borrar</button>\" style='cursor: pointer;'>";
                $html .= "<td>{$reg->getDocumento()}</td>";
                $html .= "<td>".$reg->getPriape()." ".$reg->getSegape()." ".$reg->getPrinom()." ".$reg->getSegnom()."</td>";
                $html .= "<td>{$reg->getTipoUsuarioD()}</td>";
                $html .= "<td>{$reg->getAreaD()}</td>";
                $html .= "<td>{$reg->getEstadoDetalle()}</td>";
                $html .= "</tr>";
            }
            $html .= '</tbody>';
            $response["flag"] = true;
            $response["data"] = $html;
        }catch(DbException $e){
            $response["flag"] = false;
            $response["msg"] = "Error inesperado";
        }
        $this->renderText($this->jsonEncode($response));
    }

	public function nuevoAction(){
        try{
            $this->setResponse("ajax");
            $response["flag"] = true;
        }catch(DbException $e){
            $response["flag"] = false;
            $response["msg"] = "Error inesperado";
        }
        $this->renderText($this->jsonEncode($response));
    }

	public function guardarAction(){
        try{
            try{
                $this->setResponse("ajax");
                $transaction = TransactionManager::getUserTransaction();
                $this->Usuarios->setTransaction($transaction);
                $documento = $this->getPostParam("documento","striptags","extraspaces","addslaches");
                $tipo = $this->getPostParam("tipo_usuario_id","striptags","extraspaces","addslaches","alpha");
                $priape = $this->getPostParam("priape","striptags","extraspaces","addslaches","alpha");
                $prinom = $this->getPostParam("prinom","striptags","extraspaces","addslaches","alpha");
                $ciudad = $this->getPostParam("ciudad","striptags","extraspaces","addslaches","alpha");
                $celular = $this->getPostParam("celular","striptags","extraspaces","addslaches","alpha");
                $estado = $this->getPostParam("estado","striptags","extraspaces","addslaches","alpha");
                $area = $this->getPostParam("id_area","striptags","extraspaces","addslaches","alpha");
                $clave = $this->getPostParam("clave","striptags","extraspaces","addslaches","alpha");
                $usuarios = $this->Usuarios->findFirst("documento = '$documento'");
                if($usuarios == FALSE){
                    $usuarios = new Usuarios();
                    $date = New Date();
                }
                $usuarios->setTransaction($transaction);
                $usuarios->setTipoUsuarioId($tipo);
                $usuarios->setPriape($priape);
                $usuarios->setPrinom($prinom);
                $usuarios->setCiudad($ciudad);
                $usuarios->setCelular($celular);
                if($clave!=""){
                    $usuarios->setClave(sha1($clave));
                }
                $usuarios->setEstado($estado);
                $usuarios->setIdArea($area);
                if(!$usuarios->save()){
                    foreach($usuarios->getMessages() as $msg){
                        $this->setLogger($msg->getMessage());
                    }
                    $transaction->rollback();
                }
                $this->Usuarios->updateAll("tipo_usuario_id='{$tipo}'","conditions:  documento='{$documento}'");
                $transaction->commit();
                $response["flag"] = true;
                $response["msg"] = 'Registro guardado satisfactoriamente.';
            }catch(DbException $e){
                $this->setLogger($e->getMessage());
                $response["flag"] = false;
                $response["msg"] = 'Registro no pudo ser guardado.';
            }
        }catch(TransactionFailed $tf){
            $response["flag"] = false;
            $response["msg"] = 'Registro no pudo ser guardado.';
        }
        $this->renderText($this->jsonEncode($response));
    }

	public function editarAction(){
        try{
		    $this->setResponse("ajax");
            $documento = $this->getPostParam("documento");
            $usuarios = $this->Usuarios->findFirst("documento = '$documento'");
            if($usuarios != FALSE){
                $response["flag"] = true;
                $response["data"] = $usuarios->getArray();
            }else{
                $response["flag"] = false;
                $response["data"] = "Error inesperado";
            }
        }catch(DbException $e){
            $this->setLogger($e->getMessages());
            $response["flag"] = false;
            $response["msg"] = "Error inesperado";
        }
        $this->renderText($this->jsonEncode($response));
    }

	public function borrarAction(){
        try{
            try{
                $this->setResponse("ajax");
                $documento = $this->getPostParam("documento");
                $transaction = TransactionManager::getUserTransaction();
                $this->Usuarios->setTransaction($transaction);
                if(!$this->Usuarios->delete("documento = '$documento'")){
                    foreach($this->usuarios->getMessages() as $msg){
                        $this->setLogger($msg->getMessage());
                    }
                    $transaction->rollback();
                }
                $response["flag"] = true;
                $response["msg"] = 'Registro borrado satisfactoriamente.';
                $transaction->commit();
            }catch(DbException $e){
                $this->setLogger($e->getMessage());
                if($e->getCode()==1451){
                    $response["flag"] = false;
                    $response["msg"] = 'El registro se encuentra referenciado, no puede ser borrado.';
                }else{
                    $response["flag"] = false;
                    $response["msg"] = 'El registro no puede ser borrado.';
                }
            }
        }catch(TransactionFailed $tf){
            $response["flag"] = false;
            $response["msg"] = 'El registro no puede ser borrado.';
        }
        $this->renderText($this->jsonEncode($response));
    }

	public function getUniqueDocumentoAction(){
		$this->setResponse("ajax");
		$documento = $this->getPostParam("documento");
		$res = $this->Usuarios->findFirst("documento = '$documento'");
		$this->renderText($this->jsonEncode(array("flag"=>$res)));
	}

	public function getUniqueLoginAction(){
		$this->setResponse("ajax");
		$login = $this->getPostParam("login");
		$res = $this->Usuarios->findFirst("login = '$login'");
		$this->renderText($this->jsonEncode(array("flag"=>$res)));
	}

}
