<?php
// ============================================================
// ERP - ActSafe | Tela Pública de Inspeção Mobile
// Acesso via token único — SEM LOGIN NECESSÁRIO
// Desenvolvido por Antônio da Luz
// ============================================================
require_once '5_config/config.php';

$token = limpar($_GET['token'] ?? '');
if (!$token) {
    http_response_code(404);
    die('<!DOCTYPE html><html lang="pt-BR"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Link Inválido</title><style>*{box-sizing:border-box;margin:0;padding:0}body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;display:flex;align-items:center;justify-content:center;min-height:100vh;background:#f1f5f9}.box{text-align:center;padding:2rem;background:#fff;border-radius:1rem;box-shadow:0 4px 20px rgba(0,0,0,.08);max-width:320px;width:90%}.icon{font-size:3rem;margin-bottom:1rem}h2{color:#1e293b;margin:0 0 .5rem;font-size:1.2rem}p{color:#64748b;font-size:.9rem}</style></head><body><div class="box"><div class="icon">🔗</div><h2>Link Inválido</h2><p>Este link de inspeção é inválido ou expirou.</p></div></body></html>');
}

$db = getDB();
$stmt = $db->prepare("SELECT i.*, u.codigo AS unidade_codigo, u.nome AS unidade_nome, e.nome AS equipamento_nome, e.cod AS equipamento_cod FROM inspecoes i LEFT JOIN unidades u ON u.id=i.unidade_id LEFT JOIN equipamentos e ON e.id=i.equipamento_id WHERE i.token=? LIMIT 1");
$stmt->execute([$token]);
$ins = $stmt->fetch();

if (!$ins) {
    http_response_code(404);
    die('<!DOCTYPE html><html lang="pt-BR"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Não Encontrada</title><style>*{box-sizing:border-box;margin:0;padding:0}body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;display:flex;align-items:center;justify-content:center;min-height:100vh;background:#f1f5f9}.box{text-align:center;padding:2rem;background:#fff;border-radius:1rem;box-shadow:0 4px 20px rgba(0,0,0,.08);max-width:320px;width:90%}</style></head><body><div class="box"><div style="font-size:3rem;margin-bottom:1rem">🔍</div><h2 style="color:#1e293b;margin:0 0 .5rem;font-size:1.2rem">Inspeção não encontrada</h2><p style="color:#64748b;font-size:.9rem">Verifique o link e tente novamente.</p></div></body></html>');
}

if ($ins['status'] === 'cancelada') {
    die('<!DOCTYPE html><html lang="pt-BR"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Revogada</title><style>*{box-sizing:border-box;margin:0;padding:0}body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;display:flex;align-items:center;justify-content:center;min-height:100vh;background:#fef2f2}.box{text-align:center;padding:2rem;background:#fff;border-radius:1rem;box-shadow:0 4px 20px rgba(0,0,0,.08);max-width:320px;width:90%}</style></head><body><div class="box"><div style="font-size:3rem;margin-bottom:1rem">🚫</div><h2 style="color:#991b1b;margin:0 0 .5rem;font-size:1.2rem">Requisição Revogada</h2><p style="color:#64748b;font-size:.9rem">Esta inspeção foi revogada pelo responsável.</p></div></body></html>');
}

if ($ins['status'] === 'concluida') {
    die('<!DOCTYPE html><html lang="pt-BR"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Concluída</title><style>*{box-sizing:border-box;margin:0;padding:0}body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;display:flex;align-items:center;justify-content:center;min-height:100vh;background:#f0fdf4}.box{text-align:center;padding:2rem;background:#fff;border-radius:1rem;box-shadow:0 4px 20px rgba(0,0,0,.08);max-width:320px;width:90%}</style></head><body><div class="box"><div style="font-size:3rem;margin-bottom:1rem">✅</div><h2 style="color:#065f46;margin:0 0 .5rem;font-size:1.2rem">Inspeção Concluída</h2><p style="color:#64748b;font-size:.9rem">Esta inspeção já foi finalizada. Obrigado!</p></div></body></html>');
}

if ($ins['status'] === 'aguardando') {
    $db->prepare("UPDATE inspecoes SET status='em_andamento', iniciada_em=NOW() WHERE token=?")->execute([$token]);
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1, user-scalable=no">
  <meta name="mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="default">
  <meta name="theme-color" content="#0F4C81">
  <title>Inspeção — <?= sanitizar($ins['titulo']) ?></title>
  <script src="https://cdn.tailwindcss.com"></script>
  <style>
    * { -webkit-tap-highlight-color: transparent; box-sizing: border-box; }
    html, body { height: 100%; overscroll-behavior: none; }

    /* TEMA CLARO — fundo cinza suave */
    body {
      background: #f0f4f8;
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
      color: #1e293b;
    }

    /* Header azul ActSafe — compacto */
    .header-actsafe {
      background: #0F4C81;
      padding: 12px 16px 10px;
      position: sticky; top: 0; z-index: 10;
    }

    /* Steps */
    .step-bar { display: flex; align-items: center; gap: 6px; margin-top: 8px; }
    .step-dot { width: 7px; height: 7px; border-radius: 50%; background: rgba(255,255,255,0.3); transition: all 0.3s; flex-shrink: 0; }
    .step-dot.active { background: #fff; width: 20px; border-radius: 4px; }
    .step-dot.done { background: rgba(255,255,255,0.65); }
    .step-line { flex: 1; height: 1px; background: rgba(255,255,255,0.2); }
    .step-line.done { background: rgba(255,255,255,0.5); }

    /* Cards brancos */
    .card {
      background: #fff;
      border-radius: 16px;
      box-shadow: 0 1px 6px rgba(0,0,0,0.07);
      overflow: hidden;
    }
    .card-header {
      padding: 12px 14px 8px;
      border-bottom: 1px solid #f1f5f9;
      font-size: 11px;
      font-weight: 700;
      text-transform: uppercase;
      letter-spacing: .05em;
      color: #94a3b8;
    }

    /* Área de foto — fundo cinza claro */
    .foto-area {
      aspect-ratio: 4/3;
      background: #e8edf2;
      position: relative;
      cursor: pointer;
      overflow: hidden;
    }
    .foto-area img { width: 100%; height: 100%; object-fit: cover; }
    .foto-placeholder {
      position: absolute; inset: 0;
      display: flex; flex-direction: column;
      align-items: center; justify-content: center; gap: 10px;
    }
    .camera-ring {
      width: 64px; height: 64px;
      border-radius: 50%;
      background: rgba(15,76,129,0.1);
      border: 2px solid rgba(15,76,129,0.2);
      display: flex; align-items: center; justify-content: center;
      transition: all 0.15s;
    }
    .foto-area:active .camera-ring { background: rgba(15,76,129,0.18); transform: scale(0.95); }
    .foto-number {
      position: absolute; top: 8px; left: 8px;
      background: rgba(15,76,129,0.85);
      color: #fff; font-size: 10px; font-weight: 700;
      padding: 2px 7px; border-radius: 20px;
    }
    .foto-remove {
      position: absolute; top: 8px; right: 8px;
      width: 26px; height: 26px;
      background: rgba(192,57,43,0.9);
      border-radius: 50%; border: none; cursor: pointer;
      display: flex; align-items: center; justify-content: center;
    }
    .foto-retake {
      position: absolute; bottom: 8px; right: 8px;
      background: rgba(0,0,0,0.5);
      color: #fff; font-size: 10px; font-weight: 600;
      padding: 3px 9px; border-radius: 20px;
      border: none; cursor: pointer;
      display: flex; align-items: center; gap: 3px;
    }

    /* Campos abaixo da foto */
    .foto-fields { padding: 12px 14px 14px; background: #fff; }
    .foto-fields label { font-size: 11px; font-weight: 600; color: #64748b; display: block; margin-bottom: 5px; }
    .foto-fields input,
    .foto-fields textarea {
      width: 100%; border: 1.5px solid #e2e8f0; border-radius: 10px;
      padding: 9px 11px; font-size: 13px; line-height: 1.5;
      resize: none; outline: none; transition: border-color 0.2s;
      font-family: inherit; color: #1e293b; background: #f8fafc;
    }
    .foto-fields input:focus,
    .foto-fields textarea:focus { border-color: #0F4C81; background: #fff; box-shadow: 0 0 0 3px rgba(15,76,129,0.08); }

    /* Toggle NC */
    .nc-toggle { display: flex; gap: 6px; margin-bottom: 8px; }
    .nc-btn {
      flex: 1; padding: 7px; border-radius: 9px; border: 1.5px solid #e2e8f0;
      font-size: 12px; font-weight: 600; cursor: pointer; transition: all 0.15s;
      display: flex; align-items: center; justify-content: center; gap: 4px;
      background: #f8fafc; color: #64748b;
    }
    .nc-btn.conforme { border-color: #10b981; background: #ecfdf5; color: #065f46; }
    .nc-btn.nao-conforme { border-color: #ef4444; background: #fef2f2; color: #991b1b; }

    /* Scroll horizontal de fotos */
    .fotos-scroll {
      display: flex; gap: 10px;
      overflow-x: auto; padding: 4px 16px 4px;
      scroll-snap-type: x mandatory;
      -webkit-overflow-scrolling: touch;
      scrollbar-width: none;
    }
    .fotos-scroll::-webkit-scrollbar { display: none; }
    .foto-item { flex: 0 0 calc(100vw - 48px); max-width: 500px; scroll-snap-align: start; }

    /* Botão principal */
    .btn-main {
      background: #0F4C81;
      color: #fff; border: none; border-radius: 14px;
      padding: 15px 24px; font-size: 15px; font-weight: 700;
      cursor: pointer; width: 100%; transition: all 0.15s;
      display: flex; align-items: center; justify-content: center; gap: 8px;
      box-shadow: 0 3px 12px rgba(15,76,129,0.25);
    }
    .btn-main:active { transform: scale(0.98); background: #0d4070; }
    .btn-main:disabled { opacity: 0.5; cursor: not-allowed; transform: none; }

    .btn-secondary {
      background: #fff; color: #0F4C81;
      border: 1.5px solid #0F4C81; border-radius: 14px;
      padding: 13px 20px; font-size: 14px; font-weight: 600;
      cursor: pointer; transition: all 0.15s;
      display: flex; align-items: center; justify-content: center; gap: 6px;
    }
    .btn-secondary:active { background: #f0f4f8; }

    .btn-success {
      background: #1A7A4A;
      color: #fff; border: none; border-radius: 14px;
      padding: 16px 24px; font-size: 16px; font-weight: 700;
      cursor: pointer; width: 100%; transition: all 0.15s;
      box-shadow: 0 3px 14px rgba(26,122,74,0.3);
      display: flex; align-items: center; justify-content: center; gap: 8px;
    }
    .btn-success:active { transform: scale(0.98); }

    /* Telas */
    .screen { display: none; }
    .screen.active { display: flex; flex-direction: column; min-height: 100vh; }

    /* Dots indicadores */
    .foto-dots { display: flex; gap: 5px; justify-content: center; padding: 6px 0; }
    .foto-dot { width: 6px; height: 6px; border-radius: 50%; background: #cbd5e1; transition: all 0.2s; }
    .foto-dot.active { background: #0F4C81; width: 16px; border-radius: 3px; }
    .foto-dot.filled { background: #64748b; }

    /* Inputs de texto gerais */
    .field-input {
      width: 100%; border: 1.5px solid #e2e8f0; border-radius: 12px;
      padding: 11px 13px; font-size: 14px; line-height: 1.5;
      resize: none; outline: none; transition: border-color 0.2s;
      font-family: inherit; color: #1e293b; background: #f8fafc;
    }
    .field-input:focus { border-color: #0F4C81; background: #fff; box-shadow: 0 0 0 3px rgba(15,76,129,0.08); }
    .field-label { font-size: 12px; font-weight: 600; color: #475569; display: block; margin-bottom: 6px; }

    /* Loading overlay — claro */
    #loading-overlay {
      position: fixed; inset: 0; z-index: 999;
      background: rgba(240,244,248,0.95);
      display: none; flex-direction: column;
      align-items: center; justify-content: center; gap: 14px;
    }
    .spinner {
      width: 44px; height: 44px;
      border: 4px solid #e2e8f0;
      border-top-color: #0F4C81;
      border-radius: 50%;
      animation: spin 0.8s linear infinite;
    }
    @keyframes spin { to { transform: rotate(360deg); } }

    /* Modal câmera/galeria */
    #modal-opcoes {
      display: none; position: fixed; inset: 0; z-index: 100;
      background: rgba(0,0,0,0.4);
      align-items: flex-end; justify-content: center;
    }
    .modal-sheet {
      background: #fff; border-radius: 20px 20px 0 0;
      padding: 16px 16px 32px; width: 100%; max-width: 480px;
      border-top: 1px solid #f1f5f9;
    }
    .modal-handle { width: 36px; height: 4px; background: #e2e8f0; border-radius: 2px; margin: 0 auto 16px; }

    input[type="file"] { display: none; }
  </style>
</head>
<body>

<!-- LOADING OVERLAY -->
<div id="loading-overlay">
  <div class="spinner"></div>
  <p style="color:#475569;font-size:14px;font-weight:600">Enviando inspeção...</p>
  <p style="color:#94a3b8;font-size:12px">Aguarde, não feche a tela</p>
</div>

<!-- INPUTS DE ARQUIVO OCULTOS — sem capture para máxima compatibilidade -->
<?php for ($i = 1; $i <= 8; $i++): ?>
<input type="file" id="input-camera-<?= $i ?>" accept="image/*" capture="environment" onchange="processarArquivo(<?= $i ?>, this.files[0]); this.value=''">
<input type="file" id="input-galeria-<?= $i ?>" accept="image/*" onchange="processarArquivo(<?= $i ?>, this.files[0]); this.value=''">
<?php endfor; ?>

<!-- ============================================================ -->
<!-- TELA 1: IDENTIFICAÇÃO -->
<!-- ============================================================ -->
<div class="screen active" id="tela-1">
  <!-- Header -->
  <div class="header-actsafe">
    <div style="display:flex;align-items:center;gap:10px;margin-bottom:8px">
      <div style="width:36px;height:36px;border-radius:10px;background:rgba(255,255,255,0.15);display:flex;align-items:center;justify-content:center;flex-shrink:0">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M9 11l3 3L22 4"/><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/></svg>
      </div>
      <div style="flex:1;min-width:0">
        <p style="font-weight:700;color:#fff;font-size:14px;line-height:1.2;white-space:nowrap;overflow:hidden;text-overflow:ellipsis"><?= sanitizar($ins['titulo']) ?></p>
        <p style="font-size:11px;color:rgba(255,255,255,0.7)"><?= sanitizar($ins['norma']) ?> · <?= sanitizar($ins['unidade_nome'] ?? '') ?></p>
      </div>
    </div>
    <div class="step-bar">
      <div class="step-dot active" id="dot-1"></div>
      <div class="step-line"></div>
      <div class="step-dot" id="dot-2"></div>
      <div class="step-line"></div>
      <div class="step-dot" id="dot-3"></div>
    </div>
    <div style="display:flex;justify-content:space-between;font-size:10px;color:rgba(255,255,255,0.55);margin-top:3px">
      <span>Identificação</span><span>Fotos</span><span>Finalizar</span>
    </div>
  </div>

  <!-- Conteúdo -->
  <div style="flex:1;overflow-y:auto;padding:16px;display:flex;flex-direction:column;gap:12px">

    <!-- Info da inspeção -->
    <div class="card">
      <div class="card-header">Dados da Inspeção</div>
      <div style="padding:12px 14px;display:grid;gap:8px">
        <div style="display:flex;align-items:center;gap:8px">
          <span style="font-size:12px;color:#94a3b8;min-width:80px">Norma</span>
          <span style="background:#fff3e0;color:#e8640c;font-size:11px;font-weight:700;padding:2px 9px;border-radius:20px"><?= sanitizar($ins['norma']) ?></span>
        </div>
        <div style="display:flex;align-items:flex-start;gap:8px">
          <span style="font-size:12px;color:#94a3b8;min-width:80px">Unidade</span>
          <span style="font-size:13px;color:#1e293b;font-weight:500"><?= sanitizar($ins['unidade_nome'] ?? '') ?></span>
        </div>
        <?php if ($ins['equipamento_nome']): ?>
        <div style="display:flex;align-items:flex-start;gap:8px">
          <span style="font-size:12px;color:#94a3b8;min-width:80px">Equipamento</span>
          <span style="font-size:13px;color:#1e293b;font-weight:500"><?= sanitizar($ins['equipamento_nome']) ?></span>
        </div>
        <?php endif; ?>
        <?php if ($ins['descricao']): ?>
        <div style="padding-top:8px;border-top:1px solid #f1f5f9">
          <p style="font-size:11px;color:#94a3b8;margin-bottom:4px">Instruções</p>
          <p style="font-size:12px;color:#475569;line-height:1.5"><?= sanitizar($ins['descricao']) ?></p>
        </div>
        <?php endif; ?>
      </div>
    </div>

    <!-- Campos de identificação -->
    <div class="card">
      <div class="card-header">Técnico Responsável</div>
      <div style="padding:12px 14px;display:grid;gap:10px">
        <div>
          <label class="field-label">Nome completo *</label>
          <input type="text" id="tecnico_nome" class="field-input" value="<?= sanitizar($ins['tecnico_nome'] ?? '') ?>" placeholder="Digite seu nome completo">
        </div>
        <div>
          <label class="field-label">Data da inspeção</label>
          <input type="date" id="data_inspecao" class="field-input" value="<?= date('Y-m-d') ?>">
        </div>
      </div>
    </div>
  </div>

  <!-- Botão continuar -->
  <div style="padding:12px 16px 24px">
    <button class="btn-main" onclick="irParaFotos()">
      <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>
      Iniciar Inspeção com Fotos
    </button>
  </div>
</div>

<!-- ============================================================ -->
<!-- TELA 2: FOTOS + TEXTO -->
<!-- ============================================================ -->
<div class="screen" id="tela-2">
  <!-- Header -->
  <div class="header-actsafe">
    <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:8px">
      <button onclick="voltarParaIdentificacao()" style="color:rgba(255,255,255,0.8);background:rgba(255,255,255,0.12);border:none;border-radius:8px;padding:6px 11px;font-size:12px;cursor:pointer;display:flex;align-items:center;gap:4px">
        <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>
        Voltar
      </button>
      <div style="text-align:center">
        <p style="color:#fff;font-size:13px;font-weight:700">Fotos da Inspeção</p>
        <p style="color:rgba(255,255,255,0.6);font-size:11px" id="contador-fotos">0 foto(s)</p>
      </div>
      <div style="width:64px"></div>
    </div>
    <div class="step-bar">
      <div class="step-dot done"></div>
      <div class="step-line done"></div>
      <div class="step-dot active"></div>
      <div class="step-line"></div>
      <div class="step-dot"></div>
    </div>
  </div>

  <!-- Instrução -->
  <div style="padding:10px 16px 4px;text-align:center">
    <p style="font-size:12px;color:#64748b">Toque no card para tirar foto · Preencha legenda e NC abaixo</p>
  </div>

  <!-- Scroll de cards de foto -->
  <div class="fotos-scroll" id="fotos-scroll">
    <?php for ($i = 1; $i <= 8; $i++): ?>
    <div class="foto-item" id="foto-item-<?= $i ?>">
      <div class="card">
        <!-- Área de foto -->
        <div class="foto-area" id="foto-area-<?= $i ?>" onclick="abrirOpcoes(<?= $i ?>)">
          <div class="foto-placeholder" id="placeholder-<?= $i ?>">
            <div class="camera-ring">
              <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="#0F4C81" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>
            </div>
            <div style="text-align:center">
              <p style="color:#475569;font-size:13px;font-weight:600">Foto <?= $i ?></p>
              <p style="color:#94a3b8;font-size:11px">Toque para capturar</p>
            </div>
          </div>
          <img id="preview-<?= $i ?>" class="hidden" alt="Foto <?= $i ?>">
          <span class="foto-number">Foto <?= $i ?></span>
          <button class="foto-remove hidden" id="remove-<?= $i ?>" onclick="event.stopPropagation();removerFoto(<?= $i ?>)">
            <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
          </button>
          <button class="foto-retake hidden" id="retake-<?= $i ?>" onclick="event.stopPropagation();abrirOpcoes(<?= $i ?>)">
            <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>
            Refazer
          </button>
        </div>

        <!-- Campos abaixo da foto -->
        <div class="foto-fields">
          <div class="nc-toggle">
            <button type="button" class="nc-btn" id="btn-conforme-<?= $i ?>" onclick="setNC(<?= $i ?>, 'conforme')">
              <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 13 4 8"/></svg>
              Conforme
            </button>
            <button type="button" class="nc-btn" id="btn-nc-<?= $i ?>" onclick="setNC(<?= $i ?>, 'nao_conforme')">
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
              Não Conforme
            </button>
          </div>
          <label>Legenda da foto</label>
          <textarea id="legenda-<?= $i ?>" placeholder="Ex: Painel elétrico do setor A..." rows="2" style="margin-bottom:8px"></textarea>
          <div id="nc-area-<?= $i ?>" style="display:none">
            <label style="color:#ef4444">Descrição da Não Conformidade</label>
            <textarea id="nc-texto-<?= $i ?>" placeholder="Descreva o problema encontrado..." rows="2" style="border-color:#fca5a5;background:#fff5f5"></textarea>
          </div>
        </div>
      </div>
    </div>
    <?php endfor; ?>
  </div>

  <!-- Dots -->
  <div class="foto-dots" id="foto-dots">
    <?php for ($i = 1; $i <= 8; $i++): ?>
    <div class="foto-dot <?= $i===1?'active':'' ?>" id="fdot-<?= $i ?>"></div>
    <?php endfor; ?>
  </div>

  <!-- Botão continuar -->
  <div style="padding:8px 16px 24px">
    <button class="btn-main" onclick="irParaFinalizar()">
      <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 18 15 12 9 6"/></svg>
      Continuar para Finalizar
    </button>
  </div>
</div>

<!-- ============================================================ -->
<!-- TELA 3: PLANO DE AÇÃO + ENVIO -->
<!-- ============================================================ -->
<div class="screen" id="tela-3">
  <!-- Header -->
  <div class="header-actsafe">
    <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:8px">
      <button onclick="voltarParaFotos()" style="color:rgba(255,255,255,0.8);background:rgba(255,255,255,0.12);border:none;border-radius:8px;padding:6px 11px;font-size:12px;cursor:pointer;display:flex;align-items:center;gap:4px">
        <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>
        Voltar
      </button>
      <p style="color:#fff;font-size:13px;font-weight:700">Finalizar Inspeção</p>
      <div style="width:64px"></div>
    </div>
    <div class="step-bar">
      <div class="step-dot done"></div>
      <div class="step-line done"></div>
      <div class="step-dot done"></div>
      <div class="step-line done"></div>
      <div class="step-dot active"></div>
    </div>
  </div>

  <!-- Conteúdo -->
  <div style="flex:1;overflow-y:auto;padding:16px;display:flex;flex-direction:column;gap:12px">

    <!-- Resumo das fotos -->
    <div class="card">
      <div class="card-header">Resumo das Fotos</div>
      <div id="resumo-fotos" style="padding:10px 14px;display:grid;gap:6px"></div>
    </div>

    <!-- Observações gerais -->
    <div class="card">
      <div class="card-header">Observações Gerais</div>
      <div style="padding:12px 14px">
        <textarea id="obs_gerais" class="field-input" rows="3" placeholder="Observações gerais sobre a inspeção..."></textarea>
      </div>
    </div>

    <!-- Plano de ação -->
    <div class="card" style="border:1.5px solid #fed7aa">
      <div class="card-header" style="color:#e8640c;background:#fff7ed">
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="display:inline;margin-right:4px"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>
        Plano de Ação (opcional)
      </div>
      <div style="padding:12px 14px">
        <textarea id="plano_acao" class="field-input" rows="4" placeholder="Descreva as ações corretivas a serem tomadas..."></textarea>
      </div>
    </div>

    <!-- Técnico -->
    <div class="card">
      <div class="card-header">Técnico Responsável</div>
      <div style="padding:12px 14px">
        <p style="font-size:15px;font-weight:600;color:#1e293b" id="nome-tecnico-resumo">—</p>
        <p style="font-size:12px;color:#64748b;margin-top:2px" id="data-resumo">—</p>
      </div>
    </div>
  </div>

  <!-- Botão enviar -->
  <div style="padding:12px 16px 28px">
    <button class="btn-success" onclick="enviarInspecao()" id="btn-enviar">
      <svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
      Finalizar e Enviar Inspeção
    </button>
  </div>
</div>

<!-- ============================================================ -->
<!-- MODAL: CÂMERA OU GALERIA -->
<!-- ============================================================ -->
<div id="modal-opcoes" style="display:none;position:fixed;inset:0;z-index:100;background:rgba(0,0,0,0.4);align-items:flex-end;justify-content:center">
  <div class="modal-sheet">
    <div class="modal-handle"></div>
    <p style="color:#94a3b8;font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;text-align:center;margin-bottom:12px">Adicionar Foto</p>
    <div style="display:grid;gap:8px">
      <button onclick="usarCamera()" style="background:#0F4C81;color:#fff;border:none;border-radius:12px;padding:15px;font-size:14px;font-weight:600;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:8px">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>
        Câmera (Traseira)
      </button>
      <button onclick="usarGaleria()" style="background:#f8fafc;color:#1e293b;border:1.5px solid #e2e8f0;border-radius:12px;padding:15px;font-size:14px;font-weight:600;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:8px">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
        Escolher da Galeria
      </button>
      <button onclick="fecharOpcoes()" style="background:transparent;color:#94a3b8;border:none;padding:10px;font-size:13px;cursor:pointer">
        Cancelar
      </button>
    </div>
  </div>
</div>

<script>
const TOKEN = '<?= $ins['token'] ?>';
const API_URL = '<?= APP_URL ?>/inspecao_api.php';
const MAX_FOTOS = 8;

// Armazena os arquivos File reais (não base64) para envio via FormData
let fotosFiles = {};  // { slot: File }
let fotosPreview = {}; // { slot: base64 string para preview }
let fotosNC = {};     // { slot: { nc, legenda, ncTexto } }
let slotAtual = 1;

// ============================================================
// NAVEGAÇÃO
// ============================================================
function irParaFotos() {
  const nome = document.getElementById('tecnico_nome').value.trim();
  if (!nome) {
    document.getElementById('tecnico_nome').style.borderColor = '#ef4444';
    document.getElementById('tecnico_nome').focus();
    return;
  }
  trocarTela('tela-1', 'tela-2');
}
function voltarParaIdentificacao() { trocarTela('tela-2', 'tela-1'); }
function voltarParaFotos() { trocarTela('tela-3', 'tela-2'); }

function irParaFinalizar() {
  const qtd = Object.keys(fotosFiles).length;
  if (qtd === 0) { alert('Adicione pelo menos 1 foto para continuar.'); return; }

  // Coletar NC e legendas
  for (let i = 1; i <= MAX_FOTOS; i++) {
    if (fotosFiles[i]) {
      if (!fotosNC[i]) fotosNC[i] = {};
      fotosNC[i].legenda = document.getElementById(`legenda-${i}`).value;
      fotosNC[i].ncTexto = document.getElementById(`nc-texto-${i}`).value;
    }
  }

  // Preencher resumo
  const resumo = document.getElementById('resumo-fotos');
  resumo.innerHTML = '';
  for (let i = 1; i <= MAX_FOTOS; i++) {
    if (!fotosFiles[i]) continue;
    const nc = fotosNC[i]?.nc || 'conforme';
    const leg = fotosNC[i]?.legenda || `Foto ${i}`;
    const cor = nc === 'nao_conforme' ? '#ef4444' : '#10b981';
    const label = nc === 'nao_conforme' ? 'NC' : 'OK';
    const bgLabel = nc === 'nao_conforme' ? '#fef2f2' : '#ecfdf5';
    const corLabel = nc === 'nao_conforme' ? '#991b1b' : '#065f46';
    resumo.innerHTML += `
      <div style="display:flex;align-items:center;gap:8px">
        <span style="width:7px;height:7px;border-radius:50%;background:${cor};flex-shrink:0"></span>
        <span style="color:#475569;font-size:13px;flex:1">${leg}</span>
        <span style="font-size:11px;font-weight:700;padding:2px 8px;border-radius:20px;background:${bgLabel};color:${corLabel}">${label}</span>
      </div>`;
  }

  document.getElementById('nome-tecnico-resumo').textContent = document.getElementById('tecnico_nome').value;
  const d = document.getElementById('data_inspecao').value;
  if (d) {
    const [y,m,dd] = d.split('-');
    document.getElementById('data-resumo').textContent = `${dd}/${m}/${y}`;
  }
  trocarTela('tela-2', 'tela-3');
}

function trocarTela(de, para) {
  document.getElementById(de).classList.remove('active');
  document.getElementById(para).classList.add('active');
  window.scrollTo(0, 0);
}

// ============================================================
// CÂMERA / GALERIA
// ============================================================
function abrirOpcoes(slot) {
  slotAtual = slot;
  const modal = document.getElementById('modal-opcoes');
  modal.style.display = 'flex';
}
function fecharOpcoes() {
  document.getElementById('modal-opcoes').style.display = 'none';
}
function usarCamera() {
  fecharOpcoes();
  document.getElementById(`input-camera-${slotAtual}`).click();
}
function usarGaleria() {
  fecharOpcoes();
  document.getElementById(`input-galeria-${slotAtual}`).click();
}

// ============================================================
// PROCESSAR ARQUIVO — guarda File real + gera preview
// ============================================================
function processarArquivo(slot, file) {
  if (!file) return;

  // Guardar arquivo real para envio via FormData
  fotosFiles[slot] = file;
  if (!fotosNC[slot]) fotosNC[slot] = { nc: null, legenda: '', ncTexto: '' };

  // Gerar preview com compressão leve
  const reader = new FileReader();
  reader.onload = (e) => {
    const img = new Image();
    img.onload = () => {
      const canvas = document.createElement('canvas');
      const maxW = 1200, maxH = 900;
      let w = img.width, h = img.height;
      if (w > maxW) { h = Math.round(h * maxW / w); w = maxW; }
      if (h > maxH) { w = Math.round(w * maxH / h); h = maxH; }
      canvas.width = w; canvas.height = h;
      canvas.getContext('2d').drawImage(img, 0, 0, w, h);
      const preview = canvas.toDataURL('image/jpeg', 0.80);
      fotosPreview[slot] = preview;
      mostrarPreview(slot, preview);
    };
    img.src = e.target.result;
  };
  reader.readAsDataURL(file);
}

function mostrarPreview(slot, src) {
  document.getElementById(`placeholder-${slot}`).classList.add('hidden');
  const prev = document.getElementById(`preview-${slot}`);
  prev.src = src;
  prev.classList.remove('hidden');
  document.getElementById(`remove-${slot}`).classList.remove('hidden');
  document.getElementById(`retake-${slot}`).classList.remove('hidden');
  atualizarContador();
  atualizarDots(slot);
}

function removerFoto(slot) {
  delete fotosFiles[slot];
  delete fotosPreview[slot];
  delete fotosNC[slot];
  document.getElementById(`placeholder-${slot}`).classList.remove('hidden');
  const prev = document.getElementById(`preview-${slot}`);
  prev.src = ''; prev.classList.add('hidden');
  document.getElementById(`remove-${slot}`).classList.add('hidden');
  document.getElementById(`retake-${slot}`).classList.add('hidden');
  setNC(slot, null);
  document.getElementById(`legenda-${slot}`).value = '';
  document.getElementById(`nc-texto-${slot}`).value = '';
  atualizarContador();
}

function atualizarContador() {
  const qtd = Object.keys(fotosFiles).length;
  document.getElementById('contador-fotos').textContent = `${qtd} foto(s)`;
}

// ============================================================
// NC TOGGLE
// ============================================================
function setNC(slot, tipo) {
  const btnC = document.getElementById(`btn-conforme-${slot}`);
  const btnN = document.getElementById(`btn-nc-${slot}`);
  const ncArea = document.getElementById(`nc-area-${slot}`);
  btnC.className = 'nc-btn' + (tipo === 'conforme' ? ' conforme' : '');
  btnN.className = 'nc-btn' + (tipo === 'nao_conforme' ? ' nao-conforme' : '');
  ncArea.style.display = tipo === 'nao_conforme' ? 'block' : 'none';
  if (!fotosNC[slot]) fotosNC[slot] = {};
  fotosNC[slot].nc = tipo;
}

// ============================================================
// DOTS
// ============================================================
function atualizarDots(slot) {
  for (let i = 1; i <= MAX_FOTOS; i++) {
    const dot = document.getElementById(`fdot-${i}`);
    if (!dot) continue;
    dot.className = 'foto-dot' + (fotosFiles[i] ? ' filled' : '');
  }
}

document.addEventListener('DOMContentLoaded', () => {
  const scroll = document.getElementById('fotos-scroll');
  if (scroll) {
    scroll.addEventListener('scroll', () => {
      const itemW = (scroll.querySelector('.foto-item')?.offsetWidth || 1) + 10;
      const idx = Math.round(scroll.scrollLeft / itemW) + 1;
      for (let i = 1; i <= MAX_FOTOS; i++) {
        const dot = document.getElementById(`fdot-${i}`);
        if (dot) dot.classList.toggle('active', i === idx);
      }
    });
  }
});

// ============================================================
// ENVIAR INSPEÇÃO — via FormData (compatível com $_FILES/$_POST)
// ============================================================
async function enviarInspecao() {
  const fotos = Object.keys(fotosFiles);
  if (fotos.length === 0) { alert('Adicione pelo menos 1 foto.'); return; }

  const btn = document.getElementById('btn-enviar');
  btn.disabled = true;
  document.getElementById('loading-overlay').style.display = 'flex';

  try {
    const fd = new FormData();
    fd.append('token', TOKEN);
    fd.append('tecnico_nome', document.getElementById('tecnico_nome').value);
    fd.append('data_inspecao', document.getElementById('data_inspecao').value);
    fd.append('obs_gerais', document.getElementById('obs_gerais').value);
    fd.append('plano_acao', document.getElementById('plano_acao').value);
    fd.append('total_fotos', fotos.length.toString());

    let idx = 0;
    for (let i = 1; i <= MAX_FOTOS; i++) {
      if (!fotosFiles[i]) continue;
      const nc = fotosNC[i] || {};
      fd.append(`foto_${idx}`, fotosFiles[i], `foto_${i}.jpg`);
      fd.append(`legenda_${idx}`, nc.legenda || '');
      fd.append(`nc_${idx}`, nc.nc === 'nao_conforme' ? (nc.ncTexto || 'Não conforme') : '');
      fd.append(`ordem_${idx}`, i.toString());
      idx++;
    }
    // Corrigir total_fotos para o número real enviado
    fd.set('total_fotos', idx.toString());

    const resp = await fetch(API_URL, { method: 'POST', body: fd });
    const json = await resp.json();

    // API responde com 'sucesso' (português)
    if (json.sucesso) {
      document.getElementById('loading-overlay').style.display = 'none';
      document.body.innerHTML = `
        <div style="min-height:100vh;background:#f0f4f8;display:flex;align-items:center;justify-content:center;padding:24px">
          <div style="text-align:center;max-width:340px;width:100%">
            <div style="width:80px;height:80px;background:#1A7A4A;border-radius:50%;display:flex;align-items:center;justify-content:center;margin:0 auto 20px;box-shadow:0 6px 24px rgba(26,122,74,0.3)">
              <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
            </div>
            <h2 style="color:#1e293b;font-size:22px;font-weight:700;margin:0 0 8px">Inspeção Enviada!</h2>
            <p style="color:#64748b;font-size:14px;line-height:1.6;margin-bottom:20px">
              <strong>${json.fotos_salvas}</strong> foto(s) registrada(s) com sucesso.<br>
              O responsável foi notificado.
            </p>
            <div style="background:#fff;border-radius:14px;padding:14px;box-shadow:0 1px 6px rgba(0,0,0,0.07)">
              <p style="color:#94a3b8;font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:.05em;margin-bottom:4px">Técnico</p>
              <p style="color:#1e293b;font-size:14px;font-weight:600">${document.getElementById('tecnico_nome')?.value || ''}</p>
            </div>
            <p style="color:#94a3b8;font-size:11px;margin-top:20px">Pode fechar esta janela.</p>
          </div>
        </div>`;
    } else {
      throw new Error(json.erro || 'Erro desconhecido ao salvar.');
    }
  } catch (err) {
    document.getElementById('loading-overlay').style.display = 'none';
    btn.disabled = false;
    alert('Erro ao enviar: ' + err.message + '\n\nVerifique sua conexão e tente novamente.');
  }
}
</script>
</body>
</html>
