<?php

class instalacion_controller
{
    private $instalacion_model;
    private $instalacion_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->instalacion_model  = $container->get('instalacion_model');
        $this->instalacion_view   = $container->get('instalacion_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'], "instalacion" );

        $filters = [];
        $filters['search']               = (isset($params['search']))             ? UtilParams::sanitizeString($params['search']) : '';
        $filters['filter_showEquipos']   = (isset($params['filter_showEquipos'])) ? UtilParams::sanitizeString($params['filter_showEquipos']) : 0;
        $filters['filter_instalador']    = (isset($params['filter_instalador']))  ? UtilParams::sanitizeString($params['filter_instalador']) : -1;
        $filters['filter_asp']           = $usuario['asp'];
//        $filters['filter_asp']           = -1;
        $filters['filter_instalaciones'] = $this->instalacion_model->get_instalaciones_array($usuario['id']);
        $filters = util_html_filter::getParams_pag ($params, $filters);
        $filters = util_html_filter::getParams_sort($params, $filters);        

        
        $action         = isset($params['action'])   ? UtilParams::sanitizeString($params['action']) : 'instalacion_showAll';
        $instalacion_id = isset($params['id_inst'])  ? UtilParams::sanitizeString($params['id_inst']) : '';

        // html        
        if      ( $action === 'instalacion_showAll' ) {return $this->showAllAction($filters); }      
        else if ( $action === 'instalacion_edit' )    {$this->editAction($instalacion_id); }        
        // json
        else if ( $action === 'instalacion_filter' )  {$this->filterAction($filters); }
        else if ( $action === 'instalacion_insert' )  {$this->insertAction(); }        
        else if ( $action === 'instalacion_update' )  {$this->updateAction($instalacion_id, $params); }        
        else if ( $action === 'instalacion_delete' )  {$this->deleteAction($instalacion_id); }        
    }

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

        $content = "";
        $content .= UtilRender::showHead( "Instalaciones" );
        $content .= "<div>";
        $content .= "<div id='instalacion_filter'>".$html_filter."</div>";
        $content .= "<hr>";
        $content .= "<div id='instalacion_table'>".$html_table."</div>";
        $content .= "<hr>";
        $content .= "<div id='instalacion_pag'>".$html_pag."</div>";
        $content .= "</div>";

        return $content;
    }

    private function editAction($instalacion_id)
    {
        $data = $this->instalacion_model->select($instalacion_id)[0];
        echo $this->instalacion_view->showId($data, $this->level, $this->asp);
        exit;
    }



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

        $html_table   = $this->instalacion_view->showAll       ($filters, $this->level, $this->asp, $data);
        $html_pag     = util_html_filter::showPaginacion($filters, $count, 'instalacion_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->instalacion_model->insert( "nueva instalacion" .rand() ) ;
            if ($newId) 
            {
                $this->instalacion_model->insert_acl_usuarios_instalaciones( $this->usuario['id'], $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($instalacion_id, $params)
    {
        try {

            $fields = [
                'ref_inst','nombre_inst','instalador','notas_inst',
                'email_inst','logo_cliente_inst','web_cliente','direccion',
                'localidad','provincia','pais','CP','Tlf','lat','lon','asp'
            ];

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

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

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

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


} // class
?>