<?php

function noCachePHP(): void {
    header("Expires: Tue, 01 Jul 2001 06:00:00 GMT");
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    header("Cache-Control: no-store, no-cache, must-revalidate");
    header("Cache-Control: post-check=0, pre-check=0", false);
    header("Pragma: no-cache");
}

function imagenposter(string $ruta_imagen, int $ancho, int $alto) {
    $imagenorigen = imagecreatefrompng($ruta_imagen);
    $escalado = imagescale($imagenorigen, $ancho, $alto);
    return $escalado;
}

function hexColorAllocate($im, string $hex) {
    $hex = ltrim($hex, '#');
    $r = hexdec(substr($hex, 0, 2));
    $g = hexdec(substr($hex, 2, 2));
    $b = hexdec(substr($hex, 4, 2));
    return imagecolorallocate($im, $r, $g, $b); 
}

function centrartexto(string $texto, string $fuente, $fondo, int $tamano_texto, string $color_letra, int $coordenada_x, int $coordenada_y, int $angulo) {
    $auxcolor = hexColorAllocate($fondo, $color_letra);
    $tb = imagettfbbox($tamano_texto, $angulo, $_SERVER['DOCUMENT_ROOT'] . "/fuentes/" . $fuente, $texto);
    $coord_x = ceil(($coordenada_x - $tb[2]) / 2); // lower left X coordinate for text
    imagettftext($fondo, $tamano_texto, $angulo, $coord_x, $coordenada_y, $auxcolor, $_SERVER['DOCUMENT_ROOT'] . "/fuentes/" . $fuente, $texto);
    return $fondo;
}


function centrartextolineas(string $texto, string $fuente, $fondo, int $tamano_texto, string $color_letra, int $coordenada_x, int $coordenada_y, int $angulo, int $ancho_maximo) {
    $auxcolor = hexColorAllocate($fondo, $color_letra);
    $fuente_ruta = $_SERVER['DOCUMENT_ROOT'] . "/fuentes/" . $fuente;
    
    // Divide el texto en palabras
    $palabras = explode(' ', $texto);
    $lineas = [];
    $linea_actual = '';
    
    // Crear líneas que se ajusten al ancho máximo dado
    foreach ($palabras as $palabra) {
        $tb = imagettfbbox($tamano_texto, $angulo, $fuente_ruta, $linea_actual . ' ' . $palabra);
        if ($tb[2] - $tb[0] <= $ancho_maximo) {
            $linea_actual .= ($linea_actual === '') ? $palabra : ' ' . $palabra;
        } else {
            $lineas[] = $linea_actual;
            $linea_actual = $palabra;
        }
    }
    if ($linea_actual !== '') {
        $lineas[] = $linea_actual;
    }
    
    // Altura de línea estimada para la fuente y el tamaño dados
    $line_height = abs($tb[7] - $tb[1]);
    
    // Renderiza cada línea de texto
    foreach ($lineas as $linea) {
        $tb = imagettfbbox($tamano_texto, $angulo, $fuente_ruta, $linea);
        $coord_x = ceil($coordenada_x - ($tb[2] - $tb[0]) / 2); // Coordenada X centrada para la línea actual
        imagettftext($fondo, $tamano_texto, $angulo, $coord_x, $coordenada_y, $auxcolor, $fuente_ruta, $linea);
        $coordenada_y += $line_height;
    }
    
    return $fondo;
}

function imagettfstroketext(string $text, string $fuente, &$image, int $size, &$textcolor, int $x, int $y, int $angle, &$strokecolor, int $px) {
    $fontfile = $_SERVER['DOCUMENT_ROOT'] . "/fuentes/" . $fuente;
    for ($c1 = ($x - abs($px)); $c1 <= ($x + abs($px)); $c1++) {
        for ($c2 = ($y - abs($px)); $c2 <= ($y + abs($px)); $c2++) {
            imagettftext($image, $size, $angle, $c1, $c2, $strokecolor, $fontfile, $text);
        }
    }
    return imagettftext($image, $size, $angle, $x, $y, $textcolor, $fontfile, $text);
}

function imagettfstroketextcentered(string $text, string $fuente, &$image, int $size, &$textcolor, int $x, int $y, int $angle, &$strokecolor, int $px) {
    $fontfile = $_SERVER['DOCUMENT_ROOT'] . "/fuentes/" . $fuente;

    // Calcular el bounding box del texto
    $tb = imagettfbbox($size, $angle, $fontfile, $text);
    $textWidth = abs($tb[4] - $tb[0]);
    $coord_x = ceil(($x - $textWidth) / 2);

    for ($c1 = ($coord_x - abs($px)); $c1 <= ($coord_x + abs($px)); $c1++) {
        for ($c2 = ($y - abs($px)); $c2 <= ($y + abs($px)); $c2++) {
            imagettftext($image, $size, $angle, $c1, $c2, $strokecolor, $fontfile, $text);
        }
    }
    return imagettftext($image, $size, $angle, $coord_x, $y, $textcolor, $fontfile, $text);
}

if (!function_exists('textWithLineBreaks')) {
    function textWithLineBreaks(
        string $text,
        int $size,
        int $angle,
        string $fontfile,
        int $maximumWidth,
        string $lineBreakCharacter = PHP_EOL
    ): string {
        // create an array with all the words
        $words = explode(' ', $text);

        // process all our words to generate $textWithLineBreaks
        $textWithLineBreaks = '';
        $currentLine = '';
        foreach ($words as $position => $word) {
            // place the first word into $currentLine without any processing (we
            // always want to include the first word on the first line--obviously)
            if ($position === 0) {
                $currentLine = $word;
            } else {
                // calculate the text's size if we were to add the word
                $textDimensions = imagettfbbox(
                    $size,
                    $angle,
                    $fontfile,
                    $currentLine . ' ' . $word
                );
                $textLeft = min($textDimensions[0], $textDimensions[6]);
                $textRight = max($textDimensions[2], $textDimensions[4]);
                $textWidth = $textRight - $textLeft;
                if ($textWidth > $maximumWidth) {
                    // the text is too wide with the added word so we add a line
                    // break then start a new line with only the added word
                    $textWithLineBreaks .= $currentLine;
                    $textWithLineBreaks .= $lineBreakCharacter;

                    $currentLine = $word;
                } else {
                    // we have space on the current line for the added word so we
                    // add a space then the word
                    $currentLine .= ' ';
                    $currentLine .= $word;
                }
            }
        }
        // the current line is still unadded to $textWithLineBreaks so we add it
        $textWithLineBreaks .= $currentLine;

        // return $text with line breaks added
        return $textWithLineBreaks;
    }
}

function eliminar_acentos(string $text): string {
    $text = htmlentities($text, ENT_QUOTES, 'UTF-8');
    $text = strtolower($text);
    $patron = array (
        '/[á]/' => 'a', '/[é]/' => 'e',
        '/[í]/' => 'i', '/[ó]/' => 'o',
        '/[ú]/' => 'u', '/[ñ]/' => 'n',
        '/[Á]/' => 'A', '/[É]/' => 'E',
        '/[Í]/' => 'I', '/[Ó]/' => 'O',
        '/[Ú]/' => 'U', '/[Ñ]/' => 'N',
    );
    $text = preg_replace(array_keys($patron), array_values($patron), $text);
    return $text;
}

    function nuevaimagen($imagen, string $ruta, int $ancho, int $alto, int $dest_x = 0, int $dest_y = 0) {
        // Reemplazar espacios en blanco en la URL por %20
        $ruta = str_replace(' ', '%20', $ruta);
        
        // Obtener la extensión del archivo
        $extension = strtolower(pathinfo($ruta, PATHINFO_EXTENSION));

        // Cargar la imagen original según la extensión
        switch ($extension) {
            case 'jpeg':
            case 'jpg':
                $origen = imagecreatefromjpeg($ruta);
                break;
            case 'png':
                $origen = imagecreatefrompng($ruta);
                break;
            case 'gif':
                $origen = imagecreatefromgif($ruta);
                break;
            default:
                throw new Exception("Formato de imagen no soportado: $extension");
        }

        // Verificar que la imagen se haya cargado correctamente
        if (!$origen) {
            throw new Exception("No se pudo cargar la imagen desde: $ruta");
        }

        // Copiar y redimensionar la imagen original
        imagecopyresized($imagen, $origen, $dest_x, $dest_y, 0, 0, $ancho, $alto, imagesx($origen), imagesy($origen));

        return $imagen;
    }


function izqtexto(string $texto, string $fuente, $fondo, int $tamano_texto, string $color_letra, int $coordenada_x, int $coordenada_y, int $angulo, int $ancho_maximo) {
    $auxcolor = hexColorAllocate($fondo, $color_letra);
    $fuente_ruta = $_SERVER['DOCUMENT_ROOT'] . "/fuentes/" . $fuente;
    
    // Divide el texto en palabras
    $palabras = explode(' ', $texto);
    $lineas = [];
    $linea_actual = '';
    
    // Crear líneas que se ajusten al ancho máximo dado
    foreach ($palabras as $palabra) {
        $tb = imagettfbbox($tamano_texto, $angulo, $fuente_ruta, $linea_actual . ' ' . $palabra);
        if ($tb[2] - $tb[0] <= $ancho_maximo) {
            $linea_actual .= ($linea_actual === '') ? $palabra : ' ' . $palabra;
        } else {
            $lineas[] = $linea_actual;
            $linea_actual = $palabra;
        }
    }
    if ($linea_actual !== '') {
        $lineas[] = $linea_actual;
    }
    
    // Altura de línea estimada para la fuente y el tamaño dados
    $line_height = abs($tb[7] - $tb[1]);
    
    // Renderiza cada línea de texto
    foreach ($lineas as $linea) {
        imagettftext($fondo, $tamano_texto, $angulo, $coordenada_x, $coordenada_y, $auxcolor, $fuente_ruta, $linea);
        $coordenada_y += $line_height;
    }
    
    return $fondo;
}


function CleanHTML($input) {
    // Reemplazar caracteres HTML
    $search = ['&oacute;', '&aacute;', '&eacute;', '&iacute;', '&uacute;', '&ntilde;', '&uuml;', '&nbsp;', '&quot;', '&amp;', '<br />'];
    $replace = ['ó', 'á', 'é', 'í', 'ú', 'ñ', 'ü', ' ', '"', '&', ' '];
    $output = str_replace($search, $replace, $input);

    // Eliminar etiquetas HTML
    $output = strip_tags($output);

    // Reemplazar saltos de línea
    $output = str_replace(["\r\n", "\n", "\r"], ' ', $output);

    // Eliminar espacios duplicados
    $output = preg_replace('/\s+/', ' ', $output);

    return $output;
}

function cleanProductName($input) {
    // Reemplazar frases específicas
    $search = ['PRECIO NETO', 'OFERTA', ' - ', '-', 'PRODUCCION NACIONAL'];
    $replace = ['', '', ' ', ' ', ''];
    $output = str_replace($search, $replace, $input);

    // Eliminar espacios al principio y al final
    $output = trim($output);

    return $output;
}

function identifyMaterials($input) {
    // Limpiar el HTML
    $cleaned_input = cleanHTML($input);
    $materials = [];

    // Identificar materiales
    $materialKeywords = [
        'metal' => 'Metal',
        'plástico' => 'Plástico',
        'silicona' => 'Silicona',
        'polipropileno' => 'Polipropileno',
        'poliestireno' => 'Poliestireno',
        'madera' => 'Madera',
        'cartón' => 'Cartón',
        'aluminio' => 'Aluminio'
    ];

    foreach ($materialKeywords as $keyword => $material) {
        if (stripos($cleaned_input, $keyword) !== false) {
            $materials[] = $material;
        }
    }

    return !empty($materials) ? implode(', ', $materials) : null;
}


function initCap($cadena) {
    $result = '';
    $words = explode(' ', $cadena);

    foreach ($words as $word) {
        if (strlen($word) < 4) {
            $result .= $word;
        } else {
            $result .= strtoupper(substr($word, 0, 1)) . substr($word, 1);
        }
        $result .= ' ';
    }

    // Quitar el espacio adicional al final
    return trim($result);
}
function removeTrailingComma($inputText) {
    // Verificar si el último carácter es una coma
    if (substr($inputText, -1) === ',') {
        // Eliminar la coma final
        return substr($inputText, 0, -1);
    } else {
        return $inputText;
    }
}


function TitleCase($cadena) {
    $result = '';
    $cadena = strtolower($cadena); // Convertir todo a minúsculas
    $words = explode(' ', $cadena);

    foreach ($words as $word) {
        if (strlen($word) < 4) {
            $result .= $word;
        } else {
            $result .= strtoupper(substr($word, 0, 1)) . substr($word, 1);
        }
        $result .= ' ';
    }

    // Quitar el espacio adicional al final
    return trim($result);
}


function limpiar_texto($inputText) {
    // Eliminar espacios finales
    $cleanedText = trim($inputText);

    // Eliminar puntos al inicio
    if (substr($cleanedText, 0, 1) === '.') {
        $cleanedText = substr($cleanedText, 1);
    }

    // Reemplazar tildes y otros caracteres específicos
    $search = ['á', 'é', 'í', 'ó', 'ú', 'ñ', 'N/R'];
    $replace = ['a', 'e', 'i', 'o', 'u', 'n', 'Unico'];
    $cleanedText = str_replace($search, $replace, $cleanedText);

    // Reemplazar dobles espacios por uno solo
    while (strpos($cleanedText, '  ') !== false) {
        $cleanedText = str_replace('  ', ' ', $cleanedText);
    }

    return $cleanedText;
}




?>
