<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

include('simple_html_dom.php');
require $_SERVER['DOCUMENT_ROOT'] . '/vendor/autoload.php';
use Stichoza\GoogleTranslate\GoogleTranslate;

function ajustarFormatoHTML($html) {
    // Quitar espacios alrededor de las etiquetas span, li, h3, h4, ul, strong, header, p, main
    $html = preg_replace('/\s*<\s*(span|li|h3|h4|ul|strong|header|p|main)\s*(?:(?=\s)[^>]*)?>/', '<$1>', $html);
    $html = preg_replace('/<\s*\/\s*(span|li|h3|h4|ul|strong|header|p|main)\s*>\s*/', '</$1>', $html);
    
    // Eliminar las etiquetas <i> y su contenido
    $html = preg_replace('/<i[^>]*>.*?<\/i>/', '', $html);
    
    // Eliminar todas las comillas sencillas
    $html = str_replace("'", '', $html);

    // Cambiar </h3><h3> a </h4><h4>
    $html = str_replace('<h3>', '<h4>', $html);
    $html = str_replace('</h3>', '</h4>', $html);
    $html = str_replace('</header>', '', $html);
    $html = str_replace('<header>', '', $html);
    $html = str_replace('<i></i>', '', $html);
    $html = str_replace('<li></li>', '', $html);
    $html = str_replace('</main>', '', $html);
    $html = str_replace('<main>', '', $html);
    $html = str_replace('< intervalo>', '', $html);
    $html = str_replace('</ intervalo>', '', $html);
    $html = str_replace('<i class="icon--big-circle icon-custom--checklist-file"></i>', '', $html);
    $html = str_replace('<i class="icon--big-circle icon-custom--plug"></i>', '', $html);
    $html = str_replace('<div class="block description-section--50">', '', $html);
    $html = str_replace('<div class="clearfix"> <div class="bloque descripción-sección--50">', '', $html);
    $html = str_replace('</div>', '', $html);
    $html = str_replace('< /div>', '', $html);
    $html = str_replace('</div >', '', $html);
    $html = str_replace(' <', '<', $html);
    $html = str_replace('> ', '>', $html);
    $html = preg_replace('/<\/span><span>/', '</span>: <span>', $html);
    $html = str_replace('https: //', 'https://', $html);
    $html = str_replace('<div class="block descripción-section--50">', '', $html);
    $html = str_replace('<i class="icon--big-circle icon-custom--note-3"></i>', '', $html);
    $html = str_replace('<div class="clearfix"> <div class="bloque descripción-sección--50"> <i class="icon--big-circle icon-custom--full-package-trolley"></i>', '', $html);
    $html = str_replace('<div class="bloque descripción-sección--50"> <i class="icon--big-circle icon-custom--add-archive ">', '', $html);
    $html = str_replace('<i class="icon--big-circle icon-custom--settings"></i>', '', $html);

    return $html;
}

function translateAndFormat($html, $tr) {
    return $html !== null ? ajustarFormatoHTML($tr->translate($html)) : null;
}

$servername = "localhost";
$username = "ndconsulta";
$password = "Nitro2021";
$dbname = "db_tiendanitro";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$getLinksQuery = "SELECT id, link, descripcion, especificaciones, caracteristicas, compatibilidad, notas, packing, descripcion_larga, image1, image2, image3, image4, image5, image6, image7 FROM inv_fanatec_info";
$result = $conn->query($getLinksQuery);

if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $url = $row['link'];
        $html = @file_get_html($url);

        if ($html === false) {
            // URL no válida o error al obtener el HTML
            $activo = 0;
            $sqlUpdate = $conn->prepare("UPDATE inv_fanatec_info SET activo=? WHERE id=?");
            $sqlUpdate->bind_param("ii", $activo, $row['id']);
            $sqlUpdate->execute();
            continue;
        } else {
            // URL válida
            $activo = 1;

            // Extract SKU
            $sku = $html->find('meta[itemprop=sku]', 0)->content;

            // Extract title
            $title = $html->find('meta[property=og:title]', 0)->content;

            // Extract price
            $price = $html->find('meta[property=product:price]', 0)->content;

            // Extract text status
            $deliveryInformation = $html->find('p.delivery--information span.delivery--text', 0);
            $text_status = 'Estado desconocido';
            if ($deliveryInformation) {
                $statusText = trim($deliveryInformation->plaintext);
                if (strpos($statusText, 'Sold out') !== false) {
                    $text_status = 'Sold out';
                } elseif (strpos($statusText, 'Open for Pre-Orders') !== false) {
                    $text_status = 'Preventa';
                } elseif (strpos($statusText, 'Ready to ship') !== false) {
                    $text_status = 'Listo para enviar';
                } elseif (strpos($statusText, 'Ships within 4-7 days') !== false) {
                    $text_status = 'Envío en 4-7 días';
                }
            }

            // Extract images if not already available
            $imageSliderContainer = $html->find('.image-slider--container', 0);
            $images = [];
            if (empty($row['image1']) && $imageSliderContainer) {
                $sliderItems = $imageSliderContainer->find('.image-slider--item');
                foreach ($sliderItems as $index => $sliderItem) {
                    $largeImage = $sliderItem->find('.image--element', 0)->getAttribute('data-img-large');
                    $images[$index] = $largeImage;
                }
            }
            $imagen1 = $images[0] ?? $row['image1'];
            $imagen2 = $images[1] ?? $row['image2'];
            $imagen3 = $images[2] ?? $row['image3'];
            $imagen4 = $images[3] ?? $row['image4'];
            $imagen5 = $images[4] ?? $row['image5'];
            $imagen6 = $images[5] ?? $row['image6'];
            $imagen7 = $images[6] ?? $row['image7'];

            // Extract main image
            $imageElement = $html->find('meta[property=og:image]', 0);
            $imagen = $imageElement ? $imageElement->content : 'No se pudo determinar la imagen';

            // Initialize translator
            $tr = new GoogleTranslate();
            $tr->setSource('en');
            $tr->setTarget('es');

            // Extract and translate fields if they are empty
            $descripcion = !empty($row['descripcion']) ? $row['descripcion'] : translateAndFormat(($html->find('meta[name=description]', 0))->content ?? null, $tr);
            $especificaciones = !empty($row['especificaciones']) ? $row['especificaciones'] : translateAndFormat(($html->find('section.description-section--properties', 0))->innertext ?? null, $tr);
            $caracteristicas = !empty($row['caracteristicas']) ? $row['caracteristicas'] : translateAndFormat(($html->find('section.description-section--features', 0))->innertext ?? null, $tr);
            $compatibilidad = !empty($row['compatibilidad']) ? $row['compatibilidad'] : translateAndFormat(($html->find('section.description-section--compatibility', 0))->innertext ?? null, $tr);
            $notas = !empty($row['notas']) ? $row['notas'] : translateAndFormat(($html->find('section.description-section--specialnotes', 0))->innertext ?? null, $tr);
            $packing = !empty($row['packing']) ? $row['packing'] : translateAndFormat(($html->find('section.description-section--packaging', 0))->innertext ?? null, $tr);

            // Crear la descripción larga
            $descripcion_larga = $descripcion . '<br><br>Ficha Técnica:<br>' . $caracteristicas . '<br>' . $compatibilidad . '<br>' . $notas . '<br>' . $packing . '<br>' . $especificaciones;

            // Añadir texto de tiempo de entrega y enlace de más información
            $descripcion .= '<ul><li>Tiempo de entrega 15 días hábiles Incluye envio en Colombia</li><li>Somos distribuidores</li></ul>';
            $descripcion .= '<a href="' . $url . '" target="_blank">Mas información del producto aquí</a>';

            // Update inventory info
            $sqlUpdate = $conn->prepare("UPDATE inv_fanatec_info SET sku=?, title=?, price=?, text_status=?, image1=?, image2=?, image3=?, image4=?, image5=?, image6=?, image7=?, imagen_principal=?, packing=?, notas=?, descripcion=?, compatibilidad=?, caracteristicas=?, especificaciones=?, descripcion_larga=?, activo=? WHERE id=?");
            $sqlUpdate->bind_param("sssssssssssssssssssi", $sku, $title, $price, $text_status, $imagen1, $imagen2, $imagen3, $imagen4, $imagen5, $imagen6, $imagen7, $imagen, $packing, $notas, $descripcion, $compatibilidad, $caracteristicas, $especificaciones, $descripcion_larga, $activo, $row['id']);
            if ($sqlUpdate->execute()) {
                echo "Record updated successfully for URL: $url\n";
            } else {
                echo "Error: " . $sqlUpdate->error . "\n";
            }
        }
    }
} else {
    echo "No links found in inv_fanatec_info table\n";
}

$conn->close();
?>
