<?php
/**
 * relatorio_os.php — Relatório completo da OS com imagens embutidas (base64)
 * Gera uma página HTML autossuficiente que pode ser:
 * - Enviada como link via WhatsApp (se servidor acessível na rede)
 * - Baixada como HTML e compartilhada
 * - Impressa / salva como PDF
 */
require_once __DIR__ . '/functions.php';
require_once __DIR__ . '/auth.php';
requireLogin();

$id = (int)($_GET['id'] ?? 0);
$os = getOSById($id);
if (!$os) { header('Location: ordens.php'); exit; }

// ── Materiais ───────────────────────────────────────────
$stmtMat = pdo()->prepare(
    "SELECT mu.quantidade_usada, m.nome AS mat_nome, m.unidade
     FROM materiais_usados_os mu JOIN materiais m ON m.id=mu.material_id
     WHERE mu.os_id=? ORDER BY mu.data_registro"
);
$stmtMat->execute([$id]);
$matList = $stmtMat->fetchAll();

// ── Fotos da OS ─────────────────────────────────────────
$stmtFotos = pdo()->prepare("SELECT * FROM fotos_os WHERE os_id=? ORDER BY data_envio");
$stmtFotos->execute([$id]);
$todasFotos = $stmtFotos->fetchAll();

// Fachada do cliente
$stmtFachada = pdo()->prepare(
    "SELECT caminho_arquivo FROM clientes_fotos
     WHERE cliente_id=? AND tipo='INSTALACAO' ORDER BY data_envio DESC LIMIT 1"
);
$stmtFachada->execute([$os['cliente_id']]);
$fotoFachada = $stmtFachada->fetchColumn();

// ── Converte imagem em base64 embutido ──────────────────
function imgBase64(string $caminho): string {
    $path = __DIR__ . '/' . ltrim($caminho, '/');
    if (!file_exists($path)) return '';
    $ext  = strtolower(pathinfo($path, PATHINFO_EXTENSION));
    $mime = match($ext) {
        'png'  => 'image/png',
        'webp' => 'image/webp',
        'gif'  => 'image/gif',
        default=> 'image/jpeg',
    };
    $data = base64_encode(file_get_contents($path));
    return "data:{$mime};base64,{$data}";
}

// ── Dados completos do cliente ──────────────────────────────────
$stmtCli = pdo()->prepare(
    "SELECT c.*,
            CONCAT_WS(', ',
                NULLIF(TRIM(c.endereco_logradouro),''),
                NULLIF(TRIM(c.endereco_numero),''),
                NULLIF(TRIM(c.endereco_bairro),''),
                NULLIF(TRIM(c.endereco_cidade),''),
                NULLIF(TRIM(c.endereco_cep),'')
            ) AS endereco_completo
     FROM clientes c WHERE c.id = ?"
);
$stmtCli->execute([$os['cliente_id']]);
$cli = $stmtCli->fetch() ?: [];

// ── Infraestrutura do cliente (CTO/sinal) ───────────────
$infra = $cli; // já incluído na query acima

function corSinalRel(?string $v): string {
    if ($v === null || $v === '') return '#718096';
    $f = (float)$v;
    if ($f >= -25) return '#10b981';
    if ($f >= -28) return '#f59e0b';
    return '#ef4444';
}

// ── Empresa ─────────────────────────────────────────────
$empresaNome = getConfig('empresa_nome', APP_NAME);
$logoUrl     = getConfig('logo_url', '');
$logoBase64  = '';
if ($logoUrl && file_exists(__DIR__ . '/' . ltrim($logoUrl,'/'))) {
    $logoBase64 = imgBase64($logoUrl);
}

// ── Para download como HTML ──────────────────────────────
if (isset($_GET['download'])) {
    header('Content-Type: text/html; charset=utf-8');
    header('Content-Disposition: attachment; filename="OS-' . $os['numero_os'] . '.html"');
}

// Agrupa fotos
$fotosServico = array_filter($todasFotos, fn($f) => ($f['tipo']??'SERVICO') === 'SERVICO');
$fotosOLT     = array_filter($todasFotos, fn($f) => ($f['tipo']??'') === 'OLT');
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>OS <?= e($os['numero_os']) ?> — <?= e($empresaNome) ?></title>
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{font-family:'Segoe UI',Arial,sans-serif;background:#f5f7fa;color:#1a202c;font-size:13px}
.page{max-width:1200px;margin:0 auto;background:#fff;min-height:100vh;box-shadow:0 0 30px rgba(0,0,0,.1)}

/* Cabeçalho mais compacto */
.header{background:linear-gradient(135deg,#0f1729,#1a2a4a);color:#fff;padding:12px 20px;display:flex;justify-content:space-between;align-items:center}
.header-logo img{max-height:40px;max-width:140px;object-fit:contain}
.header-nome{font-size:11px;opacity:.7;font-family:monospace}
.os-num{font-size:22px;font-weight:800;color:#00d4ff;letter-spacing:-1px}
.status-badge{display:inline-block;padding:3px 12px;border-radius:20px;font-size:10px;font-weight:700;letter-spacing:.5px;margin-top:4px}
.status-CONCLUIDA{background:#10b98122;color:#10b981;border:1px solid #10b981}
.status-ABERTA{background:#f59e0b22;color:#f59e0b;border:1px solid #f59e0b}
.status-EM_ANDAMENTO{background:#00d4ff22;color:#00d4ff;border:1px solid #00d4ff}
.status-CANCELADA{background:#ef444422;color:#ef4444;border:1px solid #ef4444}
.status-AGENDADA{background:#8b5cf622;color:#8b5cf6;border:1px solid #8b5cf6}

/* Seções mais compactas */
.section{padding:8px 16px;border-bottom:1px solid #e2e8f0}
.section:last-child{border-bottom:none}
.section-title{font-size:9px;font-weight:700;letter-spacing:2px;text-transform:uppercase;color:#00d4ff;margin-bottom:6px;padding-bottom:3px;border-bottom:2px solid #00d4ff22}

/* Layout principal - foto fachada à esquerda, informações à direita */
.cliente-main-layout{display:grid;grid-template-columns:260px 1fr;gap:16px;align-items:start}
@media(max-width:680px){.cliente-main-layout{grid-template-columns:1fr}}

/* Coluna da foto fachada - proporção mantida */
.fachada-col{background:#f8fafc;border-radius:8px;overflow:hidden;border:1px solid #e2e8f0}
.fachada-col img{width:100%;height:auto;display:block;cursor:pointer;transition:transform .2s}
.fachada-col img:hover{transform:scale(1.02)}
.fachada-col .sem-foto{aspect-ratio:4/3;background:#f0f4f8;border-radius:8px;border:1px dashed #cbd5e0;display:flex;align-items:center;justify-content:center;color:#a0aec0;font-size:11px;min-height:160px}
.fachada-label{font-size:8px;font-weight:700;letter-spacing:2px;text-transform:uppercase;color:#718096;text-align:center;padding:5px;background:#f1f5f9;border-top:1px solid #e2e8f0}

/* Coluna de informações - todas as grids lado a lado */
.info-col{display:flex;flex-direction:column;gap:8px}

/* Linha superior com nome e status - mais compacto */
.cliente-header{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:6px;padding-bottom:5px;border-bottom:1.5px solid #00d4ff22}
.cliente-nome{font-size:16px;font-weight:800;color:#1a202c}
.cliente-tipo-badge{display:inline-block;padding:3px 12px;border-radius:20px;font-size:10px;font-weight:700}

/* Grids de dados - mais compactas */
.data-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:5px}
.data-grid.cols2{grid-template-columns:repeat(2,1fr)}
.data-grid.cols4{grid-template-columns:repeat(4,1fr)}
.data-item{background:#f8fafc;border-radius:5px;padding:5px 8px}
.data-label{font-size:8px;color:#718096;letter-spacing:.8px;text-transform:uppercase;margin-bottom:2px;font-weight:700}
.data-val{font-size:11px;font-weight:600;color:#1a202c;line-height:1.25}
.data-val.mono{font-family:monospace;font-size:10px}
.data-val.accent{color:#10b981}
.data-val.cyan{color:#0284c7}
.data-val.red{color:#ef4444}
.data-val.amber{color:#d97706}
.data-full{grid-column:1/-1}
.data-half{grid-column:span 2}
@media(max-width:600px){
  .data-grid{grid-template-columns:repeat(2,1fr)}
  .data-grid.cols4{grid-template-columns:repeat(2,1fr)}
}

/* Blocos de texto mais compactos */
.text-block{background:#f8fafc;border-left:3px solid #00d4ff;border-radius:3px;padding:6px 10px;font-size:11px;line-height:1.4;color:#2d3748}
.text-block .data-label{font-size:8px;margin-bottom:3px}
.text-block.success{border-left-color:#10b981;background:#f0fdf4}
.text-block.servico{border-left-color:#8b5cf6}
.text-block.solucao{border-left-color:#10b981;background:#f0fdf4}

/* Tabela de materiais compacta */
.mat-mini{width:100%;border-collapse:collapse;font-size:10px}
.mat-mini th{font-size:8px;letter-spacing:.8px;color:#718096;text-transform:uppercase;padding:4px 6px;border-bottom:1px solid #e2e8f0;background:#f8fafc;text-align:left}
.mat-mini td{padding:4px 6px;border-bottom:1px solid #f0f0f0;color:#2d3748}
.mat-mini tr:last-child td{border-bottom:none}
.mat-mini .mat-qtd{font-family:monospace;font-weight:700;color:#00d4ff;text-align:right;white-space:nowrap}

/* Fotos - thumbnails menores para caber mais no PDF */
.fotos-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(120px,1fr));gap:6px;margin-top:6px}
.foto-card{border-radius:5px;overflow:hidden;border:1px solid #e2e8f0;box-shadow:0 1px 2px rgba(0,0,0,.04);cursor:pointer;transition:transform .15s}
.foto-card:hover{transform:translateY(-2px);box-shadow:0 3px 8px rgba(0,0,0,.1)}
.foto-card img{width:100%;height:100px;object-fit:cover;display:block}
.foto-card-cap{padding:3px 6px;font-size:9px;color:#718096;background:#f8fafc}

/* Lightbox */
.lightbox{display:none;position:fixed;top:0;left:0;width:100%;height:100%;background-color:rgba(0,0,0,.95);z-index:9999;cursor:pointer;animation:fadeIn 0.3s}
.lightbox.active{display:flex;align-items:center;justify-content:center}
.lightbox-img{max-width:90%;max-height:90%;object-fit:contain;animation:zoomIn 0.3s;box-shadow:0 0 30px rgba(0,0,0,.5);border-radius:4px}
.lightbox-caption{position:absolute;bottom:20px;left:0;right:0;text-align:center;color:#fff;background:rgba(0,0,0,.7);padding:10px;font-size:13px;margin:0 auto;width:80%;border-radius:8px}
.lightbox-close{position:absolute;top:15px;right:20px;color:#fff;font-size:35px;font-weight:bold;cursor:pointer;transition:0.3s;width:35px;height:35px;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,.5);border-radius:50%}
.lightbox-close:hover{color:#00d4ff;transform:scale(1.1)}
.lightbox-prev,.lightbox-next{position:absolute;top:50%;transform:translateY(-50%);background:rgba(0,0,0,.5);color:#fff;font-size:25px;padding:12px 8px;cursor:pointer;border-radius:5px;transition:0.3s;user-select:none}
.lightbox-prev{left:15px}
.lightbox-next{right:15px}
.lightbox-prev:hover,.lightbox-next:hover{background:rgba(0,212,255,.5);color:#fff}
.lightbox-counter{position:absolute;top:15px;left:15px;color:#fff;background:rgba(0,0,0,.5);padding:4px 10px;border-radius:20px;font-size:11px}

@keyframes fadeIn{from{opacity:0}to{opacity:1}}
@keyframes zoomIn{from{transform:scale(0.8);opacity:0}to{transform:scale(1);opacity:1}}

/* Rodapé mais compacto */
.footer{background:#0f1729;color:rgba(255,255,255,.5);padding:10px 20px;font-size:10px;font-family:monospace;display:flex;justify-content:space-between;flex-wrap:wrap;gap:6px}

/* Ações (não aparecem no PDF/print) */
.actions{padding:10px 20px;background:#f8fafc;border-bottom:1px solid #e2e8f0;display:flex;gap:8px;flex-wrap:wrap}
.btn{display:inline-flex;align-items:center;gap:5px;padding:6px 14px;border-radius:5px;font-size:11px;font-weight:700;cursor:pointer;border:none;text-decoration:none;transition:.15s}
.btn-wa{background:#25d366;color:#fff}
.btn-wa:hover{background:#1ebe5d}
.btn-pdf{background:#ef4444;color:#fff}
.btn-dl{background:#3b82f6;color:#fff}
.btn-back{background:#e2e8f0;color:#4a5568}

/* Configurações especiais para impressão/PDF */
@media print {
  .actions{display:none}
  .page{max-width:100%;margin:0;box-shadow:none}
  .header{background:#0f1729;color:#fff;-webkit-print-color-adjust:exact;print-color-adjust:exact}
  .status-badge{-webkit-print-color-adjust:exact;print-color-adjust:exact}
  .section-title{color:#00d4ff}
  .data-item{background:#f8fafc;break-inside:avoid}
  .foto-card{break-inside:avoid}
  .lightbox-prev,.lightbox-next,.lightbox-close,.lightbox-counter{display:none}
}
</style>
</head>
<body>
<div class="page">

  <!-- AÇÕES (visíveis só no browser) -->
  <div class="actions">
    <a href="os_detalhe.php?id=<?= $id ?>" class="btn btn-back">← Voltar à OS</a>
    <button class="btn btn-wa" onclick="compartilharWA()">
      📱 Compartilhar no WhatsApp
    </button>
    <button class="btn btn-pdf" onclick="window.print()">
      🖨 Imprimir / PDF
    </button>
    <a href="relatorio_os.php?id=<?= $id ?>&download=1" class="btn btn-dl">
      ⬇ Baixar HTML
    </a>
  </div>

  <!-- CABEÇALHO -->
  <div class="header">
    <div>
      <?php if ($logoBase64): ?>
        <div class="header-logo"><img src="<?= $logoBase64 ?>" alt="<?= e($empresaNome) ?>"/></div>
      <?php else: ?>
        <div style="font-size:16px;font-weight:800;color:#00d4ff;letter-spacing:-1px"><?= e($empresaNome) ?></div>
      <?php endif; ?>
      <div class="header-nome">Relatório de Atendimento Técnico</div>
    </div>
    <div style="text-align:right">
      <div class="os-num"><?= e($os['numero_os']) ?></div>
      <span class="status-badge status-<?= $os['status'] ?>"><?= $os['status'] ?></span>
      <?php if ($os['protocolo']): ?>
      <div style="font-size:9px;color:rgba(255,255,255,.5);font-family:monospace;margin-top:3px">Proto: <?= e($os['protocolo']) ?></div>
      <?php endif; ?>
    </div>
  </div>

  <!-- CLIENTE + FACHADA + TODAS AS INFORMAÇÕES LADO A LADO -->
  <div class="section">
    <div class="cliente-main-layout">

      <!-- Coluna ESQUERDA: Foto Fachada -->
      <div class="fachada-col">
        <?php $b64Fachada = $fotoFachada ? imgBase64($fotoFachada) : ''; if ($b64Fachada): ?>
          <img src="<?= $b64Fachada ?>" alt="Fachada" class="lightbox-trigger" data-caption="Fachada do cliente"/>
        <?php else: ?>
          <div class="sem-foto">📷 Sem foto da fachada</div>
        <?php endif; ?>
        <div class="fachada-label">FACHADA DO CLIENTE</div>
      </div>

      <!-- Coluna DIREITA: Todas as informações -->
      <div class="info-col">

        <!-- Nome + tipo OS -->
        <div class="cliente-header">
          <div class="cliente-nome"><?= e($os['cliente_nome']) ?></div>
          <span class="cliente-tipo-badge status-badge status-<?= $os['status'] ?>"><?= labelTipoOS($os['tipo_os']) ?></span>
        </div>

        <!-- Grid: Dados Pessoais (CPF, Telefone, Email, Plano) -->
        <?php if ($cli['documento'] ?? '' || $cli['telefone'] ?? '' || $cli['email'] ?? '' || $cli['plano'] ?? ''): ?>
        <div class="data-grid">
          <?php if ($cli['documento'] ?? ''): ?>
          <div class="data-item">
            <div class="data-label">CPF / CNPJ</div>
            <div class="data-val mono"><?= e($cli['documento']) ?></div>
          </div>
          <?php endif; ?>
          <?php if ($cli['telefone'] ?? ''): ?>
          <div class="data-item">
            <div class="data-label">Telefone</div>
            <div class="data-val mono"><?= e($cli['telefone']) ?></div>
          </div>
          <?php endif; ?>
          <?php if ($cli['email'] ?? ''): ?>
          <div class="data-item">
            <div class="data-label">E-mail</div>
            <div class="data-val"><?= e($cli['email']) ?></div>
          </div>
          <?php endif; ?>
          <?php if ($cli['plano'] ?? ''): ?>
          <div class="data-item">
            <div class="data-label">Plano</div>
            <div class="data-val cyan"><?= e($cli['plano']) ?></div>
          </div>
          <?php endif; ?>
        </div>
        <?php endif; ?>

        <!-- Endereço completo -->
        <?php if ($cli['endereco_completo'] ?? ''): ?>
        <div class="data-grid">
          <div class="data-item data-full">
            <div class="data-label">Endereço</div>
            <div class="data-val"><?= e($cli['endereco_completo']) ?></div>
          </div>
        </div>
        <?php endif; ?>

        <!-- Grid: Dados da OS (Técnico, Abertura, Conclusão, VLAN, Cód. Conexão) -->
        <div class="data-grid cols4">
          <div class="data-item">
            <div class="data-label">Técnico</div>
            <div class="data-val" style="font-size:10px"><?= e($os['tecnico_nome'] ?: '—') ?></div>
          </div>
          <div class="data-item">
            <div class="data-label">Abertura</div>
            <div class="data-val mono" style="font-size:9px"><?= fmtData($os['data_abertura'], false) ?></div>
          </div>
          <?php if ($os['data_fechamento']): ?>
          <div class="data-item">
            <div class="data-label">Conclusão</div>
            <div class="data-val mono accent" style="font-size:9px"><?= fmtData($os['data_fechamento'], false) ?></div>
          </div>
          <?php elseif ($os['agendamento']): ?>
          <div class="data-item">
            <div class="data-label">Agendamento</div>
            <div class="data-val mono" style="font-size:9px"><?= fmtData($os['agendamento'], false) ?></div>
          </div>
          <?php endif; ?>
          <?php if ($cli['vlan'] ?? ''): ?>
          <div class="data-item">
            <div class="data-label">VLAN</div>
            <div class="data-val mono"><?= e($cli['vlan']) ?></div>
          </div>
          <?php endif; ?>
          <?php if ($cli['cod_conexao'] ?? ''): ?>
          <div class="data-item">
            <div class="data-label">Cód. Conexão</div>
            <div class="data-val mono"><?= e($cli['cod_conexao']) ?></div>
          </div>
          <?php endif; ?>
        </div>

        <!-- Relato do Cliente -->
        <?php if ($os['relato_cliente']): ?>
        <div class="text-block">
          <div class="data-label">✎ Relato do Cliente</div>
          <?= nl2br(e($os['relato_cliente'])) ?>
        </div>
        <?php endif; ?>

        <!-- Serviço Realizado -->
        <?php if ($os['descricao_servico']): ?>
        <div class="text-block servico">
          <div class="data-label">🔧 Serviço Realizado</div>
          <?= nl2br(e($os['descricao_servico'])) ?>
        </div>
        <?php endif; ?>

        <!-- Solução Aplicada -->
        <?php if ($os['solucao']): ?>
        <div class="text-block solucao">
          <div class="data-label">✔ Solução Aplicada</div>
          <?= nl2br(e($os['solucao'])) ?>
        </div>
        <?php endif; ?>

        <!-- Materiais Utilizados -->
        <?php if ($matList): ?>
        <div>
          <div class="data-label" style="margin-bottom:4px">▣ Materiais Utilizados (<?= count($matList) ?>)</div>
          <table class="mat-mini">
            <thead>
              <tr><th>Material</th><th style="text-align:right">Quantidade</th></tr>
            </thead>
            <tbody>
              <?php foreach ($matList as $m): ?>
              <tr>
                <td><?= e($m['mat_nome']) ?></td>
                <td class="mat-qtd"><?= $m['quantidade_usada'] ?> <?= e($m['unidade']) ?></td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
        <?php endif; ?>

      </div><!-- /info-col -->
    </div><!-- /cliente-main-layout -->
  </div>

  <!-- DADOS DE REDE (PPPoE / WiFi / Roteador) -->
  <?php $temRede = ($cli['pppoe_usuario']??'') || ($cli['wifi_ssid_2g']??'') || ($cli['wifi_ssid_5g']??'') || ($cli['modelo_roteador']??''); ?>
  <?php if ($temRede): ?>
  <div class="section">
    <div class="section-title">🌐 Dados de Rede e Equipamento</div>
    <div class="data-grid">
      <?php if ($cli['pppoe_usuario'] ?? ''): ?>
      <div class="data-item">
        <div class="data-label">PPPoE Usuário</div>
        <div class="data-val mono cyan"><?= e($cli['pppoe_usuario']) ?></div>
      </div>
      <?php endif; ?>
      <?php if ($cli['pppoe_senha'] ?? ''): ?>
      <div class="data-item">
        <div class="data-label">PPPoE Senha</div>
        <div class="data-val mono"><?= e($cli['pppoe_senha']) ?></div>
      </div>
      <?php endif; ?>
      <?php if ($cli['wifi_ssid_2g'] ?? ''): ?>
      <div class="data-item">
        <div class="data-label">Wi-Fi 2.4G (SSID)</div>
        <div class="data-val mono"><?= e($cli['wifi_ssid_2g']) ?></div>
      </div>
      <div class="data-item">
        <div class="data-label">Senha Wi-Fi 2.4G</div>
        <div class="data-val mono"><?= e($cli['wifi_senha_2g'] ?? '—') ?></div>
      </div>
      <?php endif; ?>
      <?php if ($cli['wifi_ssid_5g'] ?? ''): ?>
      <div class="data-item">
        <div class="data-label">Wi-Fi 5G (SSID)</div>
        <div class="data-val mono"><?= e($cli['wifi_ssid_5g']) ?></div>
      </div>
      <div class="data-item">
        <div class="data-label">Senha Wi-Fi 5G</div>
        <div class="data-val mono"><?= e($cli['wifi_senha_5g'] ?? '—') ?></div>
      </div>
      <?php endif; ?>
      <?php if ($cli['modelo_roteador'] ?? ''): ?>
      <div class="data-item">
        <div class="data-label">Roteador</div>
        <div class="data-val"><?= e($cli['modelo_roteador']) ?></div>
      </div>
      <?php endif; ?>
      <?php if ($cli['password_equipamento'] ?? ''): ?>
      <div class="data-item">
        <div class="data-label">Senha Equipamento</div>
        <div class="data-val mono"><?= e($cli['password_equipamento']) ?></div>
      </div>
      <?php endif; ?>
      <?php if ($cli['mac_key'] ?? ''): ?>
      <div class="data-item">
        <div class="data-label">MAC / Chave</div>
        <div class="data-val mono" style="font-size:9px"><?= e($cli['mac_key']) ?></div>
      </div>
      <?php endif; ?>
      <?php if ($cli['possui_repetidor'] && ($cli['modelo_repetidor']??'')): ?>
      <div class="data-item">
        <div class="data-label">Repetidor</div>
        <div class="data-val"><?= e($cli['modelo_repetidor']) ?></div>
      </div>
      <?php endif; ?>
    </div>
  </div>
  <?php endif; ?>

  <!-- CÂMERAS -->
  <?php if ($cli['possui_cameras'] ?? false): ?>
  <div class="section">
    <div class="section-title">📷 Câmeras de Segurança</div>
    <div class="data-grid cols2">
      <?php if ($cli['camera_local'] ?? ''): ?>
      <div class="data-item data-full">
        <div class="data-label">Localização / Observação</div>
        <div class="data-val"><?= e($cli['camera_local']) ?></div>
      </div>
      <?php else: ?>
      <div class="data-item"><div class="data-label">Status</div><div class="data-val">✓ Câmeras instaladas</div></div>
      <?php endif; ?>
    </div>
  </div>
  <?php endif; ?>

  <!-- INFRAESTRUTURA ÓPTICA -->
  <?php if ($infra['cto_nome'] ?? ''): ?>
  <div class="section">
    <div class="section-title">◉ Infraestrutura Óptica</div>
    <div class="data-grid">
      <div class="data-item">
        <div class="data-label">Caixa CTO</div>
        <div class="data-val cyan"><?= e($infra['cto_nome']) ?></div>
      </div>
      <div class="data-item">
        <div class="data-label">Porta CTO</div>
        <div class="data-val mono"><?= $infra['cto_porta'] ? 'Porta '.$infra['cto_porta'] : '—' ?></div>
      </div>
      <?php if ($infra['sinal_box'] !== null && $infra['sinal_box'] !== ''): ?>
      <div class="data-item">
        <div class="data-label">Sinal BOX</div>
        <div class="data-val mono" style="font-size:13px;font-weight:800;color:<?= corSinalRel($infra['sinal_box']) ?>"><?= e($infra['sinal_box']) ?> dBm</div>
      </div>
      <?php endif; ?>
      <?php if ($infra['sinal_cli'] !== null && $infra['sinal_cli'] !== ''): ?>
      <div class="data-item">
        <div class="data-label">Sinal Cliente (RX)</div>
        <div class="data-val mono" style="font-size:13px;font-weight:800;color:<?= corSinalRel($infra['sinal_cli']) ?>"><?= e($infra['sinal_cli']) ?> dBm</div>
      </div>
      <?php endif; ?>
      <?php if ($infra['olt_gps'] ?? ''): ?>
      <div class="data-item data-full">
        <div class="data-label">GPS da CTO</div>
        <div class="data-val mono" style="font-size:9px">
          <?= e($infra['olt_gps']) ?>
          <a href="https://maps.google.com/?q=<?= urlencode($infra['olt_gps']) ?>" target="_blank"
             style="color:#0284c7;margin-left:6px">◉ Ver no mapa</a>
        </div>
      </div>
      <?php endif; ?>
    </div>
  </div>
  <?php endif; ?>

  <!-- FOTOS DO SERVIÇO -->
  <?php if ($fotosServico): ?>
  <div class="section">
    <div class="section-title">📸 Fotos do Serviço (<?= count($fotosServico) ?>)</div>
    <div class="fotos-grid">
      <?php foreach ($fotosServico as $f):
        $b64 = imgBase64($f['caminho_arquivo']);
        if (!$b64) continue;
        $caption = $f['descricao'] ? e($f['descricao']) . ' · ' . fmtData($f['data_envio']) : fmtData($f['data_envio']);
      ?>
      <div class="foto-card" data-img-src="<?= $b64 ?>" data-caption="<?= $caption ?>">
        <img src="<?= $b64 ?>" alt="<?= e($f['descricao']) ?>" loading="lazy" class="lightbox-trigger"/>
        <div class="foto-card-cap"><?= $caption ?></div>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
  <?php endif; ?>

  <!-- FOTOS DA OLT/CTO -->
  <?php if ($fotosOLT): ?>
  <div class="section">
    <div class="section-title">📡 Fotos da OLT / CTO (<?= count($fotosOLT) ?>)</div>
    <div class="fotos-grid">
      <?php foreach ($fotosOLT as $f):
        $b64 = imgBase64($f['caminho_arquivo']);
        if (!$b64) continue;
        $caption = $f['descricao'] ? e($f['descricao']) . ' · ' . fmtData($f['data_envio']) : fmtData($f['data_envio']);
      ?>
      <div class="foto-card" data-img-src="<?= $b64 ?>" data-caption="<?= $caption ?>">
        <img src="<?= $b64 ?>" alt="<?= e($f['descricao']) ?>" loading="lazy" class="lightbox-trigger"/>
        <div class="foto-card-cap"><?= $caption ?></div>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
  <?php endif; ?>

  <!-- RODAPÉ -->
  <div class="footer">
    <span><?= e($empresaNome) ?> · <?= e($os['numero_os']) ?></span>
    <span>Gerado em <?= date('d/m/Y H:i') ?></span>
  </div>

</div><!-- /page -->

<!-- LIGHTBOX -->
<div id="lightbox" class="lightbox">
  <span class="lightbox-close">&times;</span>
  <span class="lightbox-prev">&#10094;</span>
  <span class="lightbox-next">&#10095;</span>
  <div class="lightbox-counter"></div>
  <img class="lightbox-img" alt="">
  <div class="lightbox-caption"></div>
</div>

<script>
// ── Lightbox System ──────────────────────────────────────────
class Lightbox {
  constructor() {
    this.images = [];
    this.currentIndex = 0;
    this.lightbox = document.getElementById('lightbox');
    this.lightboxImg = document.querySelector('.lightbox-img');
    this.lightboxCaption = document.querySelector('.lightbox-caption');
    this.lightboxCounter = document.querySelector('.lightbox-counter');
    this.init();
  }

  init() {
    // Coleta todas as imagens que têm a classe lightbox-trigger
    this.collectImages();
    
    // Event listeners
    document.querySelectorAll('.lightbox-trigger').forEach(img => {
      img.addEventListener('click', (e) => {
        e.stopPropagation();
        const parent = img.closest('.foto-card');
        if (parent) {
          const imgSrc = parent.dataset.imgSrc;
          const caption = parent.dataset.caption;
          this.open(this.getImageIndex(imgSrc), imgSrc, caption);
        } else {
          // Para imagem solta (fachada)
          const imgSrc = img.src;
          const caption = img.dataset.caption || '';
          this.open(this.getImageIndex(imgSrc), imgSrc, caption);
        }
      });
    });

    // Fechar lightbox
    this.lightbox.addEventListener('click', (e) => {
      if (e.target === this.lightbox || e.target.classList.contains('lightbox-close')) {
        this.close();
      }
    });

    // Navegação
    document.querySelector('.lightbox-prev').addEventListener('click', (e) => {
      e.stopPropagation();
      this.prev();
    });
    
    document.querySelector('.lightbox-next').addEventListener('click', (e) => {
      e.stopPropagation();
      this.next();
    });

    // Teclado
    document.addEventListener('keydown', (e) => {
      if (!this.lightbox.classList.contains('active')) return;
      if (e.key === 'ArrowLeft') this.prev();
      if (e.key === 'ArrowRight') this.next();
      if (e.key === 'Escape') this.close();
    });
  }

  collectImages() {
    const items = [];
    // Coleta fotos dos cards
    document.querySelectorAll('.foto-card').forEach(card => {
      if (card.dataset.imgSrc) {
        items.push({
          src: card.dataset.imgSrc,
          caption: card.dataset.caption || ''
        });
      }
    });
    // Coleta foto da fachada se existir
    const fachadaImg = document.querySelector('.fachada-col img');
    if (fachadaImg && fachadaImg.src && fachadaImg.src !== '') {
      items.push({
        src: fachadaImg.src,
        caption: fachadaImg.dataset.caption || 'Fachada do cliente'
      });
    }
    this.images = items;
  }

  getImageIndex(src) {
    return this.images.findIndex(img => img.src === src);
  }

  open(index, src, caption) {
    this.currentIndex = index !== -1 ? index : 0;
    this.updateContent();
    this.lightbox.classList.add('active');
    document.body.style.overflow = 'hidden';
  }

  updateContent() {
    const img = this.images[this.currentIndex];
    if (img) {
      this.lightboxImg.src = img.src;
      this.lightboxCaption.textContent = img.caption;
      this.updateCounter();
    }
  }

  updateCounter() {
    if (this.images.length > 1) {
      this.lightboxCounter.textContent = `${this.currentIndex + 1} / ${this.images.length}`;
      this.lightboxCounter.style.display = 'block';
    } else {
      this.lightboxCounter.style.display = 'none';
    }
    
    // Mostrar/esconder setas de navegação
    const prevBtn = document.querySelector('.lightbox-prev');
    const nextBtn = document.querySelector('.lightbox-next');
    if (this.images.length <= 1) {
      prevBtn.style.display = 'none';
      nextBtn.style.display = 'none';
    } else {
      prevBtn.style.display = 'flex';
      nextBtn.style.display = 'flex';
    }
  }

  next() {
    if (this.currentIndex < this.images.length - 1) {
      this.currentIndex++;
      this.updateContent();
    }
  }

  prev() {
    if (this.currentIndex > 0) {
      this.currentIndex--;
      this.updateContent();
    }
  }

  close() {
    this.lightbox.classList.remove('active');
    document.body.style.overflow = '';
  }
}

// ── Compartilhar via WhatsApp com Web Share API ──────────────────────
async function compartilharWA() {
  const tel = prompt('Telefone do supervisor (somente números, sem +55):', '');
  if (!tel || tel.replace(/\D/g,'').length < 10) return;

  const texto = <?= json_encode(
      "📋 *" . $os['numero_os'] . " — " . $empresaNome . "*\n" .
      "Cliente: " . $os['cliente_nome'] . "\n" .
      "Tipo: " . labelTipoOS($os['tipo_os']) . "\n" .
      "Status: " . $os['status'] . "\n" .
      "Técnico: " . ($os['tecnico_nome'] ?: '—') . "\n" .
      "Data: " . fmtData($os['data_abertura']) . "\n\n" .
      "📸 Relatório completo com fotos:\n"
  ) ?>;

  // ── Tenta Web Share API com arquivos ────────────────────────────
  if (typeof navigator.share === 'function') {
    const imgElements = document.querySelectorAll('.fotos-grid img, .fachada-col img');
    const files = [];

    for (let i = 0; i < imgElements.length; i++) {
      try {
        const src = imgElements[i].src;
        if (!src.startsWith('data:')) continue;
        const arr = src.split(',');
        const mime = arr[0].match(/:(.*?);/)[1];
        const bstr = atob(arr[1]);
        const u8 = new Uint8Array(bstr.length);
        for (let j = 0; j < bstr.length; j++) u8[j] = bstr.charCodeAt(j);
        const ext = mime.split('/')[1] === 'png' ? 'png' : 'jpg';
        files.push(new File([u8], 'foto_' + (i+1) + '.' + ext, { type: mime }));
      } catch(e) {}
    }

    if (files.length > 0 && navigator.canShare && navigator.canShare({ files })) {
      try {
        await navigator.share({ text: texto + window.location.href, files });
        return;
      } catch(e) {
        if (e.name === 'AbortError') return;
      }
    }
  }

  // ── Fallback: abre wa.me com o link do relatório ─────────────────
  const waUrl = 'https://wa.me/55' + tel.replace(/\D/g,'') +
                '?text=' + encodeURIComponent(texto + window.location.href);
  window.open(waUrl, '_blank');
}

// Inicializar lightbox quando o DOM estiver carregado
document.addEventListener('DOMContentLoaded', () => {
  new Lightbox();
});
</script>
</body>
</html>
