/*
Theme Name: Phlox Pro Child
Template: phlox-pro
Author: InfoTech Nicaragua
Version: 1.0
*/

@import url("../phlox-pro/style.css");

function mostrar_tipo_cambio() {
    $dia = date('j');
    $mes = strtolower(date_i18n('F')); // Ej: "julio"

    $archivos = get_posts([
        'post_type' => 'attachment',
        'post_status' => 'inherit',
        'posts_per_page' => 1,
        'orderby' => 'date',
        'order' => 'DESC',
        'meta_query' => [
            [
                'key' => '_wp_attached_file',
                'value' => "tipo-cambio-$mes.csv",
                'compare' => 'LIKE',
            ],
        ],
    ]);

    if (!$archivos) {
        return '<span>No se encontró archivo de tipo de cambio.</span>';
    }

    $url = wp_get_attachment_url($archivos[0]->ID);
    $output = '<span id="tc-compra">Compra: C$ --</span> | <span id="tc-venta">Venta: C$ --</span>';

    ob_start();
    ?>
    <script>
    fetch("<?php echo esc_url($url); ?>")
      .then(response => response.text())
      .then(csv => {
        const lineas = csv.trim().split('\n');
        for (let i = 1; i < lineas.length; i++) {
          const fila = lineas[i].split(',');
          if (parseInt(fila[0]) === <?php echo intval($dia); ?>) {
            document.getElementById('tc-compra').innerText = `Compra: C$ ${fila[1]}`;
            document.getElementById('tc-venta').innerText = `Venta: C$ ${fila[2]}`;
            break;
          }
        }
      })
      .catch(err => console.error('Error cargando tipo de cambio:', err));
    </script>
    <?php
    $output .= ob_get_clean();
    return $output;
}
add_shortcode('tipo_cambio', 'mostrar_tipo_cambio');
