<?php

class languages_controller
{
    private $languages_model;
    private $languages_view;
    private $usuarios_model;

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


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

    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'], "languages" );

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

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

        // html        
        if      ( $action === 'languages_showAll' ) {return $this->showAllAction($filters); }      
        else if ( $action === 'languages_edit' )    {$this->editAction($languages_id); }        
        // json
        else if ( $action === 'languages_filter' )  {$this->filterAction($filters); }
        else if ( $action === 'languages_insert' )  {$this->insertAction(); }        
        else if ( $action === 'languages_update' )  {$this->updateAction($languages_id, $params); }        
        else if ( $action === 'languages_delete' )  {$this->deleteAction($languages_id); }        
    }

    ///   ACCIONES HTML    ///
    private function showAllAction($filters)
    {
        $count        = $this->languages_model->count($filters, false);
        $data         = $this->languages_model->selectAll($filters);
        
        $html_filter  = $this->languages_view->showFilter    ($filters );
        $html_table   = $this->languages_view->showAll       ($filters, $data, $this->level);
        $html_pag     = util_html_filter::showPaginacion($filters, $count, 'languages_showAll');
        $html_pag     = "";

        $content = "";
        $content .= UtilRender::showHead("Languages");
        $content .= "<div>";
        $content .= "<div id='languages_filter'>".$html_filter."</div>";
        $content .= "<hr>";
        $content .= "<div id='languages_table'>".$html_table."</div>";
        $content .= "<hr>";
        $content .= "<div id='languages_pag'>".$html_pag."</div>";
        $content .= "</div>";

        return $content;
    }

    private function editAction($languages_id)
    {
        $data = $this->languages_model->select($languages_id)[0];
        echo $this->languages_view->showId($data, $this->level);
        exit;
    }



    ///   ACCIONES AJAX    ///
    // devuelve json, con tabla + paginacion
    public function filterAction($filters)
    {
        $count   = $this->languages_model->count($filters, false);
        $data    = $this->languages_model->selectAll($filters);

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

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

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

    private function insertAction()
    {
        try
        {
            $newId = $this->languages_model->insert( "nuevo token" .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($languages_id, $params)
    {
        try {

            $fields = [
                'servicio', 'token', 'es', 'en'
            ];

            $data = [];
            foreach ($fields as $field) {
                $data[$field] = isset($params[$field]) ? UtilParams::sanitizeString($params[$field]) : '';
            }

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

            $updated = $this->languages_model->update($languages_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($languages_id)
    {
      try {
            if (empty($languages_id)) { throw new Exception('Datos incompletos');  }

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


} // class
?>