<?php
$url_json = 'https://json.x7.com.ar/cotiz_json.php';

function obtener_json_remoto($url) {
    $respuesta = '';

    if (function_exists('curl_init')) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; cotiz_div/1.0)');
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $respuesta = curl_exec($ch);
        curl_close($ch);
    }

    if ($respuesta === false || $respuesta === '' || $respuesta === null) {
        if (ini_get('allow_url_fopen')) {
            $contexto = stream_context_create(array(
                'ssl' => array(
                    'verify_peer' => false,
                    'verify_peer_name' => false
                ),
                'http' => array(
                    'timeout' => 15,
                    'header' => "User-Agent: Mozilla/5.0\r\n"
                )
            ));
            $respuesta = @file_get_contents($url, false, $contexto);
        }
    }

    return $respuesta;
}

function esc($txt) {
    return htmlspecialchars((string)$txt, ENT_QUOTES, 'UTF-8');
}

function limpiar_texto($txt) {
    $txt = trim((string)$txt);
    $txt = strip_tags($txt);
    $txt = html_entity_decode($txt, ENT_QUOTES, 'UTF-8');
    $txt = preg_replace('/\s+/', ' ', $txt);
    return trim($txt);
}

function a_numero($valor) {
    $valor = limpiar_texto($valor);
    $valor = str_replace('$', '', $valor);
    $valor = str_replace(' ', '', $valor);
    $valor = preg_replace('/[^0-9,\.\-+]/', '', $valor);

    if ($valor === '' || $valor === '+' || $valor === '-') {
        return 0;
    }

    $lastComma = strrpos($valor, ',');
    $lastDot   = strrpos($valor, '.');

    if ($lastComma !== false && $lastDot !== false) {
        if ($lastComma > $lastDot) {
            $valor = str_replace('.', '', $valor);
            $valor = str_replace(',', '.', $valor);
        } else {
            $valor = str_replace(',', '', $valor);
        }
    } elseif ($lastComma !== false) {
        $partes = explode(',', $valor);
        $ultima = end($partes);

        if (strlen($ultima) == 2) {
            $valor = str_replace('.', '', $valor);
            $valor = str_replace(',', '.', $valor);
        } else {
            $valor = str_replace(',', '', $valor);
        }
    } elseif ($lastDot !== false) {
        $partes = explode('.', $valor);
        $ultima = end($partes);

        if (strlen($ultima) != 2) {
            $valor = str_replace('.', '', $valor);
        }
    }

    return floatval($valor);
}

function formatear_moneda($valor) {
    return '$ ' . number_format(a_numero($valor), 2, ',', '.');
}

function formatear_variacion_numero($numero) {
    $numero = floatval($numero);

    if ($numero == 0) {
        return 'Igual';
    }

    $signo = ($numero > 0) ? '+' : '-';
    return $signo . '$ ' . number_format(abs($numero), 2, ',', '.');
}

function variacion_info($txt) {
    $numero = a_numero($txt);

    if ($numero > 0) {
        return array(
            'class' => 'dolar-subio',
            'text'  => formatear_variacion_numero($numero)
        );
    }

    if ($numero < 0) {
        return array(
            'class' => 'dolar-bajo',
            'text'  => formatear_variacion_numero($numero)
        );
    }

    return array(
        'class' => 'dolar-igual',
        'text'  => 'Igual'
    );
}

function svg_icono_variacion($clase) {
    if ($clase === 'dolar-subio') {
        return '<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
                    <path fill="currentColor" d="M8 2l5 5H9.5v7h-3V7H3L8 2z"></path>
                </svg>';
    }

    if ($clase === 'dolar-bajo') {
        return '<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
                    <path fill="currentColor" d="M8 14l-5-5h3.5V2h3v7H13l-5 5z"></path>
                </svg>';
    }

    return '<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
                <path fill="currentColor" d="M3 8h10v2H3z"></path>
            </svg>';
}

function render_variacion($txt) {
    $v = variacion_info($txt);

    return '<div class="dolar-var-wrap">' .
                '<span class="dolar-var ' . esc($v['class']) . '">' .
                    '<span class="dolar-var-icon">' . svg_icono_variacion($v['class']) . '</span>' .
                    '<span class="dolar-var-text">' . esc($v['text']) . '</span>' .
                '</span>' .
           '</div>';
}

$json = obtener_json_remoto($url_json);
$data = json_decode($json, true);

$compra   = '$ 0,00';
$venta    = '$ 0,00';
$comprab  = '$ 0,00';
$ventab   = '$ 0,00';
$fecha    = '';
$up1      = '';
$up2      = '';
$up3      = '';
$up4      = '';
$error    = false;

if (is_array($data) && isset($data[0]) && is_array($data[0])) {
    $fila = $data[0];

    $compra   = isset($fila['compra'])  ? formatear_moneda($fila['compra'])  : $compra;
    $venta    = isset($fila['venta'])   ? formatear_moneda($fila['venta'])   : $venta;
    $comprab  = isset($fila['comprab']) ? formatear_moneda($fila['comprab']) : $comprab;
    $ventab   = isset($fila['ventab'])  ? formatear_moneda($fila['ventab'])  : $ventab;
    $fecha    = isset($fila['fecha'])   ? limpiar_texto($fila['fecha'])      : $fecha;
    $up1      = isset($fila['up1'])     ? $fila['up1']                       : $up1;
    $up2      = isset($fila['up2'])     ? $fila['up2']                       : $up2;
    $up3      = isset($fila['up3'])     ? $fila['up3']                       : $up3;
    $up4      = isset($fila['up4'])     ? $fila['up4']                       : $up4;
} else {
    $error = true;
}
?>

<article style="margin-bottom:20px;">
    <div class="base-box2">

        <div class="widget-head">
            <h3 class="widget-title"><span>DOLAR</span></h3>
        </div>

        <style>
            .dolar-widget-tabla{
                width:100%;
                border-collapse:collapse;
                table-layout:fixed;
                background:#fff;
                border:1px solid #d9d9d9;
                font-family:Arial, Helvetica, sans-serif;
            }

            .dolar-widget-tabla th{
                background:#f2f2f2;
                color:#2a2a2a;
                font-size:12px;
                font-weight:bold;
                text-transform:uppercase;
                letter-spacing:.3px;
                padding:11px 6px;
                border:1px solid #dddddd;
                text-align:center;
            }

            .dolar-widget-tabla td{
                background:linear-gradient(180deg,#ffffff 0%,#fafafa 100%);
                border:1px solid #e5e5e5;
                text-align:center;
                padding:14px 8px 12px 8px;
                vertical-align:middle;
            }

            .dolar-precio{
                font-size:18px;
                line-height:1.15;
                font-weight:bold;
                color:#222;
                margin-bottom:8px;
                letter-spacing:-0.2px;
            }

            .dolar-var-wrap{
                min-height:24px;
            }

            .dolar-var{
                display:inline-flex;
                align-items:center;
                justify-content:center;
                padding:4px 9px;
                border-radius:14px;
                font-size:11px;
                line-height:1.2;
                font-weight:bold;
                border:1px solid #ddd;
                white-space:nowrap;
            }

            .dolar-var-icon{
                display:inline-block;
                width:12px;
                height:12px;
                margin-right:4px;
                vertical-align:-1px;
            }

            .dolar-var-icon svg{
                display:block;
                width:12px;
                height:12px;
            }

            .dolar-bajo{
                background:#ebf8ef;
                color:#178344;
                border-color:#bfe3c9;
            }

            .dolar-subio{
                background:#fff0f0;
                color:#c53d3d;
                border-color:#edc0c0;
            }

            .dolar-igual{
                background:#f2f2f2;
                color:#666;
                border-color:#d8d8d8;
            }

            .dolar-actualizado{
                text-align:center;
                font-size:11px;
                color:#777;
                padding:8px 6px 2px 6px;
                font-family:Arial, Helvetica, sans-serif;
                text-transform:uppercase;
                letter-spacing:.4px;
            }

            .dolar-error{
                padding:14px 10px;
                text-align:center;
                color:#b42318;
                background:#fff6f6;
                border:1px solid #ead1d1;
                font-family:Arial, Helvetica, sans-serif;
                font-size:13px;
            }

            @media screen and (max-width:768px){
                .dolar-precio{
                    font-size:16px;
                }

                .dolar-widget-tabla th{
                    font-size:11px;
                    padding:9px 4px;
                }

                .dolar-widget-tabla td{
                    padding:11px 5px 10px 5px;
                }

                .dolar-var{
                    font-size:10px;
                    padding:4px 6px;
                }
            }
        </style>

        <?php if ($error) { ?>
            <div class="dolar-error">No se pudo cargar la cotización en este momento.</div>
        <?php } else { ?>

            <table class="dolar-widget-tabla">
                <tr>
                    <th>OFICIAL COMPRA</th>
                    <th>OFICIAL VENTA</th>
                </tr>
                <tr>
                    <td>
                        <div class="dolar-precio"><?php echo esc($compra); ?></div>
                        <?php echo render_variacion($up1); ?>
                    </td>
                    <td>
                        <div class="dolar-precio"><?php echo esc($venta); ?></div>
                        <?php echo render_variacion($up2); ?>
                    </td>
                </tr>

                <tr>
                    <th>BLUE COMPRA</th>
                    <th>BLUE VENTA</th>
                </tr>
                <tr>
                    <td>
                        <div class="dolar-precio"><?php echo esc($comprab); ?></div>
                        <?php echo render_variacion($up3); ?>
                    </td>
                    <td>
                        <div class="dolar-precio"><?php echo esc($ventab); ?></div>
                        <?php echo render_variacion($up4); ?>
                    </td>
                </tr>
            </table>

            <?php if ($fecha != '') { ?>
                <div class="dolar-actualizado">ACTUALIZADO: <?php echo esc($fecha); ?></div>
            <?php } ?>

        <?php } ?>

    </div>
</article>