<?php

class usuarios_controller
{
    private $usuarios_model;
    private $usuarios_view;

    private $usuario;   // datos de usuario menos la pass
    private $level;     // level de servicio
    private $asp;       // asp
    private $language;  // language


    public function __construct($container) 
    {
        $this->usuarios_model = $container->get('usuarios_model');
        $this->usuarios_view  = $container->get('usuarios_view');
    }

    public function checkAction($usuario, $params) 
    {
        $this->usuario  = $usuario;
        $this->asp      = $usuario['asp'];
        $this->language = $usuario['language'];
        $this->level    = $this->usuarios_model->get_level_servicio( $usuario['id'], "usuarios" );

        $filters = [];
        $filters['search']          = (isset($params['search'])) ? UtilParams::sanitizeString($params['search']) : '';
        $filters['filter_asp']      = $usuario['asp'];
        $filters = util_html_filter::getParams_pag ($params,$filters);
        $filters = util_html_filter::getParams_sort($params, $filters);        


        $action     = isset($params['action'])   ? UtilParams::sanitizeString($params['action']) : 'usuarios_showAll';
        $usuario_id = isset($params['id'])       ? UtilParams::sanitizeString($params['id']) : '';

        // html        
        if      ( $action === 'usuarios_showAll' ) {return $this->showAllAction($filters); }      
        else if ( $action === 'usuarios_edit' )    {$this->editAction($usuario_id); }        
        // json
        else if ( $action === 'usuarios_filter' )  {$this->filterAction($filters); }
        else if ( $action === 'usuarios_insert' )  {$this->insertAction(); }        
        else if ( $action === 'usuarios_update' )  {$this->updateAction($usuario_id, $params); }        
        else if ( $action === 'usuarios_delete' )  {$this->deleteAction($usuario_id); }        
    }


    // Actions html
    private function showAllAction($filters)
    {
        $count        = $this->usuarios_model->count($filters, false);
        $data         = $this->usuarios_model->selectAll($filters);
        
        $html_filter  = $this->usuarios_view->showFilter    ($filters );
        $html_table   = $this->usuarios_view->showAll       ($filters, $data, $this->level);
        $html_pag     = util_html_filter::showPaginacion($filters, $count, 'usuarios_showAll');
        $html_pag     = "";

        $content = "";
        $content .= UtilRender::showHead( "Usuarios" );
        $content .= "<div>";
        $content .= "<div id='usuarios_filter'>".$html_filter."</div>";
        $content .= "<hr>";
        $content .= "<div id='usuarios_table'>".$html_table."</div>";
        $content .= "<hr>";
        $content .= "<div id='usuarios_pag'>".$html_pag."</div>";
        $content .= "</div>";

        return $content;
    }

    private function editAction($usuario_id)
    {
        $data = $this->usuarios_model->select($usuario_id)[0];
        echo $this->usuarios_view->showId($data);
        exit;
    }

    ///   ACCIONES AJAX    ///
    public function filterAction($filters)
    {
        $count   = $this->usuarios_model->count($filters, false);
        $data    = $this->usuarios_model->selectAll($filters);

        $html_table   = $this->usuarios_view->showAll       ($filters, $data, $this->level);
        $html_pag     = util_html_filter::showPaginacion($filters, $count, 'usuarios_showAll');

        $response = [
            'table'      => $html_table,
            'pagination' => $html_pag,
            'totalRecords' => $count
        ];

        header('Content-Type: application/json');
        echo json_encode($response);
        exit;
  }

    // Actions ajax
    private function insertAction()
    {
        try
        {
            $newId = $this->usuarios_model->insert( "new usuario". rand()) ;
            if ($newId) 
            {
                Util:: jsonResponse('success', SUCCESS_INSERT, ['lastId'=> $newId]);  
             }
            else          
            { 
                Util:: jsonResponse('error', ERROR_INSERT);                        
            }
        } 
        catch (Exception $e)
        {
            Util::jsonResponse('error', $e->getMessage() );                 
        }
    }




    private function updateAction($usuario_id, $params)
    {
        try {

            $fields = [
                'user',
                'pass',
                'email',
                'level',
                'remember_token',
                'comentario',
                'language',
                'asp'
            ];

            $data = [];
            $data['user']           = isset($params['user']) ? UtilParams::sanitizeString($params['user']) : '';
            $data['pass']           = isset($params['pass']) ? UtilParams::sanitizeString($params['pass']) : '';
            $data['email']          = isset($params['email']) ? UtilParams::sanitizeString($params['email']) : '';
            $data['level']          = isset($params['level']) ? UtilParams::sanitizeString($params['level']) : '';
            $data['remember_token'] = isset($params['remember_token']) ? UtilParams::sanitizeString($params['remember_token']) : '';
            $data['comentario']     = isset($params['comentario']) ? UtilParams::sanitizeString($params['comentario']) : '';
            $data['language']       = isset($params['language']) ? UtilParams::sanitizeString($params['language']) : '';
            $data['asp']            = isset($params['asp']) ? UtilParams::sanitizeString($params['asp']) : '';


            // validacion minima
            if (empty($usuario_id) ) {
                throw new Exception('Datos incompletos');
            }

            $updated = $this->usuarios_model->update($usuario_id, $data );
    
    
            if ($updated)
            {
                Util:: jsonResponse('success', SUCCESS_UPDATE, []);  
            }
            else
            {
               Util:: jsonResponse('error', ERROR_UPDATE);
            }
        } 
        catch (Exception $e) {
            Util::jsonResponse('error', $e->getMessage() );
        }
            
    }

    private function deleteAction($usuario_id) {
      try {
            if (empty($usuario_id)) { throw new Exception('Datos incompletos');  }

            $success = $this->usuarios_model->delete($usuario_id);
            if ($success)
             { Util:: jsonResponse('success', SUCCESS_DELETE);  }
            else 
             { Util:: jsonResponse('error', ERROR_DELETE); }
        } 
        catch (Exception $e) {
            Util::jsonResponse('error', $e->getMessage() );
        }        
    }


} // class
?>