{% extends "base.html" %}
{% block title %}JA4 SOC — Trafic HTTP{% endblock %}
{% block page_title %}
    Trafic HTTP
    <span class="relative inline-block ml-1"><button onclick="docToggle(this)" class="doc-btn">ⓘ</button><div class="doc-panel">
        <h4>Logs HTTP bruts</h4>
        <p>Toutes les requêtes HTTP capturées (24h). Filtrez par méthode, host ou status pour identifier les patterns suspects.</p>
        <p><strong>Workflow :</strong> Filtrez POST → cherchez du brute-force → cliquez sur l'IP → investiguez.</p>
        <p><strong>Codes couleur :</strong> GET=vert, POST=bleu, PUT=jaune, DELETE=rouge. Status : 2xx=vert, 3xx=jaune, 4xx=orange, 5xx=rouge.</p>
        <p class="doc-source">Source : http_logs (24h)</p>
    </div></span>
{% endblock %}
{% block content %}
<div class="space-y-4">
    <!-- Traffic summary charts -->
    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
        <div class="section-card">
            <div class="section-header"><span class="section-title">Méthodes HTTP
                <span class="relative inline-block"><button onclick="docToggle(this)" class="doc-btn">ⓘ</button><div class="doc-panel">
                    <h4>Distribution des méthodes</h4>
                    <p>Ratio des méthodes HTTP. Un ratio POST anormalement élevé peut indiquer du brute-force ou du credential stuffing.</p>
                    <p class="doc-source">Source : http_logs (24h)</p>
                </div></span>
            </span></div>
            <div class="section-body"><div id="method-chart" style="height:160px"></div></div>
        </div>
        <div class="section-card">
            <div class="section-header"><span class="section-title">Top User-Agents
                <span class="relative inline-block"><button onclick="docToggle(this)" class="doc-btn">ⓘ</button><div class="doc-panel">
                    <h4>User-Agents les plus fréquents</h4>
                    <p>Les bots utilisent souvent des UAs génériques (python-requests, curl) ou vides. Un UA massivement représenté = potentiel botnet.</p>
                    <p class="doc-source">Source : http_logs (24h)</p>
                </div></span>
            </span></div>
            <div class="section-body"><div id="ua-chart" style="height:160px"></div></div>
        </div>
        <div class="section-card">
            <div class="section-header"><span class="section-title">Top Paths
                <span class="relative inline-block"><button onclick="docToggle(this)" class="doc-btn">ⓘ</button><div class="doc-panel">
                    <h4>Chemins les plus accédés</h4>
                    <p>Les paths comme /wp-admin, /xmlrpc.php, /.env indiquent du scanning. Un path API martelé = possible DDoS L7.</p>
                    <p class="doc-source">Source : http_logs (24h)</p>
                </div></span>
            </span></div>
            <div class="section-body"><div id="path-chart" style="height:160px"></div></div>
        </div>
    </div>
    <div class="flex items-center gap-3 flex-wrap">
        <select id="method-filter" class="px-2 py-1 bg-gray-800 border border-gray-700 rounded text-sm text-gray-300">
            <option value="">Toutes méthodes</option>
            <option>GET</option><option>POST</option><option>PUT</option><option>DELETE</option><option>HEAD</option><option>OPTIONS</option>
        </select>
        <input type="text" id="host-filter" placeholder="Filtrer host..." class="px-3 py-1.5 bg-gray-800 border border-gray-700 rounded-lg text-sm text-gray-300 w-48 focus:border-brand-500 focus:outline-none">
        <input type="text" id="search-filter" placeholder="Rechercher IP, path, UA…" class="px-3 py-1.5 bg-gray-800 border border-gray-700 rounded-lg text-sm text-gray-300 w-64 focus:border-brand-500 focus:outline-none">
    </div>
    <div class="section-card overflow-hidden">
        <div class="overflow-x-auto max-h-[70vh] overflow-y-auto">
            <table class="data-table"><thead><tr>
                <th class="cursor-pointer" data-sort="time">Time ↕</th>
                <th>IP</th><th>Method</th><th>Host</th><th>Path</th>
                <th>HTTP</th><th>User-Agent</th><th>JA4</th><th>Pays</th>
            </tr></thead><tbody id="traffic-body"></tbody></table>
        </div>
        <div class="flex items-center justify-between px-4 py-3 border-t border-gray-800">
            <span class="text-xs text-gray-500" id="traffic-info">—</span>
            <div class="flex gap-2">
                <button id="prev-btn" class="px-3 py-1 bg-gray-800 rounded text-sm text-gray-400 hover:text-white disabled:opacity-30">&larr;</button>
                <button id="next-btn" class="px-3 py-1 bg-gray-800 rounded text-sm text-gray-400 hover:text-white disabled:opacity-30">&rarr;</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}
{% block scripts %}
<script>
let tPage=1, tSort='time', tOrder='DESC';
const sc = s => s>=500?'text-red-400':s>=400?'text-orange-400':s>=300?'text-yellow-400':'text-green-400';
const mc = m => ({GET:'text-green-400',POST:'text-blue-400',PUT:'text-yellow-400',DELETE:'text-red-400'}[m]||'text-gray-400');

async function loadTraffic() {
    const params = new URLSearchParams({page:tPage,per_page:100,sort:tSort,order:tOrder});
    const m=document.getElementById('method-filter').value;
    const h=document.getElementById('host-filter').value;
    const q=document.getElementById('search-filter').value;
    if(m) params.set('method',m); if(h) params.set('host',h); if(q) params.set('search',q);
    try {
        const r = await fetch('/api/traffic?'+params); const d = await r.json();
        const tbody = document.getElementById('traffic-body');
        tbody.innerHTML = (d.data||[]).map(row => `<tr onclick="window.location='/ip/'+encodeURIComponent('${escapeHtml(row.src_ip||'')}')">
            <td class="text-xs whitespace-nowrap">${row.time||''}</td>
            <td class="whitespace-nowrap">${fmtIP(row.src_ip)}</td>
            <td class="${mc(row.method)} font-mono text-xs">${row.method||''}</td>
            <td class="text-xs max-w-[150px] truncate">${escapeHtml(row.host||'')}</td>
            <td class="text-xs max-w-[250px] truncate font-mono" title="${escapeHtml(row.path||'')}">${escapeHtml(row.path||'')}</td>
            <td class="font-mono text-xs">${escapeHtml(row.http_version||'')}</td>
            <td class="text-xs max-w-[200px] truncate" title="${escapeHtml(row.header_user_agent||'')}">${escapeHtml(row.header_user_agent||'')}</td>
            <td class="text-xs font-mono max-w-[100px] truncate">${fmtJA4(row.ja4)}</td>
            <td>${fmtCountry(row.src_country_code)}</td>
        </tr>`).join('') || '<tr><td colspan="10" class="text-center text-gray-500 py-8">Aucun log</td></tr>';
        const total=d.total||0;
        document.getElementById('traffic-info').textContent=`${fmtNum(total)} logs — page ${tPage}/${Math.max(1,Math.ceil(total/100))}`;
        document.getElementById('prev-btn').disabled=tPage<=1;
        document.getElementById('next-btn').disabled=tPage*100>=total;
    } catch(e) { console.error(e); }
}
document.getElementById('prev-btn').onclick=()=>{if(tPage>1){tPage--;loadTraffic();}};
document.getElementById('next-btn').onclick=()=>{tPage++;loadTraffic();};

// Column sorting
document.querySelectorAll('[data-sort]').forEach(th => th.onclick = () => {
    const s=th.dataset.sort;
    if(tSort===s) tOrder=tOrder==='DESC'?'ASC':'DESC'; else {tSort=s;tOrder='DESC';}
    tPage=1; loadTraffic();
});

// Filters with debounce
let filterTimer;
['method-filter','host-filter','search-filter'].forEach(id=>{
    let el=document.getElementById(id);
    el.addEventListener(el.tagName==='SELECT'?'change':'input',()=>{
        clearTimeout(filterTimer);
        filterTimer=setTimeout(()=>{tPage=1;loadTraffic();},300);
    });
});
loadTraffic();

// Traffic summary charts
async function loadTrafficSummary() {
    try {
        const r = await fetch('/api/traffic?per_page=500'); const d = await r.json();
        const rows = d.data||[];
        const METHOD_COLORS = {GET:'#22c55e',POST:'#3b82f6',PUT:'#eab308',DELETE:'#ef4444',HEAD:'#8b5cf6',OPTIONS:'#6b7280'};
        const methods = {}, uas = {}, paths = {};
        rows.forEach(row => {
            methods[row.method] = (methods[row.method]||0)+1;
            const ua = (row.header_user_agent||'').substring(0,30) || '(empty)';
            uas[ua] = (uas[ua]||0)+1;
            const p = (row.path||'/').split('?')[0];
            paths[p] = (paths[p]||0)+1;
        });
        const ch1 = echarts.init(document.getElementById('method-chart'));
        ch1.setOption(ecBase({tooltip:ecTooltip({trigger:'item'}),series:[{type:'pie',radius:['30%','65%'],label:{color:EC_TEXT,fontSize:10,formatter:'{b}\n{d}%'},
            data:Object.entries(methods).map(([k,v])=>({name:k,value:v,itemStyle:{color:METHOD_COLORS[k]||'#6b7280'}}))}]}));
        const topUA = Object.entries(uas).sort((a,b)=>b[1]-a[1]).slice(0,5);
        if (topUA.length) {
            const ch2 = echarts.init(document.getElementById('ua-chart'));
            ch2.setOption(ecBase({tooltip:ecTooltip({trigger:'axis'}),grid:{left:10,right:40,top:5,bottom:5,containLabel:true},
                yAxis:{type:'category',data:topUA.map(r=>r[0]).reverse(),axisLabel:{color:EC_TEXT,fontSize:9,width:120,overflow:'truncate'},axisLine:{show:false}},
                xAxis:{type:'value',show:false},
                series:[{type:'bar',data:topUA.map(r=>r[1]).reverse(),barWidth:'60%',itemStyle:{color:'#3b82f6'},label:{show:true,position:'right',color:EC_TEXT,fontSize:10}}]}));
        }
        const topPath = Object.entries(paths).sort((a,b)=>b[1]-a[1]).slice(0,5);
        if (topPath.length) {
            const ch3 = echarts.init(document.getElementById('path-chart'));
            ch3.setOption(ecBase({tooltip:ecTooltip({trigger:'axis'}),grid:{left:10,right:40,top:5,bottom:5,containLabel:true},
                yAxis:{type:'category',data:topPath.map(r=>r[0]).reverse(),axisLabel:{color:EC_TEXT,fontSize:9,width:120,overflow:'truncate'},axisLine:{show:false}},
                xAxis:{type:'value',show:false},
                series:[{type:'bar',data:topPath.map(r=>r[1]).reverse(),barWidth:'60%',itemStyle:{color:'#14b8a6'},label:{show:true,position:'right',color:EC_TEXT,fontSize:10}}]}));
        }
    } catch(e) { console.error(e); }
}
loadTrafficSummary();
</script>
{% endblock %}
