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

// ============================================================
// CRIAR NOVA REQUISIÇÃO
// ============================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['acao'] ?? '') === 'criar') {
    $titulo         = limpar($_POST['titulo'] ?? '');
    $descricao      = limpar($_POST['descricao'] ?? '');
    $norma          = limpar($_POST['norma'] ?? '');
    $unidade_id     = (int)($_POST['unidade_id'] ?? 0);
    $equipamento_id = (int)($_POST['equipamento_id'] ?? 0) ?: null;
    $tecnico_nome   = limpar($_POST['tecnico_nome'] ?? '');
    $tecnico_email  = limpar($_POST['tecnico_email'] ?? '');
    $data_limite    = limpar($_POST['data_limite'] ?? '') ?: null;

    if ($titulo && $norma && $unidade_id) {
        $token = bin2hex(random_bytes(20));
        $db->prepare("INSERT INTO inspecoes (token,titulo,descricao,norma,unidade_id,equipamento_id,tecnico_nome,tecnico_email,criado_por,data_limite) VALUES (?,?,?,?,?,?,?,?,?,?)")
           ->execute([$token,$titulo,$descricao,$norma,$unidade_id,$equipamento_id,$tecnico_nome,$tecnico_email,$usuario['id'],$data_limite]);
        header('Location: inspecoes.php?msg=success:Requisi%C3%A7%C3%A3o+criada+com+sucesso!'); exit;
    } else {
        header('Location: inspecoes.php?msg=error:Preencha+os+campos+obrigat%C3%B3rios.'); exit;
    }
}

// ============================================================
// REVOGAR REQUISIÇÃO (inativa, mas mantém no histórico)
// ============================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['acao'] ?? '') === 'revogar') {
    $id = (int)($_POST['id'] ?? 0);
    if ($id && temPermissao('editar', $perfil)) {
        $db->prepare("UPDATE inspecoes SET status='cancelada' WHERE id=? AND status IN ('aguardando','em_andamento')")->execute([$id]);
    }
    header('Location: inspecoes.php?msg=success:Requisi%C3%A7%C3%A3o+revogada.'); exit;
}

// ============================================================
// APAGAR REQUISIÇÃO (exclusão física)
// ============================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['acao'] ?? '') === 'apagar') {
    $id = (int)($_POST['id'] ?? 0);
    if ($id && temPermissao('excluir', $perfil)) {
        $db->prepare("DELETE FROM inspecao_fotos WHERE inspecao_id=?")->execute([$id]);
        $db->prepare("DELETE FROM inspecoes WHERE id=?")->execute([$id]);
    }
    header('Location: inspecoes.php?msg=success:Requisi%C3%A7%C3%A3o+apagada.'); exit;
}

// ============================================================
// LER MENSAGEM PRG
// ============================================================
$msg_sucesso = $msg_erro = '';
if (isset($_GET['msg'])) {
    $raw = urldecode($_GET['msg']);
    if (str_starts_with($raw, 'success:')) $msg_sucesso = substr($raw, 8);
    elseif (str_starts_with($raw, 'error:'))  $msg_erro   = substr($raw, 6);
}

// ============================================================
// LISTAR
// ============================================================
$inspecoes = $db->query("
    SELECT i.*, u.codigo AS unidade_codigo, u.nome AS unidade_nome,
           e.nome AS equipamento_nome,
           usr.nome AS criado_por_nome
    FROM inspecoes i
    LEFT JOIN unidades u ON u.id = i.unidade_id
    LEFT JOIN equipamentos e ON e.id = i.equipamento_id
    LEFT JOIN usuarios usr ON usr.id = i.criado_por
    ORDER BY i.criado_em DESC
")->fetchAll();

$unidades     = $db->query("SELECT id,codigo,nome FROM unidades WHERE ativo=1 ORDER BY nome")->fetchAll();
$equipamentos = $db->query("SELECT id,cod,nome FROM equipamentos ORDER BY nome")->fetchAll();

$pagina_titulo = 'Inspeções Mobile';
require_once '../1_frontend/layout.php';
?>

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

  <!-- Cabeçalho -->
  <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
    <div>
      <h1 class="text-2xl font-bold text-actsafe-text flex items-center gap-2">
        <i data-lucide="smartphone" class="w-6 h-6 text-actsafe-blue"></i>
        Inspeções Mobile
      </h1>
      <p class="text-sm text-gray-500 mt-0.5">Gere links públicos para inspeções em campo — sem login, câmera nativa</p>
    </div>
    <?php if (temPermissao('criar', $perfil)): ?>
    <button onclick="document.getElementById('modal-nova').classList.remove('hidden')"
            class="btn-primary flex items-center gap-2 self-start">
      <i data-lucide="plus" class="w-4 h-4"></i> Nova Requisição
    </button>
    <?php endif; ?>
  </div>

  <!-- Alertas -->
  <?php if ($msg_sucesso): ?>
  <div class="bg-green-50 border border-green-200 text-green-800 rounded-xl px-4 py-3 flex items-center gap-2">
    <i data-lucide="check-circle" class="w-4 h-4 text-green-500 flex-shrink-0"></i>
    <?= sanitizar($msg_sucesso) ?>
  </div>
  <?php endif; ?>
  <?php if ($msg_erro): ?>
  <div class="bg-red-50 border border-red-200 text-red-800 rounded-xl px-4 py-3 flex items-center gap-2">
    <i data-lucide="alert-circle" class="w-4 h-4 text-red-500 flex-shrink-0"></i>
    <?= sanitizar($msg_erro) ?>
  </div>
  <?php endif; ?>

  <!-- Estatísticas rápidas -->
  <?php
    $total      = count($inspecoes);
    $aguardando = count(array_filter($inspecoes, fn($i) => $i['status']==='aguardando'));
    $andamento  = count(array_filter($inspecoes, fn($i) => $i['status']==='em_andamento'));
    $concluidas = count(array_filter($inspecoes, fn($i) => $i['status']==='concluida'));
    $revogadas  = count(array_filter($inspecoes, fn($i) => $i['status']==='cancelada'));
  ?>
  <div class="grid grid-cols-2 sm:grid-cols-4 gap-3">
    <div class="card p-4 text-center">
      <p class="text-2xl font-bold text-actsafe-blue"><?= $total ?></p>
      <p class="text-xs text-gray-500 mt-0.5">Total</p>
    </div>
    <div class="card p-4 text-center">
      <p class="text-2xl font-bold text-yellow-500"><?= $aguardando ?></p>
      <p class="text-xs text-gray-500 mt-0.5">Aguardando</p>
    </div>
    <div class="card p-4 text-center">
      <p class="text-2xl font-bold text-blue-500"><?= $andamento ?></p>
      <p class="text-xs text-gray-500 mt-0.5">Em Andamento</p>
    </div>
    <div class="card p-4 text-center">
      <p class="text-2xl font-bold text-actsafe-green"><?= $concluidas ?></p>
      <p class="text-xs text-gray-500 mt-0.5">Concluídas</p>
    </div>
  </div>

  <!-- Lista de Inspeções -->
  <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-list" class="w-4 h-4 text-actsafe-blue"></i>
      <h2 class="font-semibold text-actsafe-text">Requisições de Inspeção</h2>
      <span class="ml-auto text-xs text-gray-400"><?= $total ?> registro(s)</span>
    </div>

    <?php if (empty($inspecoes)): ?>
    <div class="py-12 text-center text-gray-400">
      <i data-lucide="clipboard" class="w-10 h-10 mx-auto mb-3 opacity-30"></i>
      <p class="text-sm">Nenhuma inspeção criada ainda.</p>
      <p class="text-xs mt-1">Clique em "Nova Requisição" para começar.</p>
    </div>
    <?php else: ?>
    <div class="divide-y divide-gray-50">
      <?php foreach ($inspecoes as $ins):
        $sc_map = [
          'aguardando'   => ['bg'=>'bg-yellow-100','text'=>'text-yellow-700','label'=>'Aguardando'],
          'em_andamento' => ['bg'=>'bg-blue-100',  'text'=>'text-blue-700',  'label'=>'Em Andamento'],
          'concluida'    => ['bg'=>'bg-green-100', 'text'=>'text-green-700', 'label'=>'Concluída'],
          'cancelada'    => ['bg'=>'bg-red-50',    'text'=>'text-red-500',   'label'=>'Revogada'],
        ];
        $sc = $sc_map[$ins['status']] ?? $sc_map['aguardando'];
        $norma_cfg = [
          'NR10' => ['icon'=>'zap',           'bg'=>'bg-yellow-50','ic'=>'text-yellow-500','badge'=>'bg-yellow-100 text-yellow-700'],
          'NR12' => ['icon'=>'cog',           'bg'=>'bg-orange-50','ic'=>'text-orange-500','badge'=>'bg-orange-100 text-orange-700'],
          'SPDA' => ['icon'=>'cloud-lightning','bg'=>'bg-blue-50',  'ic'=>'text-blue-500',  'badge'=>'bg-blue-100 text-blue-700'],
        ];
        $nc = $norma_cfg[$ins['norma']] ?? $norma_cfg['NR10'];
        $link = APP_URL . '/inspecao.php?token=' . $ins['token'];
        $ativo = in_array($ins['status'], ['aguardando','em_andamento']);
      ?>
      <div class="px-5 py-4 hover:bg-gray-50/50 transition-colors">
        <div class="flex flex-col sm:flex-row sm:items-start gap-3">

          <!-- Ícone norma -->
          <div class="w-10 h-10 rounded-xl flex-shrink-0 flex items-center justify-center <?= $nc['bg'] ?>">
            <i data-lucide="<?= $nc['icon'] ?>" class="w-5 h-5 <?= $nc['ic'] ?>"></i>
          </div>

          <!-- Dados principais -->
          <div class="flex-1 min-w-0">
            <div class="flex flex-wrap items-center gap-2 mb-1">
              <span class="font-semibold text-actsafe-text"><?= sanitizar($ins['titulo']) ?></span>
              <span class="text-[10px] font-bold px-2 py-0.5 rounded-md <?= $nc['badge'] ?>"><?= $ins['norma'] ?></span>
              <span class="text-[10px] font-semibold px-2 py-0.5 rounded-md <?= $sc['bg'] ?> <?= $sc['text'] ?>"><?= $sc['label'] ?></span>
            </div>
            <p class="text-xs text-gray-500 mb-2">
              <span class="font-medium"><?= sanitizar($ins['unidade_codigo'] ?? '') ?></span> — <?= sanitizar($ins['unidade_nome'] ?? '') ?>
              <?php if ($ins['equipamento_nome']): ?> · <?= sanitizar($ins['equipamento_nome']) ?><?php endif; ?>
              <?php if ($ins['tecnico_nome']): ?> · Técnico: <span class="font-medium"><?= sanitizar($ins['tecnico_nome']) ?></span><?php endif; ?>
              <?php if ($ins['data_limite']): ?> · Prazo: <span class="font-medium"><?= formatarData($ins['data_limite']) ?></span><?php endif; ?>
            </p>

            <!-- Link público (só se ativo) -->
            <?php if ($ativo): ?>
            <div class="flex items-center gap-2 bg-actsafe-blue/5 border border-actsafe-blue/20 rounded-lg px-3 py-2 mt-1">
              <i data-lucide="link" class="w-3.5 h-3.5 text-actsafe-blue flex-shrink-0"></i>
              <span class="text-xs text-actsafe-blue font-mono truncate flex-1"><?= $link ?></span>
              <button onclick="copiarLink('<?= htmlspecialchars($link, ENT_QUOTES) ?>', this)"
                      class="flex-shrink-0 text-xs bg-actsafe-blue text-white px-2 py-1 rounded-md hover:bg-blue-700 transition-colors flex items-center gap-1">
                <i data-lucide="copy" class="w-3 h-3"></i> Copiar
              </button>
              <a href="https://wa.me/?text=<?= urlencode('Olá! Acesse o link para realizar a inspeção: ' . $link) ?>"
                 target="_blank"
                 class="flex-shrink-0 text-xs bg-green-500 text-white px-2 py-1 rounded-md hover:bg-green-600 transition-colors flex items-center gap-1">
                <i data-lucide="message-circle" class="w-3 h-3"></i> WhatsApp
              </a>
            </div>
            <?php elseif ($ins['status'] === 'concluida'): ?>
            <div class="flex items-center gap-2 mt-1">
              <!-- VER RESULTADO -->
            <a href="inspecao_resultado.php?id=<?= $ins['id'] ?>"
               class="text-xs bg-actsafe-green text-white px-3 py-1.5 rounded-lg hover:bg-green-700 transition-colors flex items-center gap-1">
              <i data-lucide="file-text" class="w-3.5 h-3.5"></i> Resultado
            </a>
            <!-- VER PDF -->
            <a href="inspecao_relatorio.php?id=<?= $ins['id'] ?>"
               class="text-xs bg-red-500 text-white px-3 py-1.5 rounded-lg hover:bg-red-600 transition-colors flex items-center gap-1">
              <i data-lucide="file-pdf" class="w-3.5 h-3.5"></i> PDF
            </a>
              <span class="text-xs text-gray-400">Concluída em: <?= $ins['concluida_em'] ? date('d/m/Y H:i', strtotime($ins['concluida_em'])) : '—' ?></span>
            </div>
            <?php elseif ($ins['status'] === 'cancelada'): ?>
            <p class="text-xs text-red-400 mt-1 flex items-center gap-1">
              <i data-lucide="ban" class="w-3 h-3"></i> Requisição revogada — link inativo
            </p>
            <?php endif; ?>
          </div>

          <!-- Botões de ação -->
          <div class="flex items-center gap-1.5 flex-shrink-0">
            <?php if ($ins['status'] === 'concluida'): ?>
            <!-- VER RELATÓRIO -->
            <a href="inspecao_relatorio.php?id=<?= $ins['id'] ?>"
               class="flex items-center gap-1 text-xs text-actsafe-green bg-green-50 hover:bg-green-100 px-2.5 py-1.5 rounded-lg border border-green-200 transition-colors font-medium text-decoration-none">
              <i data-lucide="file-text" class="w-3.5 h-3.5"></i> PDF
            </a>
            <?php endif; ?>

            <?php if ($ativo && temPermissao('editar', $perfil)): ?>
            <!-- REVOGAR -->
            <form method="POST" onsubmit="return confirm('Revogar esta requisição de inspeção? O link ficará inativo.')">
              <input type="hidden" name="acao" value="revogar">
              <input type="hidden" name="id" value="<?= $ins['id'] ?>">
              <button type="submit"
                      class="flex items-center gap-1 text-xs text-orange-600 hover:text-orange-800 px-2.5 py-1.5 rounded-lg hover:bg-orange-50 border border-orange-200 transition-colors font-medium">
                <i data-lucide="shield-off" class="w-3.5 h-3.5"></i> Revogar
              </button>
            </form>
            <?php endif; ?>

            <?php if (temPermissao('excluir', $perfil)): ?>
            <!-- APAGAR -->
            <form method="POST" onsubmit="return confirm('Apagar permanentemente esta requisição? Esta ação não pode ser desfeita.')">
              <input type="hidden" name="acao" value="apagar">
              <input type="hidden" name="id" value="<?= $ins['id'] ?>">
              <button type="submit"
                      class="flex items-center gap-1 text-xs text-red-500 hover:text-red-700 px-2.5 py-1.5 rounded-lg hover:bg-red-50 border border-red-200 transition-colors font-medium">
                <i data-lucide="trash-2" class="w-3.5 h-3.5"></i> Apagar
              </button>
            </form>
            <?php endif; ?>
          </div>

        </div>
      </div>
      <?php endforeach; ?>
    </div>
    <?php endif; ?>
  </div>
</div>

<!-- MODAL: NOVA REQUISIÇÃO -->
<div id="modal-nova" class="hidden fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
  <div class="bg-white rounded-2xl shadow-2xl w-full max-w-lg max-h-[90vh] overflow-y-auto">
    <div class="flex items-center justify-between px-6 py-4 border-b border-gray-100 sticky top-0 bg-white rounded-t-2xl">
      <h3 class="font-bold text-actsafe-text flex items-center gap-2">
        <i data-lucide="smartphone" class="w-5 h-5 text-actsafe-blue"></i>
        Nova Requisição de Inspeção
      </h3>
      <button onclick="document.getElementById('modal-nova').classList.add('hidden')"
              class="text-gray-400 hover:text-gray-600 transition-colors p-1">
        <i data-lucide="x" class="w-5 h-5"></i>
      </button>
    </div>
    <form method="POST" class="px-6 py-5 space-y-4">
      <input type="hidden" name="acao" value="criar">

      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">Título da Inspeção <span class="text-red-500">*</span></label>
        <input type="text" name="titulo" required placeholder="Ex: Inspeção Elétrica Painel Principal"
               class="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-actsafe-blue/30 focus:border-actsafe-blue">
      </div>

      <div class="grid grid-cols-2 gap-3">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">Norma <span class="text-red-500">*</span></label>
          <select name="norma" required class="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-actsafe-blue/30 focus:border-actsafe-blue">
            <option value="">Selecione</option>
            <option value="NR10">NR 10 — Elétrica</option>
            <option value="NR12">NR 12 — Máquinas</option>
            <option value="SPDA">SPDA — Atmosférico</option>
          </select>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">Prazo</label>
          <input type="date" name="data_limite"
                 class="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-actsafe-blue/30 focus:border-actsafe-blue">
        </div>
      </div>

      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">Unidade Fabril <span class="text-red-500">*</span></label>
        <select name="unidade_id" required class="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-actsafe-blue/30 focus:border-actsafe-blue">
          <option value="">Selecione a unidade</option>
          <?php foreach ($unidades as $u): ?>
          <option value="<?= $u['id'] ?>"><?= sanitizar($u['codigo']) ?> — <?= sanitizar($u['nome']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>

      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">Equipamento (opcional)</label>
        <select name="equipamento_id" class="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-actsafe-blue/30 focus:border-actsafe-blue">
          <option value="">Nenhum equipamento específico</option>
          <?php foreach ($equipamentos as $eq): ?>
          <option value="<?= $eq['id'] ?>"><?= sanitizar($eq['cod']) ?> — <?= sanitizar($eq['nome']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>

      <div class="grid grid-cols-2 gap-3">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">Nome do Técnico</label>
          <input type="text" name="tecnico_nome" placeholder="Nome completo"
                 class="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-actsafe-blue/30 focus:border-actsafe-blue">
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">E-mail / WhatsApp</label>
          <input type="text" name="tecnico_email" placeholder="contato@email.com"
                 class="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-actsafe-blue/30 focus:border-actsafe-blue">
        </div>
      </div>

      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">Descrição / Instruções</label>
        <textarea name="descricao" rows="3" placeholder="Descreva o que deve ser inspecionado, pontos de atenção, etc."
                  class="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-actsafe-blue/30 focus:border-actsafe-blue resize-none"></textarea>
      </div>

      <div class="flex gap-3 pt-2">
        <button type="button" onclick="document.getElementById('modal-nova').classList.add('hidden')"
                class="btn-outline flex-1 justify-center">Cancelar</button>
        <button type="submit" class="btn-primary flex-1 justify-center flex items-center gap-2">
          <i data-lucide="link" class="w-4 h-4"></i> Gerar Link
        </button>
      </div>
    </form>
  </div>
</div>

<script>
function copiarLink(link, btn) {
  navigator.clipboard.writeText(link).then(() => {
    const orig = btn.innerHTML;
    btn.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 11 4 16"/></svg> Copiado!';
    btn.classList.add('bg-green-600');
    setTimeout(() => { btn.innerHTML = orig; btn.classList.remove('bg-green-600'); }, 2000);
  });
}
</script>

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