<?php
require_once __DIR__ . "/global.php";

$conexion = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);

mysqli_query($conexion, 'SET NAMES "' . DB_ENCODE . '"');

//Si tenemos un posible error en la conexión lo mostramos
if (mysqli_connect_errno()) {
    printf("Falló conexión a la base de datos: %s\n", mysqli_connect_error());
    exit();
}

if (!function_exists('ejecutarConsulta')) {
    function ejecutarConsulta($sql)
    {
        global $conexion;
        $query = $conexion->query($sql);
        return $query;
    }

    function insertIntoTable($tableName, $fieldsArray)
    {
        global $conexion;
        // Prepare the statement with placeholders for all fields
        $placeholders = str_repeat('?,', count($fieldsArray) - 1) . '?';
        $stmt = $conexion->prepare("INSERT INTO $tableName (" . implode(',', array_keys($fieldsArray)) . ") VALUES ($placeholders)");
        $fieldValues = array_values($fieldsArray);
        $stmt->bind_param(str_repeat('s', count($fieldValues)), ...$fieldValues); // Use spread operator for concise reference passing
        // Execute the statement
        if (!$stmt->execute()) {
            $stmt->close();
            return "Error: " . $stmt->error;
        } else {
            $stmt->close();
            return "Exito!";
        }
    }

    function updateTableRow($tableName, $fieldsArray, $whereClause)
    {
        global $conexion;
        $set_clause = implode(" = ?, ", array_keys($fieldsArray)) . " = ?";
        $stmt = $conexion->prepare("UPDATE $tableName SET $set_clause WHERE $whereClause");
        $fieldValues = array_values($fieldsArray);
        $stmt->bind_param(str_repeat('s', count($fieldValues)), ...$fieldValues); // Include where clause for binding
        if (!$stmt->execute()) {
            $stmt->close();
            return "Error: " . $stmt->error;
        } else {
            $stmt->close();
            return "Exito!";
        }
    }

    function ejecutarConsultaSimpleFila($sql)
    {
        global $conexion;
        $query = $conexion->query($sql);
        $row = $query->fetch_assoc();
        return $row;
    }

    function ejecutarConsulta_retornarID($sql)
    {
        global $conexion;
        $query = $conexion->query($sql);
        return $conexion->insert_id;
    }

    function limpiarCadena($str)
    {
        global $conexion;
        $str = mysqli_real_escape_string($conexion, trim($str));
        return htmlspecialchars($str);
    }
}
