<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<style>
.hist-row{background:#fff;border:1px solid #e2e6ea;border-radius:8px;padding:12px 16px;margin-bottom:8px;display:flex;align-items:center;gap:14px}
.hist-pct{font-size:20px;font-weight:700;width:60px;text-align:center}
.hist-bar-wrap{flex:1;height:8px;background:#f0f2f5;border-radius:4px;overflow:hidden}
.hist-bar{height:100%;border-radius:4px}
.hist-info{font-size:12px;color:#888;width:220px}
.hist-detail-link{font-size:11px}
</style>

<section class="content-header">
    <h1><i class="fa fa-history"></i> Histórico de Diagnósticos</h1>
    <ol class="breadcrumb">
        <li><a href="<?php echo site_url('admin') ?>"><i class="fa fa-dashboard"></i> Dashboard</a></li>
        <li><a href="<?php echo site_url('admin/patrimonio') ?>">Busca Patrimonial</a></li>
        <li><a href="<?php echo site_url('admin/patrimonio/diagnostico') ?>">Diagnóstico de APIs</a></li>
        <li class="active">Histórico</li>
    </ol>
</section>

<section class="content">

<div class="box box-default" style="margin-bottom:14px">
    <div class="box-body" style="padding:10px 14px">
        <a href="<?php echo site_url('admin/patrimonio/diagnostico') ?>" class="btn btn-primary btn-sm">
            <i class="fa fa-play"></i> Executar Novo Diagnóstico
        </a>
        <span style="font-size:12px;color:#888;margin-left:10px">
            Mostrando os últimos <?php echo count($historico) ?> diagnósticos executados
        </span>
    </div>
</div>

<?php if(empty($historico)): ?>
<div class="box box-default">
    <div class="box-body" style="text-align:center;padding:30px;color:#888">
        <i class="fa fa-history" style="font-size:36px;opacity:.2;display:block;margin-bottom:8px"></i>
        Nenhum diagnóstico foi executado ainda.
    </div>
</div>
<?php else: ?>

<div class="box box-primary">
    <div class="box-header with-border"><h3 class="box-title"><i class="fa fa-list"></i> Linha do Tempo</h3></div>
    <div class="box-body">
    <?php foreach($historico as $h):
        $pct = $h->total_apis > 0 ? round(($h->apis_ok / $h->total_apis) * 100) : 0;
        $cor = $pct >= 80 ? '#2e7d32' : ($pct >= 50 ? '#d35400' : '#c0392b');
        $detalhes = json_decode($h->detalhes_json, true);
        $falhas = array_filter($detalhes ?: [], fn($d) => !$d['ok']);
    ?>
    <div class="hist-row">
        <div class="hist-pct" style="color:<?php echo $cor ?>"><?php echo $pct ?>%</div>
        <div class="hist-bar-wrap"><div class="hist-bar" style="width:<?php echo $pct ?>%;background:<?php echo $cor ?>"></div></div>
        <div class="hist-info">
            <?php echo date('d/m/Y H:i', strtotime($h->created_at)) ?><br>
            <strong style="color:#2e7d32"><?php echo $h->apis_ok ?> ok</strong> ·
            <strong style="color:#c0392b"><?php echo $h->apis_falha ?> falha(s)</strong>
        </div>
        <?php if(!empty($falhas)): ?>
        <div style="font-size:11px;color:#c0392b;max-width:300px">
            <i class="fa fa-exclamation-triangle"></i>
            <?php echo implode(', ', array_map(fn($f) => $f['nome'], $falhas)) ?>
        </div>
        <?php else: ?>
        <div style="font-size:11px;color:#2e7d32">
            <i class="fa fa-check"></i> Todas as APIs funcionando
        </div>
        <?php endif; ?>
    </div>
    <?php endforeach; ?>
    </div>
</div>

<?php
// Análise de tendência: APIs que mais falharam no período
$contagem_falhas = [];
foreach($historico as $h) {
    $detalhes = json_decode($h->detalhes_json, true) ?: [];
    foreach($detalhes as $d) {
        if (!$d['ok']) {
            $contagem_falhas[$d['nome']] = ($contagem_falhas[$d['nome']] ?? 0) + 1;
        }
    }
}
arsort($contagem_falhas);
?>
<?php if(!empty($contagem_falhas)): ?>
<div class="box" style="border-top:3px solid #c0392b">
    <div class="box-header with-border"><h3 class="box-title"><i class="fa fa-exclamation-triangle text-danger"></i> APIs Mais Instáveis no Período</h3></div>
    <div class="box-body no-padding">
        <table class="table table-hover" style="margin:0">
            <thead><tr><th>API</th><th>Falhas no período</th><th>% dos testes</th></tr></thead>
            <tbody>
            <?php foreach($contagem_falhas as $nome => $qtd):
                $pct_falha = round(($qtd / count($historico)) * 100);
            ?>
            <tr>
                <td><?php echo htmlspecialchars($nome) ?></td>
                <td><?php echo $qtd ?> de <?php echo count($historico) ?></td>
                <td>
                    <span class="label label-<?php echo $pct_falha > 50 ? 'danger' : ($pct_falha > 20 ? 'warning' : 'default') ?>">
                        <?php echo $pct_falha ?>%
                    </span>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

<?php endif; ?>

</section>
