<?php
// ============================================================
// ERP - ActSafe | Dashboard Executiva — Diretor Geral
// Visão consolidada de todas as unidades
// Desenvolvido por Antônio da Luz
// ============================================================
require_once '../5_config/config.php';
$usuario = verificarAuth();

// Apenas Diretor Geral e Admin acessam esta tela
if (!in_array($usuario['perfil'], ['admin', 'diretor_geral'])) {
    header('Location: dashboard.php'); exit;
}

$db = getDB();

// ============================================================
// KPIs GLOBAIS
// ============================================================
$total_unidades  = $db->query("SELECT COUNT(*) FROM unidades WHERE ativo=1")->fetchColumn();
$total_equipamentos = $db->query("SELECT COUNT(*) FROM equipamentos")->fetchColumn();
$total_acoes     = $db->query("SELECT COUNT(*) FROM acoes")->fetchColumn();
$acoes_concluidas = $db->query("SELECT COUNT(*) FROM acoes WHERE status='concluida'")->fetchColumn();
$acoes_atrasadas = $db->query("SELECT COUNT(*) FROM acoes WHERE status='atrasada'")->fetchColumn();
$acoes_pendentes = $db->query("SELECT COUNT(*) FROM acoes WHERE status='pendente'")->fetchColumn();
$total_ncs       = $db->query("SELECT COUNT(*) FROM nao_conformidades")->fetchColumn();
$ncs_abertas     = $db->query("SELECT COUNT(*) FROM nao_conformidades WHERE status='aberta'")->fetchColumn();
$total_docs      = $db->query("SELECT COUNT(*) FROM documentos")->fetchColumn();
$total_inspecoes = $db->query("SELECT COUNT(*) FROM inspecoes")->fetchColumn() ?? 0;
$inspecoes_concluidas = $db->query("SELECT COUNT(*) FROM inspecoes WHERE status='concluida'")->fetchColumn() ?? 0;

$conformidade_geral = $total_acoes > 0 ? round(($acoes_concluidas / $total_acoes) * 100) : 0;

// ============================================================
// COMPARATIVO POR UNIDADE
// ============================================================
$stmt = $db->query("
    SELECT
        u.id,
        u.nome,
        u.cidade,
        u.estado,
        u.gestor_nome,
        u.tecnico_nome,
        COUNT(DISTINCT a.id) AS total_acoes,
        SUM(CASE WHEN a.status = 'concluida' THEN 1 ELSE 0 END) AS concluidas,
        SUM(CASE WHEN a.status = 'atrasada' THEN 1 ELSE 0 END) AS atrasadas,
        SUM(CASE WHEN a.status = 'pendente' THEN 1 ELSE 0 END) AS pendentes,
        COUNT(DISTINCT e.id) AS total_equipamentos,
        COUNT(DISTINCT nc.id) AS total_ncs
    FROM unidades u
    LEFT JOIN acoes a ON a.unidade_id = u.id
    LEFT JOIN equipamentos e ON e.unidade_id = u.id
    LEFT JOIN nao_conformidades nc ON nc.unidade_id = u.id
    WHERE u.ativo = 1
    GROUP BY u.id, u.nome, u.cidade, u.estado, u.gestor_nome, u.tecnico_nome
    ORDER BY u.nome ASC
");
$unidades_comparativo = $stmt->fetchAll();

// ============================================================
// CONFORMIDADE POR NORMA (global)
// ============================================================
$normas = ['NR 10', 'NR 12', 'SPDA'];
$conformidade_normas = [];
foreach ($normas as $norma) {
    $total_n = $db->prepare("SELECT COUNT(*) FROM acoes WHERE norma=?");
    $total_n->execute([$norma]);
    $t = (int)$total_n->fetchColumn();

    $concl_n = $db->prepare("SELECT COUNT(*) FROM acoes WHERE norma=? AND status='concluida'");
    $concl_n->execute([$norma]);
    $c = (int)$concl_n->fetchColumn();

    $conformidade_normas[$norma] = [
        'total'      => $t,
        'concluidas' => $c,
        'pct'        => $t > 0 ? round(($c / $t) * 100) : 0,
    ];
}

// ============================================================
// AÇÕES CRÍTICAS (atrasadas) — top 10
// ============================================================
$acoes_criticas = $db->query("
    SELECT a.*, u.nome AS unidade_nome
    FROM acoes a
    LEFT JOIN unidades u ON u.id = a.unidade_id
    WHERE a.status = 'atrasada'
    ORDER BY a.data_vencimento ASC
    LIMIT 10
")->fetchAll();

// ============================================================
// ÚLTIMAS INSPEÇÕES CONCLUÍDAS
// ============================================================
try {
    $ultimas_inspecoes = $db->query("
        SELECT i.*, u.nome AS unidade_nome
        FROM inspecoes i
        LEFT JOIN unidades u ON u.id = i.unidade_id
        WHERE i.status = 'concluida'
        ORDER BY i.data_conclusao DESC
        LIMIT 5
    ")->fetchAll();
} catch (Exception $e) {
    $ultimas_inspecoes = [];
}

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

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

  <!-- CABEÇALHO EXECUTIVO -->
  <div class="flex items-center justify-between flex-wrap gap-3">
    <div>
      <h1 class="text-2xl font-bold text-actsafe-text flex items-center gap-2">
        <i data-lucide="bar-chart-3" class="w-6 h-6 text-actsafe-blue"></i>
        Dashboard Executiva
      </h1>
      <p class="text-sm text-gray-500 mt-0.5">Visão consolidada de todas as unidades — <?= date('d/m/Y H:i') ?></p>
    </div>
    <a href="dashboard.php" class="btn-outline text-sm">
      <i data-lucide="layout-dashboard" class="w-4 h-4"></i> Dashboard Operacional
    </a>
  </div>

  <!-- KPIs GLOBAIS -->
  <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-4">
    <div class="card text-center">
      <p class="text-3xl font-extrabold text-actsafe-blue"><?= $total_unidades ?></p>
      <p class="text-xs text-gray-500 mt-1 font-medium">Unidades Ativas</p>
    </div>
    <div class="card text-center">
      <p class="text-3xl font-extrabold text-green-600"><?= $conformidade_geral ?>%</p>
      <p class="text-xs text-gray-500 mt-1 font-medium">Conformidade Geral</p>
    </div>
    <div class="card text-center">
      <p class="text-3xl font-extrabold text-gray-700"><?= $total_acoes ?></p>
      <p class="text-xs text-gray-500 mt-1 font-medium">Total de Ações</p>
    </div>
    <div class="card text-center">
      <p class="text-3xl font-extrabold text-red-500"><?= $acoes_atrasadas ?></p>
      <p class="text-xs text-gray-500 mt-1 font-medium">Ações Atrasadas</p>
    </div>
    <div class="card text-center">
      <p class="text-3xl font-extrabold text-orange-500"><?= $ncs_abertas ?></p>
      <p class="text-xs text-gray-500 mt-1 font-medium">NCs Abertas</p>
    </div>
    <div class="card text-center">
      <p class="text-3xl font-extrabold text-purple-600"><?= $total_equipamentos ?></p>
      <p class="text-xs text-gray-500 mt-1 font-medium">Equipamentos</p>
    </div>
  </div>

  <!-- CONFORMIDADE POR NORMA -->
  <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
    <?php
    $norma_cores = [
        'NR 10' => ['bg' => 'bg-yellow-500', 'text' => 'text-yellow-600', 'light' => 'bg-yellow-50', 'border' => 'border-yellow-200'],
        'NR 12' => ['bg' => 'bg-blue-500', 'text' => 'text-actsafe-blue', 'light' => 'bg-blue-50', 'border' => 'border-blue-200'],
        'SPDA'  => ['bg' => 'bg-purple-500', 'text' => 'text-purple-600', 'light' => 'bg-purple-50', 'border' => 'border-purple-200'],
    ];
    foreach ($conformidade_normas as $norma => $dados):
        $cor = $norma_cores[$norma];
        $pct = $dados['pct'];
        $cor_pct = $pct >= 80 ? 'text-green-600' : ($pct >= 50 ? 'text-yellow-600' : 'text-red-600');
    ?>
    <div class="card border <?= $cor['border'] ?> <?= $cor['light'] ?>">
      <div class="flex items-center justify-between mb-3">
        <span class="font-bold text-sm <?= $cor['text'] ?>"><?= $norma ?></span>
        <span class="text-2xl font-extrabold <?= $cor_pct ?>"><?= $pct ?>%</span>
      </div>
      <div class="w-full bg-gray-200 rounded-full h-2 mb-2">
        <div class="<?= $cor['bg'] ?> h-2 rounded-full transition-all" style="width:<?= $pct ?>%"></div>
      </div>
      <p class="text-xs text-gray-500"><?= $dados['concluidas'] ?> de <?= $dados['total'] ?> ações concluídas</p>
    </div>
    <?php endforeach; ?>
  </div>

  <!-- COMPARATIVO POR UNIDADE -->
  <div class="card p-0 overflow-hidden">
    <div class="px-5 py-4 border-b border-gray-100 flex items-center gap-2">
      <i data-lucide="building-2" class="w-4 h-4 text-actsafe-blue"></i>
      <h2 class="font-semibold text-actsafe-text text-sm">Comparativo por Unidade</h2>
    </div>
    <?php if (empty($unidades_comparativo)): ?>
    <div class="text-center py-10 text-gray-400 text-sm">Nenhuma unidade cadastrada.</div>
    <?php else: ?>
    <div class="overflow-x-auto">
      <table class="w-full text-sm">
        <thead class="bg-gray-50 border-b border-gray-100">
          <tr>
            <th class="text-left px-4 py-3 font-semibold text-gray-600">Unidade</th>
            <th class="text-left px-4 py-3 font-semibold text-gray-600 hidden md:table-cell">Gestor</th>
            <th class="text-center px-4 py-3 font-semibold text-gray-600">Conformidade</th>
            <th class="text-center px-4 py-3 font-semibold text-gray-600">Ações</th>
            <th class="text-center px-4 py-3 font-semibold text-gray-600 hidden sm:table-cell">Atrasadas</th>
            <th class="text-center px-4 py-3 font-semibold text-gray-600 hidden lg:table-cell">Equipamentos</th>
            <th class="text-center px-4 py-3 font-semibold text-gray-600 hidden lg:table-cell">NCs</th>
            <th class="text-center px-4 py-3 font-semibold text-gray-600">Status</th>
          </tr>
        </thead>
        <tbody class="divide-y divide-gray-50">
          <?php foreach ($unidades_comparativo as $u):
            $pct_u = $u['total_acoes'] > 0 ? round(($u['concluidas'] / $u['total_acoes']) * 100) : 0;
            $status_cor = $pct_u >= 80 ? 'bg-green-100 text-green-700' : ($pct_u >= 50 ? 'bg-yellow-100 text-yellow-700' : ($u['total_acoes'] > 0 ? 'bg-red-100 text-red-700' : 'bg-gray-100 text-gray-500'));
            $status_txt = $pct_u >= 80 ? 'Conforme' : ($pct_u >= 50 ? 'Atenção' : ($u['total_acoes'] > 0 ? 'Crítico' : 'Sem dados'));
          ?>
          <tr class="table-row">
            <td class="px-4 py-3">
              <p class="font-semibold text-actsafe-text text-sm"><?= sanitizar($u['nome']) ?></p>
              <p class="text-xs text-gray-400"><?= sanitizar($u['cidade'] ?? '') ?><?= $u['estado'] ? '/' . sanitizar($u['estado']) : '' ?></p>
            </td>
            <td class="px-4 py-3 hidden md:table-cell">
              <span class="text-xs text-gray-600"><?= sanitizar($u['gestor_nome'] ?? '—') ?></span>
              <?php if (!empty($u['tecnico_nome'])): ?>
              <span class="text-xs text-gray-400 block"><?= sanitizar($u['tecnico_nome']) ?></span>
              <?php endif; ?>
            </td>
            <td class="px-4 py-3">
              <div class="flex flex-col items-center gap-1">
                <span class="font-bold text-sm <?= $pct_u >= 80 ? 'text-green-600' : ($pct_u >= 50 ? 'text-yellow-600' : 'text-red-500') ?>"><?= $pct_u ?>%</span>
                <div class="w-16 bg-gray-200 rounded-full h-1.5">
                  <div class="h-1.5 rounded-full <?= $pct_u >= 80 ? 'bg-green-500' : ($pct_u >= 50 ? 'bg-yellow-500' : 'bg-red-500') ?>" style="width:<?= $pct_u ?>%"></div>
                </div>
              </div>
            </td>
            <td class="px-4 py-3 text-center font-semibold text-gray-700"><?= $u['total_acoes'] ?></td>
            <td class="px-4 py-3 text-center hidden sm:table-cell">
              <?php if ($u['atrasadas'] > 0): ?>
              <span class="text-xs bg-red-100 text-red-600 px-2 py-0.5 rounded-full font-bold"><?= $u['atrasadas'] ?></span>
              <?php else: ?>
              <span class="text-xs text-gray-400">—</span>
              <?php endif; ?>
            </td>
            <td class="px-4 py-3 text-center text-gray-600 hidden lg:table-cell"><?= $u['total_equipamentos'] ?></td>
            <td class="px-4 py-3 text-center hidden lg:table-cell">
              <?php if ($u['total_ncs'] > 0): ?>
              <span class="text-xs bg-orange-100 text-orange-600 px-2 py-0.5 rounded-full font-semibold"><?= $u['total_ncs'] ?></span>
              <?php else: ?>
              <span class="text-xs text-gray-400">0</span>
              <?php endif; ?>
            </td>
            <td class="px-4 py-3 text-center">
              <span class="text-xs px-2.5 py-1 rounded-full font-semibold <?= $status_cor ?>"><?= $status_txt ?></span>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
    <?php endif; ?>
  </div>

  <div class="grid grid-cols-1 lg:grid-cols-2 gap-5">

    <!-- AÇÕES CRÍTICAS (ATRASADAS) -->
    <div class="card p-0 overflow-hidden">
      <div class="px-5 py-4 border-b border-gray-100 flex items-center gap-2">
        <i data-lucide="alert-triangle" class="w-4 h-4 text-red-500"></i>
        <h2 class="font-semibold text-actsafe-text text-sm">Ações Críticas — Atrasadas</h2>
        <?php if ($acoes_atrasadas > 0): ?>
        <span class="ml-auto text-xs bg-red-100 text-red-600 px-2 py-0.5 rounded-full font-bold"><?= $acoes_atrasadas ?></span>
        <?php endif; ?>
      </div>
      <?php if (empty($acoes_criticas)): ?>
      <div class="text-center py-10 text-gray-400 text-sm">
        <i data-lucide="check-circle" class="w-8 h-8 mx-auto mb-2 text-green-400"></i>
        Nenhuma ação atrasada!
      </div>
      <?php else: ?>
      <div class="divide-y divide-gray-50">
        <?php foreach ($acoes_criticas as $ac): ?>
        <div class="px-5 py-3 flex items-start gap-3">
          <span class="w-2 h-2 rounded-full bg-red-500 mt-1.5 flex-shrink-0"></span>
          <div class="flex-1 min-w-0">
            <p class="text-sm font-medium text-gray-800 truncate"><?= sanitizar($ac['titulo'] ?? $ac['descricao'] ?? '—') ?></p>
            <p class="text-xs text-gray-500 mt-0.5">
              <?= sanitizar($ac['unidade_nome'] ?? '—') ?> · <?= sanitizar($ac['norma'] ?? '') ?>
              <?php if (!empty($ac['data_vencimento'])): ?> · Prazo: <?= formatarData($ac['data_vencimento']) ?><?php endif; ?>
            </p>
          </div>
          <span class="text-xs bg-red-100 text-red-600 px-2 py-0.5 rounded-full font-semibold flex-shrink-0">Atrasada</span>
        </div>
        <?php endforeach; ?>
      </div>
      <?php endif; ?>
    </div>

    <!-- ÚLTIMAS INSPEÇÕES CONCLUÍDAS -->
    <div class="card p-0 overflow-hidden">
      <div class="px-5 py-4 border-b border-gray-100 flex items-center gap-2">
        <i data-lucide="clipboard-check" class="w-4 h-4 text-green-500"></i>
        <h2 class="font-semibold text-actsafe-text text-sm">Últimas Inspeções Concluídas</h2>
        <span class="ml-auto text-xs text-gray-400"><?= $inspecoes_concluidas ?> de <?= $total_inspecoes ?></span>
      </div>
      <?php if (empty($ultimas_inspecoes)): ?>
      <div class="text-center py-10 text-gray-400 text-sm">
        <i data-lucide="clipboard" class="w-8 h-8 mx-auto mb-2 opacity-40"></i>
        Nenhuma inspeção concluída ainda.
      </div>
      <?php else: ?>
      <div class="divide-y divide-gray-50">
        <?php foreach ($ultimas_inspecoes as $ins): ?>
        <div class="px-5 py-3 flex items-start gap-3">
          <span class="w-2 h-2 rounded-full bg-green-500 mt-1.5 flex-shrink-0"></span>
          <div class="flex-1 min-w-0">
            <p class="text-sm font-medium text-gray-800 truncate"><?= sanitizar($ins['titulo'] ?? '—') ?></p>
            <p class="text-xs text-gray-500 mt-0.5">
              <?= sanitizar($ins['unidade_nome'] ?? '—') ?> · <?= sanitizar($ins['tecnico_nome'] ?? '') ?>
              <?php if ($ins['data_conclusao']): ?> · <?= formatarData(substr($ins['data_conclusao'], 0, 10)) ?><?php endif; ?>
            </p>
          </div>
          <a href="inspecao_relatorio.php?id=<?= $ins['id'] ?>"
             class="text-xs bg-blue-50 text-actsafe-blue px-2 py-0.5 rounded font-medium hover:bg-blue-100 flex-shrink-0">
            PDF
          </a>
        </div>
        <?php endforeach; ?>
      </div>
      <?php endif; ?>
    </div>

  </div>

  <!-- RESUMO EXECUTIVO -->
  <div class="card bg-gradient-to-r from-actsafe-blue to-blue-700 text-white">
    <div class="flex items-center gap-3 mb-4">
      <i data-lucide="trending-up" class="w-5 h-5 opacity-80"></i>
      <h2 class="font-bold text-sm uppercase tracking-wide opacity-90">Resumo Executivo</h2>
    </div>
    <div class="grid grid-cols-2 sm:grid-cols-4 gap-4 text-center">
      <div>
        <p class="text-2xl font-extrabold"><?= $acoes_concluidas ?></p>
        <p class="text-xs opacity-70 mt-0.5">Ações Concluídas</p>
      </div>
      <div>
        <p class="text-2xl font-extrabold"><?= $acoes_pendentes ?></p>
        <p class="text-xs opacity-70 mt-0.5">Ações Pendentes</p>
      </div>
      <div>
        <p class="text-2xl font-extrabold"><?= $total_docs ?></p>
        <p class="text-xs opacity-70 mt-0.5">Documentos</p>
      </div>
      <div>
        <p class="text-2xl font-extrabold"><?= $total_ncs ?></p>
        <p class="text-xs opacity-70 mt-0.5">Não Conformidades</p>
      </div>
    </div>
  </div>

</div>

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