<?php

class instalador_controller
{
    private $instalador_model;
    private $instalador_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->instalador_model  = $container->get('instalador_model');
        $this->instalador_view   = $container->get('instalador_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'], "instalador" );

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

//        print_r($filters);
        
        $action         = isset($params['action']) ? UtilParams::sanitizeString($params['action']) : 'instalador_showAll';
        $instalador_id   = isset($params['id'])     ? UtilParams::sanitizeString($params['id']) : '';

        // html        
        if      ( $action === 'instalador_showAll' ) {return $this->showAllAction($filters); }      
        else if ( $action === 'instalador_edit' )    {$this->editAction($instalador_id); }        
        // json
        else if ( $action === 'instalador_filter' )  {$this->filterAction($filters); }
        else if ( $action === 'instalador_insert' )  {$this->insertAction(); }        
        else if ( $action === 'instalador_update' )  {$this->updateAction($instalador_id, $params); }        
        else if ( $action === 'instalador_delete' )  {$this->deleteAction($instalador_id); }        
    }

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

        $content = "";
        $content .= UtilRender::showHead("Instaladores");
        $content .= "<div>";
        $content .= "<div id='instalador_filter'>".$html_filter."</div>";
        $content .= "<hr>";
        $content .= "<div id='instalador_table'>".$html_table."</div>";
        $content .= "<hr>";
        $content .= "<div id='instalador_pag'>".$html_pag."</div>";
        $content .= "</div>";

        return $content;
    }

    private function editAction($instalador_id)
    {
        $data = $this->instalador_model->select($instalador_id)[0];
        echo $this->instalador_view->showId($data, $this->level);
        exit;
    }



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

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

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

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

    private function insertAction()
    {
        try
        {
            $lastId = $this->instalador_model->lastId() + 1;
            $this->instalador_model->insert( $lastId, "nuevo instalador" .rand() ) ;

                Util:: jsonResponse('success', SUCCESS_INSERT, ['lastId'=> $lastId]);  
        } 
        catch (Exception $e)
        {
            Util::jsonResponse('error', $e->getMessage() );                 
        }
    }



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

            $fields = [
                'nombre', 'asp'
            ];

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

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

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

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


} // class
?>