<?php
declare(strict_types=1);

require_once 'auth.php';
require_once 'conexao.php';

date_default_timezone_set('America/Sao_Paulo');

if ($mysqli instanceof mysqli) {
    $mysqli->set_charset('utf8mb4');
}

function e(mixed $v): string
{
    return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
}

function js(mixed $v): string
{
    return json_encode(
        $v,
        JSON_UNESCAPED_UNICODE |
        JSON_UNESCAPED_SLASHES |
        JSON_HEX_TAG |
        JSON_HEX_APOS |
        JSON_HEX_QUOT |
        JSON_HEX_AMP
    ) ?: '[]';
}

function tabelaExiste(mysqli $db, string $tabela): bool
{
    $stmt = $db->prepare("
        SELECT COUNT(*) total
        FROM information_schema.tables
        WHERE table_schema = DATABASE()
          AND table_name = ?
    ");

    if (!$stmt) {
        return false;
    }

    $stmt->bind_param('s', $tabela);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    return (int)($row['total'] ?? 0) > 0;
}

function colunaExiste(mysqli $db, string $tabela, string $coluna): bool
{
    $stmt = $db->prepare("
        SELECT COUNT(*) total
        FROM information_schema.columns
        WHERE table_schema = DATABASE()
          AND table_name = ?
          AND column_name = ?
    ");

    if (!$stmt) {
        return false;
    }

    $stmt->bind_param('ss', $tabela, $coluna);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    return (int)($row['total'] ?? 0) > 0;
}

function statusCodigo(string $status): string
{
    $s = mb_strtolower(trim($status), 'UTF-8');

    if (str_contains($s, 'finaliz')) {
        return 'finalizado';
    }

    if (str_contains($s, 'pendente') && str_contains($s, 'retirada')) {
        return 'pendente_retirada';
    }

    return 'em_andamento';
}

function prioridadeNome(string $prioridade): string
{
    return match (mb_strtolower(trim($prioridade), 'UTF-8')) {
        'urgente' => 'Urgente',
        'alta' => 'Alta',
        'média', 'media' => 'Média',
        'baixa' => 'Baixa',
        default => 'Não informada'
    };
}

function iniciais(string $nome): string
{
    $partes = array_values(
        array_filter(preg_split('/\s+/', trim($nome)) ?: [])
    );

    if (!$partes) {
        return 'TI';
    }

    $a = mb_substr($partes[0], 0, 1, 'UTF-8');
    $b = count($partes) > 1
        ? mb_substr($partes[array_key_last($partes)], 0, 1, 'UTF-8')
        : '';

    return mb_strtoupper($a . $b, 'UTF-8');
}

$usuario = trim((string)($_SESSION['usuario'] ?? 'Servidor da TI'));
$iniciais = iniciais($usuario);
$hoje = date('Y-m-d');
$mesAtual = date('Y-m');
$mesAnterior = date('Y-m', strtotime('-1 month'));

$ordens = [];

$res = $mysqli->query("
    SELECT
        id,
        numero_os,
        nome_solicitante,
        setor,
        tipo_equipamento,
        marca,
        modelo,
        patrimonio,
        data_entrada,
        data_saida,
        prazo,
        status,
        prioridade
    FROM ordens_servico
    ORDER BY data_entrada DESC
");

if ($res) {
    while ($r = $res->fetch_assoc()) {
        $ordens[] = $r;
    }
    $res->free();
}

$total = count($ordens);
$andamento = 0;
$finalizadas = 0;
$retirada = 0;
$atrasadas = 0;
$urgentes = 0;
$altas = 0;
$abertasHoje = 0;
$finalizadasHoje = 0;
$abertasMes = 0;
$abertasMesAnterior = 0;
$finalizadasMes = 0;
$maiorBacklog = 0;

$horasConclusao = [];
$status = [];
$prioridades = [];
$equipamentos = [];
$setores = [];
$solicitantes = [];
$diasSemana = [
    'Domingo' => 0,
    'Segunda' => 0,
    'Terça' => 0,
    'Quarta' => 0,
    'Quinta' => 0,
    'Sexta' => 0,
    'Sábado' => 0
];

$faixasBacklog = [
    '0–2 dias' => 0,
    '3–5 dias' => 0,
    '6–10 dias' => 0,
    '11–20 dias' => 0,
    '21+ dias' => 0
];

$matrizRisco = [
    'Urgente' => ['No prazo' => 0, 'Atrasada' => 0],
    'Alta' => ['No prazo' => 0, 'Atrasada' => 0],
    'Média' => ['No prazo' => 0, 'Atrasada' => 0],
    'Baixa' => ['No prazo' => 0, 'Atrasada' => 0],
    'Não informada' => ['No prazo' => 0, 'Atrasada' => 0]
];

$mensal = [];

for ($i = 11; $i >= 0; $i--) {
    $chave = date('Y-m', strtotime("-{$i} months"));
    $mensal[$chave] = [
        'mes' => date('m/Y', strtotime($chave . '-01')),
        'abertas' => 0,
        'finalizadas' => 0
    ];
}

$diaria = [];
$inicio = new DateTimeImmutable('-29 days');
$fim = new DateTimeImmutable('today');

for ($d = $inicio; $d <= $fim; $d = $d->modify('+1 day')) {
    $chave = $d->format('Y-m-d');
    $diaria[$chave] = [
        'dia' => $d->format('d/m'),
        'abertas' => 0,
        'finalizadas' => 0
    ];
}

$criticas = [];

$semanaMap = [
    0 => 'Domingo',
    1 => 'Segunda',
    2 => 'Terça',
    3 => 'Quarta',
    4 => 'Quinta',
    5 => 'Sexta',
    6 => 'Sábado'
];

foreach ($ordens as $o) {
    $st = statusCodigo((string)($o['status'] ?? ''));
    $pr = prioridadeNome((string)($o['prioridade'] ?? ''));

    $entrada = strtotime((string)($o['data_entrada'] ?? '')) ?: 0;
    $saida = strtotime((string)($o['data_saida'] ?? '')) ?: 0;
    $prazo = max(0, (int)($o['prazo'] ?? 0));

    $statusLabel = match ($st) {
        'finalizado' => 'Finalizado',
        'pendente_retirada' => 'Pendente retirada',
        default => 'Em andamento'
    };

    $status[$statusLabel] = ($status[$statusLabel] ?? 0) + 1;
    $prioridades[$pr] = ($prioridades[$pr] ?? 0) + 1;

    $equip = trim((string)($o['tipo_equipamento'] ?? ''));
    $equip = $equip !== '' ? $equip : 'Não informado';
    $equipamentos[$equip] = ($equipamentos[$equip] ?? 0) + 1;

    $setor = trim((string)($o['setor'] ?? ''));
    $setor = $setor !== '' ? $setor : 'Não informado';
    $setores[$setor] = ($setores[$setor] ?? 0) + 1;

    if ($entrada > 0) {
        $diaSemana = $semanaMap[(int)date('w', $entrada)];
        $diasSemana[$diaSemana]++;

        $mesEntrada = date('Y-m', $entrada);
        $diaEntrada = date('Y-m-d', $entrada);

        if (isset($mensal[$mesEntrada])) {
            $mensal[$mesEntrada]['abertas']++;
        }

        if (isset($diaria[$diaEntrada])) {
            $diaria[$diaEntrada]['abertas']++;
        }

        if ($mesEntrada === $mesAtual) {
            $abertasMes++;

            $solicitante = trim(
                (string)($o['nome_solicitante'] ?? '')
            );

            $solicitante = $solicitante !== ''
                ? $solicitante
                : 'Não informado';

            $solicitantes[$solicitante] =
                ($solicitantes[$solicitante] ?? 0) + 1;
        }

        if ($mesEntrada === $mesAnterior) {
            $abertasMesAnterior++;
        }

        if ($diaEntrada === $hoje) {
            $abertasHoje++;
        }
    }

    if ($st === 'finalizado') {
        $finalizadas++;

        if ($saida > 0) {
            $mesSaida = date('Y-m', $saida);
            $diaSaida = date('Y-m-d', $saida);

            if (isset($mensal[$mesSaida])) {
                $mensal[$mesSaida]['finalizadas']++;
            }

            if (isset($diaria[$diaSaida])) {
                $diaria[$diaSaida]['finalizadas']++;
            }

            if ($mesSaida === $mesAtual) {
                $finalizadasMes++;
            }

            if ($diaSaida === $hoje) {
                $finalizadasHoje++;
            }

            if ($entrada > 0 && $saida >= $entrada) {
                $horasConclusao[] = ($saida - $entrada) / 3600;
            }
        }

        continue;
    }

    if ($st === 'pendente_retirada') {
        $retirada++;
    } else {
        $andamento++;
    }

    if ($pr === 'Urgente') {
        $urgentes++;
    }

    if ($pr === 'Alta') {
        $altas++;
    }

    $dias = $entrada > 0
        ? max(0, (int)floor((time() - $entrada) / 86400))
        : 0;

    $maiorBacklog = max($maiorBacklog, $dias);

    if ($dias <= 2) {
        $faixasBacklog['0–2 dias']++;
    } elseif ($dias <= 5) {
        $faixasBacklog['3–5 dias']++;
    } elseif ($dias <= 10) {
        $faixasBacklog['6–10 dias']++;
    } elseif ($dias <= 20) {
        $faixasBacklog['11–20 dias']++;
    } else {
        $faixasBacklog['21+ dias']++;
    }

    $vencida = $prazo > 0 && $dias >= $prazo;
    $matrizRisco[$pr][$vencida ? 'Atrasada' : 'No prazo']++;

    if ($vencida) {
        $atrasadas++;

        $criticas[] = [
            'id' => (int)($o['id'] ?? 0),
            'numero' => (string)($o['numero_os'] ?? ''),
            'solicitante' => (string)($o['nome_solicitante'] ?? ''),
            'setor' => $setor,
            'equipamento' => $equip,
            'prioridade' => $pr,
            'dias' => $dias,
            'prazo' => $prazo
        ];
    }
}

arsort($equipamentos);
$equipamentos = array_slice($equipamentos, 0, 8, true);

arsort($setores);
$setores = array_slice($setores, 0, 8, true);

arsort($solicitantes);
$solicitantes = array_slice($solicitantes, 0, 6, true);

$prioridadesOrdenadas = [];

foreach (
    ['Urgente', 'Alta', 'Média', 'Baixa', 'Não informada']
    as $p
) {
    if (isset($prioridades[$p])) {
        $prioridadesOrdenadas[$p] = $prioridades[$p];
    }
}

$prioridades = $prioridadesOrdenadas;

usort(
    $criticas,
    static function (array $a, array $b): int {
        $peso = [
            'Urgente' => 5,
            'Alta' => 4,
            'Média' => 3,
            'Baixa' => 2,
            'Não informada' => 1
        ];

        $c = ($peso[$b['prioridade']] ?? 0)
            <=> ($peso[$a['prioridade']] ?? 0);

        return $c !== 0 ? $c : ($b['dias'] <=> $a['dias']);
    }
);

$criticas = array_slice($criticas, 0, 8);

sort($horasConclusao);

$slaMedio = $horasConclusao
    ? round(array_sum($horasConclusao) / count($horasConclusao), 1)
    : 0;

$slaMediano = 0;

if ($horasConclusao) {
    $n = count($horasConclusao);
    $m = intdiv($n, 2);

    $slaMediano = $n % 2 === 0
        ? round(($horasConclusao[$m - 1] + $horasConclusao[$m]) / 2, 1)
        : round($horasConclusao[$m], 1);
}

$backlog = $andamento + $retirada;

$taxaConclusao = $total > 0
    ? round(($finalizadas / $total) * 100, 1)
    : 0;

$taxaAtraso = $backlog > 0
    ? round(($atrasadas / $backlog) * 100, 1)
    : 0;

$variacaoMes = $abertasMesAnterior > 0
    ? round(
        (($abertasMes - $abertasMesAnterior) /
        $abertasMesAnterior) * 100,
        1
    )
    : ($abertasMes > 0 ? 100 : 0);

$saldoHoje = $finalizadasHoje - $abertasHoje;
$saldoMes = $finalizadasMes - $abertasMes;

$almox = [
    'itens' => 0,
    'unidades' => 0,
    'criticos' => 0
];

$toner = [
    'modelos' => 0,
    'unidades' => 0,
    'criticos' => 0
];

if (tabelaExiste($mysqli, 'almoxarifado')) {
    $r = $mysqli->query("
        SELECT
            COUNT(*) itens,
            COALESCE(SUM(quantidade), 0) unidades,
            COALESCE(
                SUM(CASE WHEN quantidade <= minimo THEN 1 ELSE 0 END),
                0
            ) criticos
        FROM almoxarifado
    ");

    if ($r) {
        $x = $r->fetch_assoc();
        $almox['itens'] = (int)($x['itens'] ?? 0);
        $almox['unidades'] = (int)($x['unidades'] ?? 0);
        $almox['criticos'] = (int)($x['criticos'] ?? 0);
        $r->free();
    }
}

if (tabelaExiste($mysqli, 'tonner_estoque')) {
    $minimo = colunaExiste(
        $mysqli,
        'tonner_estoque',
        'estoque_minimo'
    )
        ? 'COALESCE(estoque_minimo, 2)'
        : '2';

    $r = $mysqli->query("
        SELECT
            COUNT(*) modelos,
            COALESCE(SUM(quantidade), 0) unidades,
            COALESCE(
                SUM(CASE WHEN quantidade <= {$minimo} THEN 1 ELSE 0 END),
                0
            ) criticos
        FROM tonner_estoque
    ");

    if ($r) {
        $x = $r->fetch_assoc();
        $toner['modelos'] = (int)($x['modelos'] ?? 0);
        $toner['unidades'] = (int)($x['unidades'] ?? 0);
        $toner['criticos'] = (int)($x['criticos'] ?? 0);
        $r->free();
    }
}

$score = 100;
$score -= min(40, $taxaAtraso * 1.6);
$score -= min(18, $urgentes * 4);
$score -= min(12, $altas * 1.5);
$score -= min(15, $almox['criticos'] * 2.5);
$score -= min(15, $toner['criticos'] * 3);
$score = max(0, min(100, (int)round($score)));

if ($score >= 85) {
    $scoreLabel = 'Operação excelente';
    $scoreClass = 'success';
    $scoreTexto = 'Prazos, capacidade e estoque estão equilibrados.';
} elseif ($score >= 65) {
    $scoreLabel = 'Operação em atenção';
    $scoreClass = 'warning';
    $scoreTexto = 'Existem sinais de pressão que exigem acompanhamento.';
} else {
    $scoreLabel = 'Operação crítica';
    $scoreClass = 'danger';
    $scoreTexto = 'Há riscos relevantes em prazos, prioridades ou estoque.';
}

$abertas30 = array_sum(array_column($diaria, 'abertas'));
$finalizadas30 = array_sum(array_column($diaria, 'finalizadas'));

$projecaoAbertas = (int)round(($abertas30 / 30) * 30);
$projecaoFinalizadas = (int)round(($finalizadas30 / 30) * 30);
$tendenciaBacklog = $projecaoAbertas - $projecaoFinalizadas;

if ($tendenciaBacklog > 0) {
    $tendenciaLabel = 'Tendência de crescimento';
    $tendenciaClass = 'danger';
    $tendenciaTexto =
        "O backlog pode crescer cerca de {$tendenciaBacklog} demanda(s) em 30 dias.";
} elseif ($tendenciaBacklog < 0) {
    $tendenciaLabel = 'Tendência de redução';
    $tendenciaClass = 'success';
    $tendenciaTexto =
        'A capacidade média de finalização está acima da entrada.';
} else {
    $tendenciaLabel = 'Tendência estável';
    $tendenciaClass = 'info';
    $tendenciaTexto =
        'A entrada e a finalização estão praticamente equilibradas.';
}

$insights = [];

if ($atrasadas > 0) {
    $insights[] = [
        'tipo' => $atrasadas >= 10 ? 'danger' : 'warning',
        'icone' => 'bi-alarm-fill',
        'titulo' => 'Backlog vencido',
        'texto' => "{$atrasadas} demanda(s) estão fora do prazo."
    ];
}

if ($urgentes > 0) {
    $insights[] = [
        'tipo' => 'danger',
        'icone' => 'bi-lightning-charge-fill',
        'titulo' => 'Urgências abertas',
        'texto' => "{$urgentes} ordem(ns) urgente(s) aguardam conclusão."
    ];
}

if ($maiorBacklog >= 15) {
    $insights[] = [
        'tipo' => 'warning',
        'icone' => 'bi-hourglass-bottom',
        'titulo' => 'Backlog envelhecido',
        'texto' => "A ordem mais antiga possui {$maiorBacklog} dias."
    ];
}

if ($variacaoMes > 20) {
    $insights[] = [
        'tipo' => 'info',
        'icone' => 'bi-graph-up-arrow',
        'titulo' => 'Crescimento da demanda',
        'texto' => "O mês atual cresceu {$variacaoMes}%."
    ];
}

if ($almox['criticos'] > 0) {
    $insights[] = [
        'tipo' => 'warning',
        'icone' => 'bi-boxes',
        'titulo' => 'Almoxarifado crítico',
        'texto' => "{$almox['criticos']} item(ns) atingiram o mínimo."
    ];
}

if ($toner['criticos'] > 0) {
    $insights[] = [
        'tipo' => 'danger',
        'icone' => 'bi-printer-fill',
        'titulo' => 'Toner crítico',
        'texto' => "{$toner['criticos']} modelo(s) precisam de reposição."
    ];
}

if (!$insights) {
    $insights[] = [
        'tipo' => 'success',
        'icone' => 'bi-check-circle-fill',
        'titulo' => 'Operação estável',
        'texto' => 'Nenhum risco relevante foi identificado.'
    ];
}

$insights = array_slice($insights, 0, 6);

$grafStatus = array_map(
    static fn(string $l, int $v): array => [
        'label' => $l,
        'value' => $v
    ],
    array_keys($status),
    array_values($status)
);

$grafPrioridade = array_map(
    static fn(string $l, int $v): array => [
        'label' => $l,
        'value' => $v
    ],
    array_keys($prioridades),
    array_values($prioridades)
);

$grafEquip = array_map(
    static fn(string $l, int $v): array => [
        'label' => $l,
        'value' => $v
    ],
    array_keys($equipamentos),
    array_values($equipamentos)
);

$grafSetor = array_map(
    static fn(string $l, int $v): array => [
        'label' => $l,
        'value' => $v
    ],
    array_keys($setores),
    array_values($setores)
);

$grafSolicitante = array_map(
    static fn(string $l, int $v): array => [
        'label' => $l,
        'value' => $v
    ],
    array_keys($solicitantes),
    array_values($solicitantes)
);

$grafSemana = array_map(
    static fn(string $l, int $v): array => [
        'label' => $l,
        'value' => $v
    ],
    array_keys($diasSemana),
    array_values($diasSemana)
);

$grafBacklog = array_map(
    static fn(string $l, int $v): array => [
        'label' => $l,
        'value' => $v
    ],
    array_keys($faixasBacklog),
    array_values($faixasBacklog)
);

$grafRisco = [];

foreach ($matrizRisco as $p => $v) {
    $grafRisco[] = [
        'prioridade' => $p,
        'no_prazo' => $v['No prazo'],
        'atrasada' => $v['Atrasada']
    ];
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<meta name="theme-color" content="#061b33">
<title>Central de Inteligência | Manutenção TI</title>

<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.7/dist/chart.umd.min.js"></script>

<style>
:root{
    --n950:#03101f;
    --n900:#061b33;
    --n850:#082640;
    --blue:#2487d8;
    --cyan:#12a9c2;
    --green:#18a373;
    --yellow:#e5a21c;
    --red:#dd4760;
    --purple:#8a6bd1;
    --text:#f3f7fb;
    --soft:#bdc9d8;
    --muted:#8292a6;
    --surface:rgba(255,255,255,.075);
    --surface2:rgba(255,255,255,.105);
    --border:rgba(255,255,255,.11);
    --border2:rgba(255,255,255,.075);
    --shadow:0 24px 65px rgba(0,0,0,.26);
    --shadow-lg:0 38px 110px rgba(0,0,0,.38);
}
*{box-sizing:border-box}
html{min-height:100%;scroll-behavior:smooth}
body{
    margin:0;
    min-height:100vh;
    overflow-x:hidden;
    font-family:"Inter",system-ui,sans-serif;
    color:var(--text);
    background:
      radial-gradient(circle at 8% 6%,rgba(36,135,216,.27),transparent 31rem),
      radial-gradient(circle at 95% 86%,rgba(18,169,194,.16),transparent 34rem),
      linear-gradient(145deg,var(--n950),var(--n900) 50%,#091a2a);
}
a{text-decoration:none}
button{font:inherit}
.top-strip{
    position:fixed;top:0;right:0;left:0;z-index:1100;height:6px;
    background:linear-gradient(90deg,var(--blue) 0 55%,var(--cyan) 55% 82%,var(--green) 82% 100%);
}
.bg-grid{
    position:fixed;inset:0;z-index:0;pointer-events:none;
    background-image:
      linear-gradient(rgba(255,255,255,.034) 1px,transparent 1px),
      linear-gradient(90deg,rgba(255,255,255,.034) 1px,transparent 1px);
    background-size:52px 52px;
    mask-image:linear-gradient(to bottom,#000,transparent 96%);
}
.app{position:relative;z-index:2;padding-top:6px}
.header{
    position:relative;overflow:hidden;margin:19px 19px 0;padding:21px 23px;
    border:1px solid var(--border);border-radius:28px;
    background:
      radial-gradient(circle at 84% 0,rgba(36,135,216,.28),transparent 25rem),
      radial-gradient(circle at 0 100%,rgba(18,169,194,.15),transparent 26rem),
      linear-gradient(135deg,rgba(4,16,31,.97),rgba(8,38,64,.94));
    box-shadow:var(--shadow-lg),inset 0 1px 0 rgba(255,255,255,.08);
}
.header:before{
    content:"";position:absolute;top:-220px;right:-120px;width:450px;height:450px;
    border:42px solid rgba(255,255,255,.03);border-radius:50%;
    box-shadow:0 0 0 44px rgba(255,255,255,.015),0 0 0 88px rgba(255,255,255,.01);
    animation:spin 33s linear infinite;
}
@keyframes spin{to{transform:rotate(360deg)}}
.header-content{
    position:relative;z-index:2;display:flex;align-items:center;
    justify-content:space-between;gap:24px;
}
.brand{display:flex;align-items:center;gap:15px;min-width:0}
.logo{
    width:72px;height:72px;flex:0 0 72px;padding:5px;
    display:grid;place-items:center;border:1px solid var(--border);
    border-radius:22px;background:rgba(255,255,255,.09);
    box-shadow:0 19px 38px rgba(0,0,0,.25);
    animation:float 6s ease-in-out infinite;
}
.logo img{max-width:58px;max-height:58px;object-fit:contain}
.logo-fallback{display:none;font-size:29px;color:#a8d5f4}
@keyframes float{
    0%,100%{transform:perspective(700px) translateY(0) rotateX(4deg) rotateY(-5deg)}
    50%{transform:perspective(700px) translateY(-5px) rotateX(0) rotateY(3deg)}
}
.gov{
    display:inline-flex;align-items:center;gap:7px;margin-bottom:7px;padding:6px 10px;
    border:1px solid var(--border);border-radius:999px;background:rgba(255,255,255,.055);
    color:rgba(255,255,255,.74);font-size:8px;font-weight:800;
    letter-spacing:.7px;text-transform:uppercase;
}
.gov i{color:#86e7ef}
.header h1{
    margin:0;font-size:clamp(22px,2.5vw,35px);line-height:1.04;
    letter-spacing:-1.05px;font-weight:900;
}
.subtitle{margin:7px 0 0;color:rgba(255,255,255,.61);font-size:10px;line-height:1.55}
.live{
    display:inline-flex;align-items:center;gap:7px;margin-top:10px;padding:6px 9px;
    border:1px solid var(--border);border-radius:999px;background:rgba(255,255,255,.045);
    color:rgba(255,255,255,.72);font-size:7px;font-weight:750;
}
.live-dot{
    width:7px;height:7px;border-radius:50%;background:#66e5c1;
    animation:pulse 1.7s ease-in-out infinite;
}
@keyframes pulse{
    0%,100%{box-shadow:0 0 0 0 rgba(102,229,193,.22)}
    50%{box-shadow:0 0 0 7px rgba(102,229,193,0)}
}
.header-side{
    min-width:470px;display:flex;flex-direction:column;align-items:flex-end;gap:12px;
}
.user{display:flex;align-items:center;gap:10px;text-align:right}
.user strong{display:block;font-size:10px;font-weight:800}
.user span{display:block;margin-top:3px;color:rgba(255,255,255,.52);font-size:7px}
.avatar{
    width:41px;height:41px;display:grid;place-items:center;border:1px solid var(--border);
    border-radius:13px;background:rgba(255,255,255,.08);color:#d8ecf9;
    font-size:11px;font-weight:900;
}
.actions{display:flex;justify-content:flex-end;gap:7px;flex-wrap:wrap}
.action{
    min-height:38px;display:inline-flex;align-items:center;justify-content:center;gap:7px;
    padding:0 12px;border:1px solid var(--border);border-radius:13px;
    color:#fff;background:rgba(255,255,255,.06);font-size:8px;font-weight:800;
    letter-spacing:.2px;text-transform:uppercase;transition:.2s;
}
.action:hover{
    color:#fff;background:rgba(255,255,255,.12);transform:translateY(-2px);
    box-shadow:0 12px 24px rgba(0,0,0,.18);
}
.action.primary{color:var(--n900);border-color:#fff;background:#fff}
.action.primary:hover{color:var(--n900);background:#eaf6fc}
.page{width:100%;max-width:1780px;margin:0 auto;padding:17px 19px 34px}
.hero{
    position:relative;display:grid;grid-template-columns:minmax(0,1.35fr) minmax(290px,.65fr);
    gap:15px;overflow:hidden;padding:22px;border:1px solid var(--border);
    border-radius:30px;background:
      radial-gradient(circle at 87% 0,rgba(36,135,216,.15),transparent 25rem),
      rgba(255,255,255,.055);
    backdrop-filter:blur(22px);box-shadow:var(--shadow),inset 0 1px 0 rgba(255,255,255,.06);
    transform-style:preserve-3d;transition:transform .25s;
}
.hero-label{
    display:inline-flex;align-items:center;gap:7px;margin-bottom:10px;
    color:#8ddcf2;font-size:8px;font-weight:850;letter-spacing:.7px;text-transform:uppercase;
}
.hero h2{
    max-width:900px;margin:0;font-size:clamp(28px,3.2vw,45px);
    line-height:1.04;letter-spacing:-1.8px;font-weight:900;
}
.hero h2 span{color:#69c9f2}
.hero p{max-width:880px;margin:12px 0 0;color:var(--soft);font-size:10px;line-height:1.68}
.chips{display:flex;flex-wrap:wrap;gap:7px;margin-top:16px}
.chip{
    display:inline-flex;align-items:center;gap:6px;padding:7px 9px;border:1px solid var(--border);
    border-radius:999px;background:rgba(255,255,255,.055);color:#bfcedc;
    font-size:7px;font-weight:750;
}
.chip i{color:#72d6ed}
.score{
    position:relative;z-index:2;min-height:225px;padding:19px;
    display:flex;flex-direction:column;justify-content:space-between;overflow:hidden;
    border:1px solid rgba(255,255,255,.09);border-radius:24px;
    background:
      radial-gradient(circle at 88% 11%,rgba(255,255,255,.08),transparent 12rem),
      linear-gradient(145deg,rgba(3,16,31,.92),rgba(10,51,82,.87));
    box-shadow:0 23px 49px rgba(0,0,0,.28),inset 0 1px 0 rgba(255,255,255,.06);
    transform:translateZ(20px);
}
.score-top{display:flex;align-items:center;justify-content:space-between;gap:10px}
.score-label{color:#a8d5f4;font-size:8px;font-weight:850;text-transform:uppercase}
.score-state{
    padding:6px 8px;border:1px solid var(--border);border-radius:999px;
    background:rgba(255,255,255,.05);color:rgba(255,255,255,.72);
    font-size:7px;font-weight:800;text-transform:uppercase;
}
.score-number{display:flex;align-items:flex-end;gap:3px;margin-top:18px}
.score-number strong{font-size:54px;line-height:.9;letter-spacing:-2px;font-weight:900}
.score-number span{color:rgba(255,255,255,.55);font-size:14px;font-weight:700}
.score-text{margin:8px 0 0;color:rgba(255,255,255,.55);font-size:8px;line-height:1.5}
.progress{height:8px;overflow:hidden;margin-top:16px;border-radius:999px;background:rgba(255,255,255,.1)}
.progress span{display:block;height:100%;border-radius:inherit;background:linear-gradient(90deg,#2dd4bf,#8bdaf2)}
.kpis{display:grid;grid-template-columns:repeat(6,minmax(0,1fr));gap:12px;margin-top:14px}
.kpi{
    position:relative;min-height:137px;padding:16px;overflow:hidden;
    border:1px solid var(--border);border-radius:22px;background:var(--surface);
    backdrop-filter:blur(16px);box-shadow:0 15px 38px rgba(0,0,0,.18);
    transform-style:preserve-3d;transition:.22s;
}
.kpi:hover{background:var(--surface2);transform:translateY(-5px) perspective(800px) rotateX(2deg);box-shadow:var(--shadow)}
.kpi:after{
    content:"";position:absolute;top:-52px;right:-52px;width:123px;height:123px;
    border-radius:50%;background:rgba(36,135,216,.085);
}
.kpi-top{position:relative;z-index:2;display:flex;justify-content:space-between;gap:10px}
.kpi-icon{
    width:40px;height:40px;display:grid;place-items:center;border-radius:13px;
    color:#8cccf5;background:rgba(36,135,216,.14);font-size:17px;
}
.kpi.green .kpi-icon{color:#7fe0bc;background:rgba(24,163,115,.14)}
.kpi.yellow .kpi-icon{color:#f2c863;background:rgba(229,162,28,.14)}
.kpi.red .kpi-icon{color:#f19aab;background:rgba(221,71,96,.14)}
.kpi.cyan .kpi-icon{color:#7fe1ea;background:rgba(18,169,194,.14)}
.kpi.purple .kpi-icon{color:#b9a7e8;background:rgba(138,107,209,.14)}
.kpi-number{position:relative;z-index:2;font-size:30px;line-height:1;letter-spacing:-1.2px;font-weight:900}
.kpi-label{
    position:relative;z-index:2;display:block;margin-top:14px;color:var(--soft);
    font-size:8px;font-weight:850;letter-spacing:.55px;text-transform:uppercase;
}
.kpi small{position:relative;z-index:2;display:block;margin-top:4px;color:var(--muted);font-size:7px;line-height:1.45}
.strategy{display:grid;grid-template-columns:1fr 1fr 1.15fr;gap:12px;margin-top:14px}
.strategy-card{
    position:relative;min-height:188px;padding:17px;overflow:hidden;
    border:1px solid var(--border);border-radius:22px;background:var(--surface);
    box-shadow:0 15px 38px rgba(0,0,0,.18);
}
.strategy-card:after{
    content:"";position:absolute;top:-50px;right:-50px;width:120px;height:120px;
    border-radius:50%;background:rgba(36,135,216,.06);
}
.strategy-label{position:relative;z-index:2;color:var(--muted);font-size:7px;font-weight:850;letter-spacing:.55px;text-transform:uppercase}
.strategy-value{position:relative;z-index:2;margin-top:13px;font-size:34px;line-height:1;letter-spacing:-1.3px;font-weight:900}
.strategy-card p{position:relative;z-index:2;margin-top:7px;color:var(--soft);font-size:8px;line-height:1.5}
.badge{
    position:relative;z-index:2;display:inline-flex;align-items:center;gap:6px;
    margin-top:12px;padding:7px 9px;border:1px solid transparent;border-radius:999px;
    font-size:7px;font-weight:850;
}
.badge.success{color:#7fe0bc;border-color:rgba(24,163,115,.22);background:rgba(24,163,115,.14)}
.badge.warning{color:#f2c863;border-color:rgba(229,162,28,.22);background:rgba(229,162,28,.14)}
.badge.danger{color:#f19aab;border-color:rgba(221,71,96,.22);background:rgba(221,71,96,.14)}
.badge.info{color:#7fe1ea;border-color:rgba(18,169,194,.22);background:rgba(18,169,194,.14)}
.insights{position:relative;z-index:2;display:flex;flex-direction:column;gap:7px;margin-top:10px}
.insight{
    display:flex;align-items:flex-start;gap:8px;padding:8px;border:1px solid var(--border2);
    border-radius:12px;background:rgba(255,255,255,.04);
}
.insight-icon{
    width:28px;height:28px;flex:0 0 28px;display:grid;place-items:center;border-radius:9px;
    color:#8cccf5;background:rgba(36,135,216,.14);font-size:12px;
}
.insight-icon.success{color:#7fe0bc;background:rgba(24,163,115,.14)}
.insight-icon.warning{color:#f2c863;background:rgba(229,162,28,.14)}
.insight-icon.danger{color:#f19aab;background:rgba(221,71,96,.14)}
.insight-icon.info{color:#7fe1ea;background:rgba(18,169,194,.14)}
.insight strong{display:block;font-size:7px;font-weight:800}
.insight span{display:block;margin-top:2px;color:var(--muted);font-size:6px;line-height:1.4}
.grid{display:grid;grid-template-columns:repeat(12,minmax(0,1fr));gap:14px;margin-top:14px}
.panel{
    overflow:hidden;border:1px solid var(--border);border-radius:30px;background:var(--surface);
    backdrop-filter:blur(18px);box-shadow:var(--shadow);transition:.22s;
}
.panel:hover{background:var(--surface2);transform:translateY(-3px);box-shadow:var(--shadow-lg)}
.s4{grid-column:span 4}.s5{grid-column:span 5}.s6{grid-column:span 6}
.s7{grid-column:span 7}.s8{grid-column:span 8}.s12{grid-column:span 12}
.panel-head{
    display:flex;align-items:center;justify-content:space-between;gap:14px;padding:17px 18px;
    border-bottom:1px solid var(--border2);
    background:radial-gradient(circle at 100% 0,rgba(36,135,216,.08),transparent 17rem),rgba(255,255,255,.025);
}
.panel-title{display:flex;align-items:center;gap:10px}
.panel-icon{
    width:39px;height:39px;flex:0 0 39px;display:grid;place-items:center;border-radius:13px;
    color:#dff4ff;background:linear-gradient(145deg,rgba(36,135,216,.82),rgba(18,169,194,.72));
    box-shadow:0 11px 22px rgba(0,0,0,.2);font-size:16px;
}
.panel h3{margin:0;font-size:13px;letter-spacing:-.25px;font-weight:850}
.panel-head p{margin:4px 0 0;color:var(--muted);font-size:7px;line-height:1.45}
.panel-tag{
    display:inline-flex;align-items:center;gap:6px;padding:7px 9px;border:1px solid var(--border);
    border-radius:999px;background:rgba(255,255,255,.045);color:#aadbf4;
    font-size:7px;font-weight:800;white-space:nowrap;
}
.chart{position:relative;height:330px;padding:16px}
.chart.large{height:390px}.chart.compact{height:290px}
.chart canvas{width:100%!important;height:100%!important}
.risk-summary{display:grid;grid-template-columns:repeat(3,1fr);gap:9px;padding:14px}
.risk-box{padding:11px;border:1px solid var(--border2);border-radius:14px;background:rgba(255,255,255,.04)}
.risk-box span{display:block;color:var(--muted);font-size:6px;font-weight:850;text-transform:uppercase}
.risk-box strong{display:block;margin-top:5px;font-size:18px;font-weight:900}
.risk-box strong.danger{color:#f19aab}.risk-box strong.warning{color:#f2c863}
.critical-list{
    display:flex;flex-direction:column;gap:8px;max-height:420px;overflow:auto;padding:14px;
    scrollbar-width:thin;scrollbar-color:rgba(255,255,255,.16) transparent;
}
.critical{
    display:grid;grid-template-columns:auto minmax(0,1fr) auto;align-items:center;gap:9px;
    padding:10px;border:1px solid var(--border2);border-radius:14px;
    background:rgba(255,255,255,.04);transition:.18s;color:inherit;
}
.critical:hover{border-color:rgba(255,255,255,.15);background:rgba(255,255,255,.07);transform:translateX(3px)}
.priority{
    width:34px;height:34px;display:grid;place-items:center;border-radius:11px;
    color:#f19aab;background:rgba(221,71,96,.14);font-size:14px;
}
.priority.Alta{color:#f2c863;background:rgba(229,162,28,.14)}
.priority.Média,.priority.Baixa,.priority.Não{color:#8cccf5;background:rgba(36,135,216,.14)}
.critical strong{display:block;font-size:8px;font-weight:800}
.critical span{display:block;margin-top:3px;color:var(--muted);font-size:6px;line-height:1.4}
.days{padding:6px 8px;border-radius:999px;color:#fff!important;background:var(--red);font-size:7px!important;font-weight:850;white-space:nowrap}
.empty{padding:47px 18px;text-align:center;color:var(--muted)}
.empty i{display:block;margin-bottom:9px;color:#7fe0bc;font-size:31px}
.empty strong{display:block;color:var(--text);font-size:10px}
.empty span{display:block;margin-top:5px;font-size:7px}
.stock{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px;padding:15px}
.stock-card{
    position:relative;min-height:172px;padding:15px;overflow:hidden;
    border:1px solid var(--border);border-radius:18px;background:rgba(255,255,255,.04);
}
.stock-top{display:flex;align-items:center;justify-content:space-between;gap:8px}
.stock-icon{
    width:37px;height:37px;display:grid;place-items:center;border-radius:12px;
    color:#8cccf5;background:rgba(36,135,216,.14);font-size:16px;
}
.stock-card.toner .stock-icon{color:#b9a7e8;background:rgba(138,107,209,.14)}
.stock-card h4{margin:12px 0 0;font-size:11px;font-weight:850}
.stock-card p{margin:4px 0 0;color:var(--muted);font-size:7px}
.stock-metrics{display:grid;grid-template-columns:repeat(3,1fr);gap:6px;margin-top:12px}
.stock-metric{padding:7px;border:1px solid var(--border2);border-radius:10px;background:rgba(255,255,255,.045)}
.stock-metric span{display:block;color:var(--muted);font-size:5px;font-weight:850;text-transform:uppercase}
.stock-metric strong{display:block;margin-top:4px;font-size:12px;font-weight:900}
.stock-metric.critical strong{color:#f19aab}
.stock-link{display:inline-flex;align-items:center;gap:5px;margin-top:11px;color:#8cccf5;font-size:7px;font-weight:800}
.footer{
    display:flex;align-items:center;justify-content:space-between;gap:15px;margin-top:14px;
    padding:13px 16px;border:1px solid var(--border);border-radius:17px;
    background:rgba(255,255,255,.045);color:var(--muted);
    box-shadow:0 15px 38px rgba(0,0,0,.18);font-size:7px;line-height:1.5;
}
.footer-secure{display:flex;align-items:center;gap:6px;color:#8cccf5;font-weight:750}

@media(max-width:1450px){
    .kpis{grid-template-columns:repeat(3,1fr)}
    .s4,.s5,.s7,.s8{grid-column:span 6}
}
@media(max-width:1150px){
    .strategy{grid-template-columns:1fr 1fr}
    .strategy-card:last-child{grid-column:1/-1}
}
@media(max-width:1050px){
    .header{margin:13px 11px 0}
    .header-content{align-items:flex-start;flex-direction:column}
    .header-side{width:100%;min-width:0;align-items:flex-start}
    .user{text-align:left}
    .actions{justify-content:flex-start}
    .page{padding:14px 11px 28px}
    .hero{grid-template-columns:1fr}
    .grid{grid-template-columns:1fr}
    .s4,.s5,.s6,.s7,.s8,.s12{grid-column:auto}
}
@media(max-width:760px){
    .actions{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));width:100%}
    .action{width:100%}
    .logo{width:61px;height:61px;flex-basis:61px}
    .header h1{font-size:22px}
    .kpis{grid-template-columns:repeat(2,1fr)}
    .strategy{grid-template-columns:1fr}
    .strategy-card:last-child{grid-column:auto}
    .chart{height:300px}
    .chart.large{height:345px}
    .stock{grid-template-columns:1fr}
    .risk-summary{grid-template-columns:1fr}
}
@media(max-width:540px){
    .header{margin-right:7px;margin-left:7px;padding:15px;border-radius:21px}
    .page{padding-right:7px;padding-left:7px}
    .brand{align-items:flex-start;gap:10px}
    .gov{font-size:7px}
    .subtitle{font-size:8px}
    .hero{padding:17px;border-radius:23px}
    .hero h2{font-size:28px}
    .hero p{font-size:9px}
    .kpis{grid-template-columns:1fr}
    .panel-head{align-items:flex-start}
    .panel-tag{display:none}
    .chart{height:280px;padding:11px}
    .chart.large{height:320px}
    .footer{flex-direction:column;align-items:flex-start}
}
@media(prefers-reduced-motion:reduce){
    *,*:before,*:after{animation:none!important;transition:none!important;scroll-behavior:auto!important}
}
</style>
</head>

<body>
<div class="top-strip"></div>
<div class="bg-grid"></div>

<div class="app">

<header class="header">
    <div class="header-content">

        <div class="brand">
            <div class="logo">
                <img
                    src="assets/logobranca.avif"
                    alt="Prefeitura de Extrema"
                    onerror="
                        this.style.display='none';
                        this.nextElementSibling.style.display='block';
                    "
                >
                <div class="logo-fallback">
                    <i class="bi bi-cpu-fill"></i>
                </div>
            </div>

            <div>
                <div class="gov">
                    <i class="bi bi-shield-check"></i>
                    Prefeitura de Extrema • Gerência de Tecnologia
                </div>

                <h1>Central de Inteligência Operacional</h1>

                <div class="subtitle">
                    Análise estratégica de riscos, produtividade, SLA,
                    backlog, tendências e disponibilidade de estoque.
                </div>

                <div class="live">
                    <span class="live-dot"></span>
                    Dados atualizados em <?= date('d/m/Y \à\s H:i') ?>
                </div>
            </div>
        </div>

        <div class="header-side">

            <div class="user">
                <div>
                    <strong><?= e($usuario) ?></strong>
                    <span id="clock">Carregando data e horário...</span>
                </div>

                <div class="avatar">
                    <?= e($iniciais) ?>
                </div>
            </div>

            <nav class="actions">
                <a href="listar_os.php" class="action primary">
                    <i class="bi bi-arrow-left-circle-fill"></i>
                    Ordens de serviço
                </a>

                <a href="dashboard.php" class="action">
                    <i class="bi bi-grid-1x2-fill"></i>
                    Dashboard
                </a>

                <a href="almoxarifado.php" class="action">
                    <i class="bi bi-boxes"></i>
                    Almoxarifado
                </a>

                <a href="tonner.php" class="action">
                    <i class="bi bi-printer-fill"></i>
                    Toner
                </a>

                <button type="button" class="action" onclick="window.print()">
                    <i class="bi bi-printer"></i>
                    Imprimir análise
                </button>
            </nav>
        </div>

    </div>
</header>

<main class="page">

<section class="hero" id="hero">
    <div>
        <div class="hero-label">
            <i class="bi bi-cpu-fill"></i>
            Núcleo analítico da Manutenção TI
        </div>

        <h2>
            Informação transformada em
            <span>prioridade, prevenção e decisão.</span>
        </h2>

        <p>
            Esta central interpreta o comportamento das ordens, compara
            entradas e conclusões, mede o envelhecimento do backlog,
            identifica riscos e cruza a operação com os níveis de estoque.
            Os indicadores apoiam a gestão, mas não substituem a avaliação
            técnica da equipe.
        </p>

        <div class="chips">
            <span class="chip">
                <i class="bi bi-stopwatch-fill"></i>
                SLA médio: <?= $slaMedio ?>h
            </span>

            <span class="chip">
                <i class="bi bi-check2-circle"></i>
                Conclusão: <?= $taxaConclusao ?>%
            </span>

            <span class="chip">
                <i class="bi bi-hourglass-split"></i>
                Backlog: <?= $backlog ?>
            </span>

            <span class="chip">
                <i class="bi bi-alarm-fill"></i>
                Atraso: <?= $taxaAtraso ?>%
            </span>

            <span class="chip">
                <i class="bi bi-calendar3"></i>
                Maior idade: <?= $maiorBacklog ?> dias
            </span>
        </div>
    </div>

    <aside class="score">
        <div class="score-top">
            <span class="score-label">
                <i class="bi bi-speedometer2"></i>
                Score operacional
            </span>

            <span class="score-state">
                <?= e($scoreLabel) ?>
            </span>
        </div>

        <div>
            <div class="score-number">
                <strong><?= $score ?></strong>
                <span>/100</span>
            </div>

            <div class="score-text">
                <?= e($scoreTexto) ?>
            </div>

            <div class="progress">
                <span style="width:<?= $score ?>%"></span>
            </div>
        </div>
    </aside>
</section>

<section class="kpis">

    <article class="kpi">
        <div class="kpi-top">
            <div class="kpi-icon">
                <i class="bi bi-clipboard-data-fill"></i>
            </div>
            <span class="kpi-number"><?= $total ?></span>
        </div>
        <span class="kpi-label">Total de ordens</span>
        <small>Histórico geral registrado na base.</small>
    </article>

    <article class="kpi yellow">
        <div class="kpi-top">
            <div class="kpi-icon">
                <i class="bi bi-tools"></i>
            </div>
            <span class="kpi-number"><?= $andamento ?></span>
        </div>
        <span class="kpi-label">Em andamento</span>
        <small>Demandas atualmente em execução.</small>
    </article>

    <article class="kpi green">
        <div class="kpi-top">
            <div class="kpi-icon">
                <i class="bi bi-check-circle-fill"></i>
            </div>
            <span class="kpi-number"><?= $finalizadas ?></span>
        </div>
        <span class="kpi-label">Finalizadas</span>
        <small><?= $finalizadasMes ?> concluída(s) no mês.</small>
    </article>

    <article class="kpi cyan">
        <div class="kpi-top">
            <div class="kpi-icon">
                <i class="bi bi-box-arrow-up-right"></i>
            </div>
            <span class="kpi-number"><?= $retirada ?></span>
        </div>
        <span class="kpi-label">Pendente retirada</span>
        <small>Equipamentos prontos aguardando responsável.</small>
    </article>

    <article class="kpi red">
        <div class="kpi-top">
            <div class="kpi-icon">
                <i class="bi bi-exclamation-octagon-fill"></i>
            </div>
            <span class="kpi-number"><?= $atrasadas ?></span>
        </div>
        <span class="kpi-label">Fora do prazo</span>
        <small><?= $taxaAtraso ?>% do backlog está vencido.</small>
    </article>

    <article class="kpi purple">
        <div class="kpi-top">
            <div class="kpi-icon">
                <i class="bi bi-lightning-charge-fill"></i>
            </div>
            <span class="kpi-number"><?= $urgentes ?></span>
        </div>
        <span class="kpi-label">Urgentes abertas</span>
        <small>Demandas de prioridade máxima.</small>
    </article>

</section>

<section class="strategy">

    <article class="strategy-card">
        <span class="strategy-label">Saldo operacional do mês</span>

        <div
            class="strategy-value"
            style="color:<?= $saldoMes >= 0 ? '#7fe0bc' : '#f19aab' ?>"
        >
            <?= $saldoMes > 0 ? '+' : '' ?><?= $saldoMes ?>
        </div>

        <p>
            Diferença entre <?= $finalizadasMes ?> finalizações e
            <?= $abertasMes ?> novas ordens no mês atual.
        </p>

        <span class="badge <?= $saldoMes >= 0 ? 'success' : 'danger' ?>">
            <i class="bi bi-activity"></i>
            <?= $saldoMes >= 0
                ? 'Capacidade acima da entrada'
                : 'Entrada acima da capacidade' ?>
        </span>
    </article>

    <article class="strategy-card">
        <span class="strategy-label">Projeção para 30 dias</span>

        <div class="strategy-value">
            <?= $tendenciaBacklog > 0 ? '+' : '' ?>
            <?= $tendenciaBacklog ?>
        </div>

        <p><?= e($tendenciaTexto) ?></p>

        <span class="badge <?= e($tendenciaClass) ?>">
            <i class="bi bi-graph-up-arrow"></i>
            <?= e($tendenciaLabel) ?>
        </span>
    </article>

    <article class="strategy-card">
        <span class="strategy-label">Insights automáticos</span>

        <div class="insights">
            <?php foreach ($insights as $i): ?>
                <div class="insight">
                    <div class="insight-icon <?= e($i['tipo']) ?>">
                        <i class="bi <?= e($i['icone']) ?>"></i>
                    </div>

                    <div>
                        <strong><?= e($i['titulo']) ?></strong>
                        <span><?= e($i['texto']) ?></span>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </article>

</section>

<section class="grid">

    <article class="panel s8">
        <div class="panel-head">
            <div class="panel-title">
                <div class="panel-icon">
                    <i class="bi bi-graph-up-arrow"></i>
                </div>
                <div>
                    <h3>Evolução mensal das demandas</h3>
                    <p>Aberturas e conclusões dos últimos 12 meses.</p>
                </div>
            </div>
            <span class="panel-tag">12 meses</span>
        </div>
        <div class="chart large">
            <canvas id="monthlyChart"></canvas>
        </div>
    </article>

    <article class="panel s4">
        <div class="panel-head">
            <div class="panel-title">
                <div class="panel-icon">
                    <i class="bi bi-pie-chart-fill"></i>
                </div>
                <div>
                    <h3>Composição por status</h3>
                    <p>Participação de cada situação no total.</p>
                </div>
            </div>
        </div>
        <div class="chart large">
            <canvas id="statusChart"></canvas>
        </div>
    </article>

    <article class="panel s8">
        <div class="panel-head">
            <div class="panel-title">
                <div class="panel-icon">
                    <i class="bi bi-activity"></i>
                </div>
                <div>
                    <h3>Ritmo operacional dos últimos 30 dias</h3>
                    <p>Entrada diária comparada às finalizações.</p>
                </div>
            </div>
            <span class="panel-tag">
                Saldo hoje: <?= $saldoHoje > 0 ? '+' : '' ?><?= $saldoHoje ?>
            </span>
        </div>
        <div class="chart large">
            <canvas id="dailyChart"></canvas>
        </div>
    </article>

    <article class="panel s4">
        <div class="panel-head">
            <div class="panel-title">
                <div class="panel-icon">
                    <i class="bi bi-hourglass-split"></i>
                </div>
                <div>
                    <h3>Envelhecimento do backlog</h3>
                    <p>Demandas abertas agrupadas por idade.</p>
                </div>
            </div>
        </div>
        <div class="chart large">
            <canvas id="backlogChart"></canvas>
        </div>
    </article>

    <article class="panel s6">
        <div class="panel-head">
            <div class="panel-title">
                <div class="panel-icon">
                    <i class="bi bi-shield-exclamation"></i>
                </div>
                <div>
                    <h3>Matriz de risco por prioridade</h3>
                    <p>Demandas no prazo e atrasadas.</p>
                </div>
            </div>
        </div>

        <div class="risk-summary">
            <div class="risk-box">
                <span>Urgentes abertas</span>
                <strong class="danger"><?= $urgentes ?></strong>
            </div>
            <div class="risk-box">
                <span>Altas abertas</span>
                <strong class="warning"><?= $altas ?></strong>
            </div>
            <div class="risk-box">
                <span>Backlog total</span>
                <strong><?= $backlog ?></strong>
            </div>
        </div>

        <div class="chart">
            <canvas id="riskChart"></canvas>
        </div>
    </article>

    <article class="panel s6">
        <div class="panel-head">
            <div class="panel-title">
                <div class="panel-icon">
                    <i class="bi bi-exclamation-diamond-fill"></i>
                </div>
                <div>
                    <h3>Volume por prioridade</h3>
                    <p>Concentração de urgência na base.</p>
                </div>
            </div>
        </div>
        <div class="chart">
            <canvas id="priorityChart"></canvas>
        </div>
    </article>

    <article class="panel s4">
        <div class="panel-head">
            <div class="panel-title">
                <div class="panel-icon">
                    <i class="bi bi-pc-display-horizontal"></i>
                </div>
                <div>
                    <h3>Equipamentos recorrentes</h3>
                    <p>Ativos que mais geram manutenção.</p>
                </div>
            </div>
        </div>
        <div class="chart compact">
            <canvas id="equipmentChart"></canvas>
        </div>
    </article>

    <article class="panel s4">
        <div class="panel-head">
            <div class="panel-title">
                <div class="panel-icon">
                    <i class="bi bi-buildings-fill"></i>
                </div>
                <div>
                    <h3>Setores com maior demanda</h3>
                    <p>Ranking geral por setor solicitante.</p>
                </div>
            </div>
        </div>
        <div class="chart compact">
            <canvas id="sectorChart"></canvas>
        </div>
    </article>

    <article class="panel s4">
        <div class="panel-head">
            <div class="panel-title">
                <div class="panel-icon">
                    <i class="bi bi-calendar-week-fill"></i>
                </div>
                <div>
                    <h3>Demanda por dia da semana</h3>
                    <p>Dias com maior pressão operacional.</p>
                </div>
            </div>
        </div>
        <div class="chart compact">
            <canvas id="weekdayChart"></canvas>
        </div>
    </article>

    <article class="panel s5">
        <div class="panel-head">
            <div class="panel-title">
                <div class="panel-icon">
                    <i class="bi bi-people-fill"></i>
                </div>
                <div>
                    <h3>Solicitantes do mês</h3>
                    <p>Pessoas com maior volume de novas ordens.</p>
                </div>
            </div>
            <span class="panel-tag"><?= date('m/Y') ?></span>
        </div>
        <div class="chart">
            <canvas id="requesterChart"></canvas>
        </div>
    </article>

    <article class="panel s7">
        <div class="panel-head">
            <div class="panel-title">
                <div class="panel-icon">
                    <i class="bi bi-exclamation-triangle-fill"></i>
                </div>
                <div>
                    <h3>Ordens críticas para priorização</h3>
                    <p>Ordenadas por prioridade e tempo em aberto.</p>
                </div>
            </div>
            <span class="panel-tag">
                <?= count($criticas) ?> exibida(s)
            </span>
        </div>

        <?php if ($criticas): ?>
            <div class="critical-list">
                <?php foreach ($criticas as $o): ?>
                    <a
                        href="detalhes_os.php?id=<?= $o['id'] ?>"
                        class="critical"
                    >
                        <div
                            class="priority
                            <?= e(explode(' ', $o['prioridade'])[0]) ?>"
                        >
                            <i class="bi bi-lightning-charge-fill"></i>
                        </div>

                        <div>
                            <strong>
                                OS #<?= e($o['numero']) ?>
                                — <?= e($o['equipamento']) ?>
                            </strong>
                            <span>
                                <?= e($o['solicitante']) ?>
                                • <?= e($o['setor']) ?>
                                • <?= e($o['prioridade']) ?>
                                • prazo <?= $o['prazo'] ?> dia(s)
                            </span>
                        </div>

                        <span class="days">
                            <?= $o['dias'] ?> dias
                        </span>
                    </a>
                <?php endforeach; ?>
            </div>
        <?php else: ?>
            <div class="empty">
                <i class="bi bi-check-circle-fill"></i>
                <strong>Nenhuma ordem crítica identificada</strong>
                <span>Não existem demandas abertas fora do prazo.</span>
            </div>
        <?php endif; ?>
    </article>

    <article class="panel s12">
        <div class="panel-head">
            <div class="panel-title">
                <div class="panel-icon">
                    <i class="bi bi-box-seam-fill"></i>
                </div>
                <div>
                    <h3>Risco de disponibilidade de materiais</h3>
                    <p>Almoxarifado e estoque específico de toner.</p>
                </div>
            </div>
            <span class="panel-tag">Dados atuais</span>
        </div>

        <div class="stock">

            <div class="stock-card">
                <div class="stock-top">
                    <div class="stock-icon">
                        <i class="bi bi-boxes"></i>
                    </div>
                    <span class="panel-tag">Almoxarifado</span>
                </div>

                <h4>Materiais e periféricos</h4>
                <p>Produtos utilizados pela equipe de tecnologia.</p>

                <div class="stock-metrics">
                    <div class="stock-metric">
                        <span>Itens</span>
                        <strong><?= $almox['itens'] ?></strong>
                    </div>
                    <div class="stock-metric">
                        <span>Unidades</span>
                        <strong><?= $almox['unidades'] ?></strong>
                    </div>
                    <div class="stock-metric critical">
                        <span>Críticos</span>
                        <strong><?= $almox['criticos'] ?></strong>
                    </div>
                </div>

                <a href="almoxarifado.php" class="stock-link">
                    Abrir almoxarifado
                    <i class="bi bi-arrow-right"></i>
                </a>
            </div>

            <div class="stock-card toner">
                <div class="stock-top">
                    <div class="stock-icon">
                        <i class="bi bi-printer-fill"></i>
                    </div>
                    <span class="panel-tag">Toner</span>
                </div>

                <h4>Suprimentos de impressão</h4>
                <p>Modelos e unidades disponíveis para reposição.</p>

                <div class="stock-metrics">
                    <div class="stock-metric">
                        <span>Modelos</span>
                        <strong><?= $toner['modelos'] ?></strong>
                    </div>
                    <div class="stock-metric">
                        <span>Unidades</span>
                        <strong><?= $toner['unidades'] ?></strong>
                    </div>
                    <div class="stock-metric critical">
                        <span>Críticos</span>
                        <strong><?= $toner['criticos'] ?></strong>
                    </div>
                </div>

                <a href="tonner.php" class="stock-link">
                    Abrir estoque de toner
                    <i class="bi bi-arrow-right"></i>
                </a>
            </div>

        </div>
    </article>

</section>

<footer class="footer">
    <span>
        Prefeitura de Extrema — Gerência de Tecnologia<br>
        Central analítica da Manutenção de Tecnologia da Informação.
    </span>

    <span class="footer-secure">
        <i class="bi bi-shield-lock-fill"></i>
        Indicadores calculados a partir da base institucional
    </span>
</footer>

</main>
</div>

<script>
const monthlyData = <?= js(array_values($mensal)) ?>;
const dailyData = <?= js(array_values($diaria)) ?>;
const statusData = <?= js($grafStatus) ?>;
const priorityData = <?= js($grafPrioridade) ?>;
const equipmentData = <?= js($grafEquip) ?>;
const sectorData = <?= js($grafSetor) ?>;
const requesterData = <?= js($grafSolicitante) ?>;
const weekdayData = <?= js($grafSemana) ?>;
const backlogData = <?= js($grafBacklog) ?>;
const riskData = <?= js($grafRisco) ?>;

Chart.defaults.font.family =
    "'Inter', system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif";

Chart.defaults.color = '#aebdcd';
Chart.defaults.animation.duration = 950;
Chart.defaults.animation.easing = 'easeOutQuart';
Chart.defaults.plugins.legend.labels.usePointStyle = true;
Chart.defaults.plugins.legend.labels.pointStyle = 'circle';
Chart.defaults.plugins.legend.labels.boxWidth = 7;
Chart.defaults.plugins.legend.labels.boxHeight = 7;
Chart.defaults.plugins.legend.labels.padding = 14;
Chart.defaults.plugins.legend.labels.font = {
    size: 9,
    weight: 700
};

Chart.defaults.plugins.tooltip.backgroundColor =
    'rgba(3, 16, 31, .96)';

Chart.defaults.plugins.tooltip.titleColor = '#fff';
Chart.defaults.plugins.tooltip.bodyColor = '#c8d7e5';
Chart.defaults.plugins.tooltip.padding = 12;
Chart.defaults.plugins.tooltip.cornerRadius = 12;

const gridColor = 'rgba(255,255,255,.075)';
const tickColor = '#8999ab';

const colors = {
    blue: '#2487d8',
    cyan: '#12a9c2',
    green: '#18a373',
    yellow: '#e5a21c',
    red: '#dd4760',
    purple: '#8a6bd1',
    slate: '#8292a6'
};

function integerTick(value) {
    return Number.isInteger(value) ? value : '';
}

function gradient(ctx, start, end) {
    const g = ctx.createLinearGradient(0, 0, 0, 360);
    g.addColorStop(0, start);
    g.addColorStop(1, end);
    return g;
}

const emptyPlugin = {
    id: 'emptyPlugin',

    afterDraw(chart) {
        const hasData = chart.data.datasets.some(dataset => {
            return Array.isArray(dataset.data) &&
                dataset.data.some(value => Number(value) > 0);
        });

        if (hasData || !chart.chartArea) {
            return;
        }

        const {ctx, chartArea} = chart;

        ctx.save();
        ctx.fillStyle = '#8292a6';
        ctx.font = "700 11px 'Inter'";
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';

        ctx.fillText(
            'Sem dados disponíveis',
            (chartArea.left + chartArea.right) / 2,
            (chartArea.top + chartArea.bottom) / 2
        );

        ctx.restore();
    }
};

function lineChart(id, labels, a, b, aLabel, bLabel) {
    const canvas = document.getElementById(id);
    const ctx = canvas.getContext('2d');

    return new Chart(canvas, {
        type: 'line',
        plugins: [emptyPlugin],
        data: {
            labels,
            datasets: [
                {
                    label: aLabel,
                    data: a,
                    borderColor: colors.blue,
                    backgroundColor: gradient(
                        ctx,
                        'rgba(36,135,216,.30)',
                        'rgba(36,135,216,.01)'
                    ),
                    borderWidth: 3,
                    fill: true,
                    tension: .38,
                    pointRadius: 3,
                    pointHoverRadius: 6,
                    pointBackgroundColor: '#061b33',
                    pointBorderColor: colors.blue,
                    pointBorderWidth: 2
                },
                {
                    label: bLabel,
                    data: b,
                    borderColor: colors.green,
                    backgroundColor: gradient(
                        ctx,
                        'rgba(24,163,115,.23)',
                        'rgba(24,163,115,.01)'
                    ),
                    borderWidth: 3,
                    fill: true,
                    tension: .38,
                    pointRadius: 3,
                    pointHoverRadius: 6,
                    pointBackgroundColor: '#061b33',
                    pointBorderColor: colors.green,
                    pointBorderWidth: 2
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            interaction: {
                mode: 'index',
                intersect: false
            },
            plugins: {
                legend: {
                    position: 'top',
                    align: 'end'
                }
            },
            scales: {
                x: {
                    grid: {display: false},
                    ticks: {
                        color: tickColor,
                        maxRotation: 0,
                        autoSkip: true,
                        maxTicksLimit: 12,
                        font: {size: 8, weight: 700}
                    },
                    border: {display: false}
                },
                y: {
                    beginAtZero: true,
                    grid: {color: gridColor},
                    ticks: {
                        precision: 0,
                        callback: integerTick,
                        color: tickColor
                    },
                    border: {display: false}
                }
            }
        }
    });
}

lineChart(
    'monthlyChart',
    monthlyData.map(i => i.mes),
    monthlyData.map(i => i.abertas),
    monthlyData.map(i => i.finalizadas),
    'Abertas',
    'Finalizadas'
);

lineChart(
    'dailyChart',
    dailyData.map(i => i.dia),
    dailyData.map(i => i.abertas),
    dailyData.map(i => i.finalizadas),
    'Abertas',
    'Finalizadas'
);

new Chart(document.getElementById('statusChart'), {
    type: 'doughnut',
    plugins: [emptyPlugin],
    data: {
        labels: statusData.map(i => i.label),
        datasets: [{
            data: statusData.map(i => i.value),
            backgroundColor: [
                colors.yellow,
                colors.green,
                colors.cyan,
                colors.red,
                colors.blue
            ],
            borderWidth: 0,
            hoverOffset: 9,
            spacing: 3,
            borderRadius: 5
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        cutout: '69%',
        plugins: {
            legend: {position: 'bottom'}
        }
    }
});

function verticalBar(id, data, colorList = null) {
    return new Chart(document.getElementById(id), {
        type: 'bar',
        plugins: [emptyPlugin],
        data: {
            labels: data.map(i => i.label),
            datasets: [{
                data: data.map(i => i.value),
                backgroundColor: colorList || colors.blue,
                borderWidth: 0,
                borderRadius: 10,
                borderSkipped: false,
                maxBarThickness: 42
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {legend: {display: false}},
            scales: {
                x: {
                    grid: {display: false},
                    ticks: {
                        color: tickColor,
                        font: {size: 8, weight: 700}
                    },
                    border: {display: false}
                },
                y: {
                    beginAtZero: true,
                    grid: {color: gridColor},
                    ticks: {
                        precision: 0,
                        callback: integerTick,
                        color: tickColor
                    },
                    border: {display: false}
                }
            }
        }
    });
}

verticalBar(
    'priorityChart',
    priorityData,
    [
        colors.red,
        '#e17f2d',
        colors.yellow,
        colors.green,
        colors.slate
    ]
);

verticalBar(
    'backlogChart',
    backlogData,
    [
        colors.green,
        colors.cyan,
        colors.yellow,
        '#e17f2d',
        colors.red
    ]
);

function horizontalBar(id, data, color) {
    return new Chart(document.getElementById(id), {
        type: 'bar',
        plugins: [emptyPlugin],
        data: {
            labels: data.map(i => i.label),
            datasets: [{
                data: data.map(i => i.value),
                backgroundColor: color,
                borderWidth: 0,
                borderRadius: 9,
                borderSkipped: false,
                maxBarThickness: 27
            }]
        },
        options: {
            indexAxis: 'y',
            responsive: true,
            maintainAspectRatio: false,
            plugins: {legend: {display: false}},
            scales: {
                x: {
                    beginAtZero: true,
                    grid: {color: gridColor},
                    ticks: {
                        precision: 0,
                        callback: integerTick,
                        color: tickColor
                    },
                    border: {display: false}
                },
                y: {
                    grid: {display: false},
                    ticks: {
                        color: tickColor,
                        font: {size: 8, weight: 700}
                    },
                    border: {display: false}
                }
            }
        }
    });
}

horizontalBar('equipmentChart', equipmentData, colors.cyan);
horizontalBar('sectorChart', sectorData, colors.blue);
horizontalBar('requesterChart', requesterData, colors.green);

new Chart(document.getElementById('riskChart'), {
    type: 'bar',
    plugins: [emptyPlugin],
    data: {
        labels: riskData.map(i => i.prioridade),
        datasets: [
            {
                label: 'No prazo',
                data: riskData.map(i => i.no_prazo),
                backgroundColor: colors.green,
                borderRadius: 8,
                borderSkipped: false
            },
            {
                label: 'Atrasadas',
                data: riskData.map(i => i.atrasada),
                backgroundColor: colors.red,
                borderRadius: 8,
                borderSkipped: false
            }
        ]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: {
                position: 'top',
                align: 'end'
            }
        },
        scales: {
            x: {
                stacked: true,
                grid: {display: false},
                ticks: {
                    color: tickColor,
                    font: {size: 8, weight: 700}
                },
                border: {display: false}
            },
            y: {
                stacked: true,
                beginAtZero: true,
                grid: {color: gridColor},
                ticks: {
                    precision: 0,
                    callback: integerTick,
                    color: tickColor
                },
                border: {display: false}
            }
        }
    }
});

new Chart(document.getElementById('weekdayChart'), {
    type: 'line',
    plugins: [emptyPlugin],
    data: {
        labels: weekdayData.map(i => i.label),
        datasets: [{
            data: weekdayData.map(i => i.value),
            borderColor: colors.purple,
            backgroundColor: 'rgba(138,107,209,.14)',
            borderWidth: 3,
            fill: true,
            tension: .35,
            pointRadius: 4,
            pointHoverRadius: 7,
            pointBackgroundColor: '#061b33',
            pointBorderColor: colors.purple,
            pointBorderWidth: 2
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {legend: {display: false}},
        scales: {
            x: {
                grid: {display: false},
                ticks: {
                    color: tickColor,
                    maxRotation: 0,
                    font: {size: 7, weight: 700}
                },
                border: {display: false}
            },
            y: {
                beginAtZero: true,
                grid: {color: gridColor},
                ticks: {
                    precision: 0,
                    callback: integerTick,
                    color: tickColor
                },
                border: {display: false}
            }
        }
    }
});

function atualizarRelogio() {
    const el = document.getElementById('clock');

    if (!el) {
        return;
    }

    const agora = new Date();

    const data = agora.toLocaleDateString('pt-BR', {
        weekday: 'long',
        day: '2-digit',
        month: 'long',
        year: 'numeric'
    });

    const hora = agora.toLocaleTimeString('pt-BR');

    el.textContent =
        data.charAt(0).toUpperCase() +
        data.slice(1) +
        ' • ' +
        hora;
}

atualizarRelogio();
setInterval(atualizarRelogio, 1000);

const hero = document.getElementById('hero');

if (
    hero &&
    window.matchMedia('(pointer:fine)').matches &&
    !window.matchMedia('(prefers-reduced-motion:reduce)').matches
) {
    hero.addEventListener('mousemove', event => {
        const r = hero.getBoundingClientRect();
        const x = event.clientX - r.left;
        const y = event.clientY - r.top;
        const cx = r.width / 2;
        const cy = r.height / 2;

        hero.style.transform =
            `perspective(1600px)
             rotateX(${((cy - y) / cy) * .28}deg)
             rotateY(${((x - cx) / cx) * .42}deg)`;
    });

    hero.addEventListener('mouseleave', () => {
        hero.style.transform =
            'perspective(1600px) rotateX(0deg) rotateY(0deg)';
    });
}
</script>

</body>
</html>
