<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

include('simple_html_dom.php');

$servername = "186.31.136.130";
$username = "ndconsulta";
$password = "Nitro2021";
$dbname = "db_productos";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$getLinksQuery = "SELECT guia FROM pd_envia_envios WHERE estado = 0";
$result = $conn->query($getLinksQuery);

$totalLinks = $result->num_rows;
$currentLink = 0;

if ($totalLinks > 0) {
    while ($row = $result->fetch_assoc()) {
        $currentLink++;
        $url = 'http://200.69.100.66/OnLineRastreo/RastreoUSA/RastreoUSA?Guia='.$row['guia'].'#modal_rastrea' ;

        $html = file_get_html($url);

        // Assuming $html contains the HTML content

        // Load HTML
        $htmlDom = new simple_html_dom();
        $htmlDom->load($html);

        // Extracting $destinatario
        $destinatarioElement = $htmlDom->find('.col_datos_envio ul li strong', 4);
        $destinatario = $destinatarioElement ? $destinatarioElement->plaintext : '';

        // Extracting $estado_guia
        $estadoElement = $htmlDom->find('.cont_rastreo h3', 0);
        $estado_guia = $estadoElement ? $estadoElement->plaintext : '';
        // Encontrar el elemento que contiene la fecha de envío
        $fechaEnvioElement = $htmlDom->find('h5:contains("fecha de envío:") strong', 0);


// Obtener el texto de la fecha de envío
echo $fecha_envio = $fechaEnvioElement ? $fechaEnvioElement->plaintext : '';
        
        

        $guia_arribo_element = $htmlDom->find('.col_datos_envio ul li strong', 3);
        $guia_arribo = $guia_arribo_element ? $guia_arribo_element->plaintext : '';
       
        
       

        // Update the pd_envia_envios table
        $updateQuery = "UPDATE pd_envia_envios SET destinatario = '$destinatario', estadoguia = '$estado_guia', fecha_envio = '$fecha_envio', guia_arribo = '$guia_arribo' WHERE guia = '" . $row['guia'] . "'";
        if ($conn->query($updateQuery) === TRUE) {
            echo "Record updated successfully\n";

            // If $estado_guia is "ENTREGADO," update the estado column to 1
            if (strpos($estado_guia, 'ENTREGADA DIGITALIZADA') !== false) {
                $updateEstadoQuery = "UPDATE pd_envia_envios SET estado = 1 WHERE guia = '" . $row['guia'] . "'";
                $conn->query($updateEstadoQuery);
            }
        } else {
            echo "Error updating record: " . $conn->error . "\n";
        }

        // Clear memory
        $htmlDom->clear();
        unset($htmlDom);

        // Calcular y mostrar el porcentaje de progreso
        $percentage = ($currentLink / $totalLinks) * 100;
        echo "Progress: " . number_format($percentage, 2) . "%\n";
    }
} else {
    echo "No links found in pd_links table\n";
}

$conn->close();
?>
