<?php

class servicios_model
{
    private $conexion;

    public function __construct($conection)
    {
        $this->conexion = $conection;
    }

    public function count($filters)
    {
        $sql = " SELECT COUNT(*) AS total";
        $sql .= " FROM acl_servicios";
        $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, $filtrar = true)
    {
        $sql = " SELECT * ";
        $sql .= " FROM acl_servicios";
        $sql .= " WHERE 1=1 ";
        $params = [];
        $types = "";

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

        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_user)
    {
        $sql = "SELECT * FROM acl_servicios WHERE id = ?";

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

            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 id FROM acl_servicios 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']) ? (int)$resultSQL['id'] : 0;
        $stmt->close();

        return $lastId;  
    }


    
    public function get_servicios_options($includeTodos = true) {
        $tmp = $this->selectAll([], false, false);
        
        $result = [];

        if ($includeTodos) {
            $result = [
                [
                    'id'     => '',        // puedes usar -1 o cualquier valor que indique "todos"
                    'value1' => '',         // o null
                    'text'   => '[ Todos ]'
                ]
            ];
        }

        $index = 0;
        foreach($tmp as $item)
        {
            $result[] =
             [
                'id'     => $index,
                'value1' => $item['servicio'],
                'text'   => $item['nombre']
             ];
            $index++;
        }

        return $result;
    }



} // class
