<?php
require_once '../5_config/config.php';
$usuario = verificarAuth();
$db = getDB();
$perfil = $usuario['perfil'];

// ============================================================
// DADOS 100% REAIS — baseados no schema exato do banco
// ============================================================

// Total de unidades ativas
$total_unidades = (int) $db->query("SELECT COUNT(*) FROM unidades WHERE ativo = 1")->fetchColumn();

// ============================================================
// EQUIPAMENTOS NR 12 — checklist real (sem coluna 'ativo' na tabela)
// ============================================================
$stmt_eq = $db->query("
    SELECT id, nome, tag, cod,
           (proj_conceito + execucao + procedimento + validacao + laudos) AS checklist_ok
    FROM equipamentos
    ORDER BY (proj_conceito + execucao + procedimento + validacao + laudos) DESC
");
$equipamentos_todos = $stmt_eq->fetchAll();
$total_equipamentos  = count($equipamentos_todos);
$equipamentos_ok     = 0;
foreach ($equipamentos_todos as $eq) {
    if ((int)$eq['checklist_ok'] >= 5) $equipamentos_ok++;
}
$pct_eq = $total_equipamentos > 0 ? round($equipamentos_ok / $total_equipamentos * 100) : 0;

// ============================================================
// AÇÕES REAIS — NR10, NR12, SPDA
// ============================================================
$stmt_acoes = $db->query("
    SELECT norma,
           COUNT(*) AS total,
           SUM(status = 'concluida')                         AS concluidas,
           SUM(status IN ('pendente','em_andamento'))        AS pendentes,
           SUM(status = 'atrasada')                         AS atrasadas
    FROM acoes
    GROUP BY norma
");
$kpis_norma = ['NR10'=>['total'=>0,'concluidas'=>0,'pendentes'=>0,'atrasadas'=>0,'pct'=>0],
               'NR12'=>['total'=>0,'concluidas'=>0,'pendentes'=>0,'atrasadas'=>0,'pct'=>0],
               'SPDA'=>['total'=>0,'concluidas'=>0,'pendentes'=>0,'atrasadas'=>0,'pct'=>0]];
foreach ($stmt_acoes->fetchAll() as $row) {
    $n = $row['norma'];
    if (!isset($kpis_norma[$n])) continue;
    $kpis_norma[$n]['total']     = (int)$row['total'];
    $kpis_norma[$n]['concluidas']= (int)$row['concluidas'];
    $kpis_norma[$n]['pendentes'] = (int)$row['pendentes'];
    $kpis_norma[$n]['atrasadas'] = (int)$row['atrasadas'];
    $kpis_norma[$n]['pct']       = $row['total'] > 0 ? round($row['concluidas'] / $row['total'] * 100) : 0;
}

$total_concluidas = $kpis_norma['NR10']['concluidas'] + $kpis_norma['NR12']['concluidas'] + $kpis_norma['SPDA']['concluidas'];
$total_pendentes  = $kpis_norma['NR10']['pendentes']  + $kpis_norma['NR12']['pendentes']  + $kpis_norma['SPDA']['pendentes'];
$total_atrasadas  = $kpis_norma['NR10']['atrasadas']  + $kpis_norma['NR12']['atrasadas']  + $kpis_norma['SPDA']['atrasadas'];

// ============================================================
// AÇÕES RECENTES
// ============================================================
$acoes_recentes = $db->query("
    SELECT a.titulo, a.norma, a.status, a.data_vencimento,
           u.codigo AS unidade_codigo
    FROM acoes a
    LEFT JOIN unidades u ON u.id = a.unidade_id
    ORDER BY a.atualizado_em DESC
    LIMIT 10
")->fetchAll();

// ============================================================
// NÃO CONFORMIDADES
// ============================================================
$nc_abertas       = (int) $db->query("SELECT COUNT(*) FROM nao_conformidades WHERE status = 'aberta'")->fetchColumn();
$nc_em_tratamento = (int) $db->query("SELECT COUNT(*) FROM nao_conformidades WHERE status = 'em_tratamento'")->fetchColumn();
$nc_total         = (int) $db->query("SELECT COUNT(*) FROM nao_conformidades")->fetchColumn();

// ============================================================
// TOP 5 EQUIPAMENTOS
// ============================================================
$equipamentos_top = array_slice($equipamentos_todos, 0, 5);

$pagina_titulo = 'Dashboard';
require_once '../1_frontend/layout.php';
?>

<div class="space-y-6">

  <!-- Cabeçalho -->
  <div>
    <h1 class="text-2xl font-bold text-actsafe-text">Dashboard</h1>
    <p class="text-sm text-gray-500 mt-0.5">Visão geral da conformidade normativa — <?= date('d/m/Y H:i') ?></p>
  </div>

  <!-- KPIs Principais -->
  <div class="grid grid-cols-2 lg:grid-cols-4 gap-4">
    <div class="card flex flex-col gap-2">
      <div class="w-10 h-10 rounded-xl bg-blue-50 flex items-center justify-center">
        <i data-lucide="building-2" class="w-5 h-5 text-actsafe-blue"></i>
      </div>
      <p class="text-3xl font-bold text-actsafe-blue"><?= $total_unidades ?></p>
      <p class="text-sm text-gray-500">Unidades Monitoradas</p>
    </div>
    <div class="card flex flex-col gap-2">
      <div class="w-10 h-10 rounded-xl bg-green-50 flex items-center justify-center">
        <i data-lucide="check-circle" class="w-5 h-5 text-actsafe-green"></i>
      </div>
      <p class="text-3xl font-bold text-actsafe-green"><?= $total_concluidas ?></p>
      <p class="text-sm text-gray-500">Ações Concluídas</p>
    </div>
    <div class="card flex flex-col gap-2">
      <div class="w-10 h-10 rounded-xl bg-yellow-50 flex items-center justify-center">
        <i data-lucide="clock" class="w-5 h-5 text-yellow-500"></i>
      </div>
      <p class="text-3xl font-bold text-yellow-500"><?= $total_pendentes ?></p>
      <p class="text-sm text-gray-500">Ações Pendentes</p>
    </div>
    <div class="card flex flex-col gap-2">
      <div class="w-10 h-10 rounded-xl bg-red-50 flex items-center justify-center">
        <i data-lucide="alert-circle" class="w-5 h-5 text-actsafe-red"></i>
      </div>
      <p class="text-3xl font-bold text-actsafe-red"><?= $total_atrasadas ?></p>
      <p class="text-sm text-gray-500">Ações Atrasadas</p>
    </div>
  </div>

  <!-- Cards por Norma -->
  <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
    <?php
    $normas_cfg = [
      'NR10' => ['nome'=>'Segurança Elétrica',      'icon'=>'zap',           'borda'=>'border-yellow-400','cor_icon'=>'text-yellow-500','bg_icon'=>'bg-yellow-50','href'=>'nr10.php'],
      'NR12' => ['nome'=>'Máquinas e Equipamentos', 'icon'=>'cog',           'borda'=>'border-orange-400','cor_icon'=>'text-orange-500','bg_icon'=>'bg-orange-50','href'=>'nr12.php'],
      'SPDA' => ['nome'=>'Proteção Atmosférica',    'icon'=>'cloud-lightning','borda'=>'border-blue-400',  'cor_icon'=>'text-blue-500',  'bg_icon'=>'bg-blue-50',  'href'=>'spda.php'],
    ];
    foreach ($normas_cfg as $sigla => $cfg):
      $kpi = $kpis_norma[$sigla];
      $cor_pct = $kpi['pct'] >= 80 ? 'text-actsafe-green' : ($kpi['pct'] >= 50 ? 'text-yellow-500' : 'text-actsafe-red');
      $cor_bar = $kpi['pct'] >= 80 ? 'bg-actsafe-green'   : ($kpi['pct'] >= 50 ? 'bg-yellow-400'   : 'bg-actsafe-red');
    ?>
    <a href="<?= $cfg['href'] ?>" class="card border-l-4 <?= $cfg['borda'] ?> hover:shadow-md transition-shadow block">
      <div class="flex items-center gap-3 mb-3">
        <div class="w-10 h-10 rounded-xl <?= $cfg['bg_icon'] ?> flex items-center justify-center">
          <i data-lucide="<?= $cfg['icon'] ?>" class="w-5 h-5 <?= $cfg['cor_icon'] ?>"></i>
        </div>
        <div>
          <p class="font-bold text-actsafe-text"><?= $sigla ?></p>
          <p class="text-xs text-gray-500"><?= $cfg['nome'] ?></p>
        </div>
        <span class="ml-auto text-xs text-gray-400"><?= $kpi['total'] ?> ação(ões)</span>
      </div>
      <div class="flex items-center justify-between text-sm mb-1.5">
        <span class="text-gray-600">Conformidade</span>
        <span class="font-bold <?= $cor_pct ?>"><?= $kpi['pct'] ?>%</span>
      </div>
      <div class="w-full bg-gray-100 rounded-full h-2 mb-3">
        <div class="h-2 rounded-full <?= $cor_bar ?>" style="width:<?= $kpi['pct'] ?>%"></div>
      </div>
      <div class="flex gap-3 text-xs text-gray-500">
        <span class="flex items-center gap-1"><i data-lucide="clock" class="w-3 h-3 text-yellow-500"></i> <?= $kpi['pendentes'] ?> pendentes</span>
        <span class="flex items-center gap-1"><i data-lucide="alert-triangle" class="w-3 h-3 text-red-500"></i> <?= $kpi['atrasadas'] ?> atrasadas</span>
      </div>
    </a>
    <?php endforeach; ?>
  </div>

  <!-- Equipamentos NR 12 — Progresso do Checklist -->
  <?php if ($total_equipamentos > 0): ?>
  <div class="card border-l-4 border-orange-400">
    <div class="flex items-center justify-between mb-3">
      <h2 class="font-semibold text-actsafe-text flex items-center gap-2">
        <i data-lucide="cog" class="w-4 h-4 text-orange-500"></i>
        Equipamentos NR 12 — Checklist de Adequação
      </h2>
      <a href="nr12.php" class="text-xs text-actsafe-blue hover:underline">Ver todos</a>
    </div>
    <div class="flex items-center justify-between text-sm mb-2">
      <span class="text-gray-600"><?= $total_equipamentos ?> equipamento(s) cadastrado(s)</span>
      <span class="font-bold <?= $pct_eq >= 80 ? 'text-actsafe-green' : ($pct_eq >= 50 ? 'text-yellow-500' : 'text-actsafe-red') ?>">
        <?= $equipamentos_ok ?>/<?= $total_equipamentos ?> completo(s) — <?= $pct_eq ?>%
      </span>
    </div>
    <div class="w-full bg-gray-100 rounded-full h-3 mb-4">
      <div class="h-3 rounded-full <?= $pct_eq >= 80 ? 'bg-actsafe-green' : ($pct_eq >= 50 ? 'bg-yellow-400' : 'bg-actsafe-red') ?>"
           style="width:<?= $pct_eq ?>%"></div>
    </div>
    <!-- Lista dos top equipamentos -->
    <div class="space-y-2">
      <?php foreach ($equipamentos_top as $eq):
        $pct_item = round((int)$eq['checklist_ok'] / 5 * 100);
        $cor_item = $pct_item >= 80 ? 'bg-actsafe-green' : ($pct_item >= 50 ? 'bg-yellow-400' : 'bg-actsafe-red');
      ?>
      <div class="flex items-center gap-3 p-2 bg-gray-50 rounded-lg">
        <div class="flex-1 min-w-0">
          <p class="text-sm font-medium text-actsafe-text truncate"><?= sanitizar($eq['nome']) ?></p>
          <p class="text-xs text-gray-400"><?= sanitizar($eq['cod']) ?><?= $eq['tag'] ? ' · ' . sanitizar($eq['tag']) : '' ?></p>
        </div>
        <div class="flex items-center gap-2 flex-shrink-0">
          <div class="w-20 bg-gray-200 rounded-full h-2">
            <div class="h-2 rounded-full <?= $cor_item ?>" style="width:<?= $pct_item ?>%"></div>
          </div>
          <span class="text-xs font-bold text-gray-600 w-8 text-right"><?= (int)$eq['checklist_ok'] ?>/5</span>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
  <?php endif; ?>

  <!-- Ações Recentes + Alertas -->
  <div class="grid grid-cols-1 lg:grid-cols-3 gap-4">

    <!-- Ações Recentes -->
    <div class="card lg:col-span-2">
      <div class="flex items-center justify-between mb-4">
        <h2 class="font-semibold text-actsafe-text flex items-center gap-2">
          <i data-lucide="trending-up" class="w-4 h-4 text-actsafe-blue"></i> Ações Recentes
        </h2>
        <a href="nr10.php" class="text-xs text-actsafe-blue hover:underline">Ver todas</a>
      </div>
      <?php if (empty($acoes_recentes)): ?>
      <p class="text-sm text-gray-400 text-center py-6">Nenhuma ação registrada ainda.</p>
      <?php else: ?>
      <div class="space-y-2">
        <?php foreach ($acoes_recentes as $a):
          $badge_norma = $a['norma']==='NR10' ? 'bg-yellow-100 text-yellow-700' : ($a['norma']==='NR12' ? 'bg-orange-100 text-orange-700' : 'bg-blue-100 text-blue-700');
          $labels_status = ['pendente'=>'Pendente','em_andamento'=>'Em And.','concluida'=>'Concluída','atrasada'=>'Atrasada'];
        ?>
        <div class="flex items-center gap-3 py-2 border-b border-gray-50 last:border-0 rounded-lg px-2">
          <span class="text-[10px] font-bold px-2 py-0.5 rounded-md flex-shrink-0 <?= $badge_norma ?>"><?= $a['norma'] ?></span>
          <div class="flex-1 min-w-0">
            <p class="text-sm font-medium text-actsafe-text truncate"><?= sanitizar($a['titulo']) ?></p>
            <p class="text-xs text-gray-400"><?= sanitizar($a['unidade_codigo'] ?? '—') ?> · Venc: <?= formatarData($a['data_vencimento']) ?></p>
          </div>
          <span class="badge-status badge-<?= $a['status'] ?> flex-shrink-0 text-xs">
            <?= $labels_status[$a['status']] ?? $a['status'] ?>
          </span>
        </div>
        <?php endforeach; ?>
      </div>
      <?php endif; ?>
    </div>

    <!-- Alertas -->
    <div class="card">
      <h2 class="font-semibold text-actsafe-text flex items-center gap-2 mb-4">
        <i data-lucide="bell" class="w-4 h-4 text-actsafe-orange"></i> Alertas
      </h2>
      <div class="space-y-3">
        <?php if ($total_atrasadas > 0): ?>
        <div class="flex items-start gap-2 bg-red-50 rounded-lg p-3">
          <i data-lucide="alert-circle" class="w-4 h-4 text-red-500 flex-shrink-0 mt-0.5"></i>
          <div>
            <p class="text-sm font-semibold text-red-700"><?= $total_atrasadas ?> ação(ões) atrasada(s)</p>
            <p class="text-xs text-red-500">Requerem atenção imediata</p>
          </div>
        </div>
        <?php endif; ?>
        <?php if ($nc_abertas > 0): ?>
        <div class="flex items-start gap-2 bg-orange-50 rounded-lg p-3">
          <i data-lucide="alert-triangle" class="w-4 h-4 text-orange-500 flex-shrink-0 mt-0.5"></i>
          <div>
            <p class="text-sm font-semibold text-orange-700"><?= $nc_abertas ?> não conformidade(s) aberta(s)</p>
            <p class="text-xs text-orange-500">Aguardando tratamento</p>
          </div>
        </div>
        <?php endif; ?>
        <?php if ($nc_em_tratamento > 0): ?>
        <div class="flex items-start gap-2 bg-yellow-50 rounded-lg p-3">
          <i data-lucide="clock" class="w-4 h-4 text-yellow-500 flex-shrink-0 mt-0.5"></i>
          <div>
            <p class="text-sm font-semibold text-yellow-700"><?= $nc_em_tratamento ?> em tratamento</p>
            <p class="text-xs text-yellow-500">Em andamento</p>
          </div>
        </div>
        <?php endif; ?>
        <?php if ($total_atrasadas == 0 && $nc_abertas == 0 && $nc_em_tratamento == 0): ?>
        <div class="flex items-center gap-2 bg-green-50 rounded-lg p-3">
          <i data-lucide="check-circle" class="w-4 h-4 text-green-500"></i>
          <p class="text-sm text-green-700 font-medium">Tudo em conformidade!</p>
        </div>
        <?php endif; ?>
        <a href="nao_conformidades.php" class="btn-outline w-full justify-center text-xs mt-2">
          <i data-lucide="alert-triangle" class="w-3.5 h-3.5"></i> Não Conformidades (<?= $nc_total ?>)
        </a>
      </div>
    </div>
  </div>

</div>

<?php require_once '../1_frontend/layout_footer.php'; ?>
