<?php

class log_web_model
{
    private $conexion;
    
    public function __construct($conection)
    {
        $this->conexion = $conection;
    }
    
    public function count($filters)
    {
        $sql = " SELECT COUNT(*) AS total";
        $sql .= " FROM log_web";
        $sql .= " WHERE 1=1 ";
        $params = [];
        $types = "";

        $sql .= $this->build_filters($filters, $params, $types);

        try {
            $stmt = UtilSQL::executeQuery($this->conexion, $sql, $params, $types);

            $sqlResult = $stmt->get_result();
            $stmt->close();

            $fila = $sqlResult->fetch_assoc();
            return $fila['total'];
        } catch (Exception $e) {
            return "Error al obtener el total: " . $e->getMessage();
        }
    }


    //  le pasaremos $pag [], para exportar a excel, ya que queremos que nos devuelva
    // tota la tabla aplicando el filtro y el orden pero sin paginar.
    public function selectAll($filters, $paginar = true)
    {
        $sql = " SELECT * ";
        $sql .= " FROM log_web";
        $sql .= " WHERE 1=1 ";
        $params = [];
        $types = "";

        $sql .= $this->build_filters($filters, $params, $types);
        $sql .= UtilSQL::build_sort($filters);
        if ($paginar) {
             $sql .= UtilSQL::build_paginacion($filters, $params, $types); 
        }
//        Tools::debugTXT( $sql );

        try {
            $stmt = UtilSQL::executeQuery($this->conexion, $sql, $params, $types);

            $sqlResult = $stmt->get_result();
            $stmt->close();

            $result = [];
            while ($fila = $sqlResult->fetch_assoc()) {
                $result[] = $fila;
            }
            return $result;
        } catch (Exception $e) {
            return "Error al obtener los registros: " . $e->getMessage();
        }
    }



    public function select($id)
    {
        $sql = "SELECT * FROM log_web WHERE id = ?";

        try {
            $stmt = $this->conexion->prepare($sql);
            $stmt->bind_param("i", $id);

            if (!$stmt->execute()) {
                die('Error en la ejecución de la consulta SQL: ' . $stmt->error);
            }

            $sqlResult = $stmt->get_result();
            $stmt->close();

            $result = [];
            while ($fila = $sqlResult->fetch_assoc()) {
                $result[] = $fila;
            }
            return $result;
        } catch (mysqli_sql_exception $e) {
            error_log("Error en consulta SELECT: " . $e->getMessage()); // Guardar en log de errores
            return "Error al obtener el registro: " . $e->getMessage(); // Mensaje amigable para el usuario
        }
    }


    public function lastId()
    {
        $sql = "SELECT * FROM log_web ORDER BY id DESC LIMIT 1";
        $stmt = $this->conexion->prepare($sql);

        if (!$stmt->execute()) {
            die('Error en la ejecución de la consulta SQL: ' . $stmt->error);
        }

        $resultSQL = $stmt->get_result()->fetch_assoc();
        $lastId = isset($resultSQL['id_inst']) ? (int)$resultSQL['id_inst'] : 0;
        $stmt->close();

        return $lastId;  
    }

    private function build_filters($filters, &$params, &$types)
    {
        $sql = "";
        /*
        if ( isset($filters['search']) && ($filters['search'] != '') ) {
            $searchValue = $filters['search'];
            $sql .= " AND nombre_inst LIKE ?";
            $params[] = "%" . $searchValue . "%";
            $types .= "s";
        }

        if ( isset($filters['filter_instalaciones'])  ) {
            $sql .= " AND id_inst IN (" . implode(',', array_fill(0, count($filters['filter_instalaciones']), '?')) . ")";
            $params = array_merge($params, $filters['filter_instalaciones']);
            $types .= str_repeat('i', count($filters['filter_instalaciones'])); // si son enteros            
        }
        */        
//        echo $sql;
        return $sql;
    }

    public function insert($user, $page, $action, $params) {
        
        $sql = "INSERT INTO log_web (`user`, page, action, params) VALUES (?,?,?,?)";

        $stmt = $this->conexion->prepare($sql);

        if (!$stmt) {
            die('Error en la preparación de la consulta SQL: ' . $this->conexion->error);
        }

        $stmt->bind_param("ssss", $user, $page, $action, $params);

        if (!$stmt->execute()) {
            die('Error al ejecutar la consulta SQL: ' . $stmt->error);
        }

        $stmt->close();
        return true;
    }



} // class
