<?php

class languages_model
{
    private $conexion;
    
    public function __construct($conexion)
    {
        $this->conexion = $conexion;
    }
    
    public function count($filters)
    {
        $sql = " SELECT COUNT(*) AS total";
        $sql .= " FROM languages";
        $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();
        }
    }


    public function selectAll($filters, $paginar = true, $filtrar =true)
    {
        $sql = " SELECT * ";
        $sql .= " FROM languages";
        $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); 
        }

//        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 languages 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 get_token($token)
    {
        $sql = "SELECT * FROM languages WHERE LOWER(token) = LOWER(?)";

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

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

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


            $result = $sqlResult->fetch_assoc();

            // Si no hay resultados, fetch_assoc devuelve null → devolvemos []
            return $result;

            /*
            $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 insert($token) {
        
        $sql = "INSERT INTO languages (token) VALUES (?)";

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

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

        $stmt->bind_param("s", $token);

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

        // obtiene el ultimo valor autoincrementado
        $newId = $this->conexion->insert_id;

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


    public function delete($id) {
        
        $sql = "DELETE FROM languages WHERE id = ? ";
        $stmt = $this->conexion->prepare($sql);

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

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

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

    public function update($id, $data) {
        
        $sql = "UPDATE languages SET 
                servicio = ?, 
                token = ?, 
                es = ?, 
                en = ? 
            WHERE id = ?";

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

        $stmt->bind_param(
            "ssssi",            
            $data['servicio'],
            $data['token'],
            $data['es'],
            $data['en'],
            $id
        );        
        if (!$stmt->execute()) {
            die('Error al ejecutar la consulta SQL: ' . $stmt->error);
        }

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


    private function build_filters($filters, &$params, &$types)
    {
        $sql = "";

        if ( isset($filters['search']) && ($filters['search'] != '') ) {
            $searchValue = $filters['search'];
            $sql .= " AND token LIKE ?";
            $params[] = "%" . $searchValue . "%";
            $types .= "s";
        }

        if ( isset($filters['filter_servicio']) && $filters['filter_servicio'] != '' ) {
            $sql .= " AND servicio = ? ";
            $params[] = $filters['filter_servicio'];
            $types .= "s";
        }

        return $sql;
    }


} // class
