<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

include 'conexao.php';
include 'config/classificacao_lead_modelo_utils.php';
$conn = conectar_banco();
garantir_modelo_classificacao_lead_padrao($conn);

// Função para formatar telefone
function formatar_telefone($ddd, $telefone) {
    if (empty($telefone)) return '-';
    $telefone = preg_replace('/\D/', '', $telefone);
    $ddd = preg_replace('/\D/', '', $ddd);
    $formatted = '';
    if (!empty($ddd)) {
        $formatted = '(' . $ddd . ') ';
    }
    if (strlen($telefone) == 8) {
        $formatted .= substr($telefone, 0, 4) . '-' . substr($telefone, 4);
    } elseif (strlen($telefone) == 9) {
        $formatted .= substr($telefone, 0, 5) . '-' . substr($telefone, 5);
    } else {
        $formatted .= $telefone;
    }
    return $formatted ?: '-';
}

function calcular_nota_resposta_pdf($resposta, $tipo_resposta, $opcoes_json = '') {
    $resposta = (string)$resposta;
    $tipo_resposta = (string)$tipo_resposta;
    $nota = 0.0;

    if ($tipo_resposta === 'campos_personalizados') {
        $resposta_campos = json_decode($resposta, true);
        $campos_def = json_decode($opcoes_json ?: '[]', true);

        if (is_array($resposta_campos) && is_array($campos_def)) {
            foreach ($campos_def as $campo_def) {
                $nome_campo = $campo_def['nome'] ?? '';
                $nota_campo = (float)($campo_def['nota'] ?? 0);
                if ($nome_campo === '') continue;

                $valor_campo = $resposta_campos[$nome_campo] ?? '';
                $tem_valor = is_array($valor_campo)
                    ? count(array_filter($valor_campo, function($v) { return trim((string)$v) !== ''; })) > 0
                    : trim((string)$valor_campo) !== '';

                if ($tem_valor) {
                    $nota += $nota_campo;
                }
            }
        }

        return $nota;
    }

    if (strpos($resposta, '|') === false) {
        return 0.0;
    }

    $partes = explode('|', $resposta);
    for ($i = 1; $i < count($partes); $i += 2) {
        $valor = trim((string)$partes[$i]);
        if ($valor !== '' && is_numeric($valor)) {
            $nota += (float)$valor;
        }
    }

    return $nota;
}

function resposta_tem_conteudo_pdf($resposta, $tipo_resposta = '') {
    $resposta = (string)$resposta;
    $tipo_resposta = (string)$tipo_resposta;

    if ($tipo_resposta === 'campos_personalizados') {
        $json = json_decode($resposta, true);
        if (!is_array($json)) return false;
        foreach ($json as $valor) {
            if (is_array($valor)) {
                if (count(array_filter($valor, function($v) { return trim((string)$v) !== ''; })) > 0) {
                    return true;
                }
            } elseif (trim((string)$valor) !== '') {
                return true;
            }
        }
        return false;
    }

    return trim($resposta) !== '';
}

$id = $_GET['id'] ?? null;
if (!$id) {
    die('ID inválido');
}

// Buscar dados da pesquisa_empresa
$stmt = $conn->prepare("
    SELECT 
        pe.*,
        e.NOME_FANTASIA, e.EMPRESA, e.CNPJ, e.RUA, e.NUMERO, e.COMPL_NUM,
        e.BAIRRO, e.CIDADE, e.UF, e.CEP, e.DDD, e.TEL, e.CNAE, e.FUNCIONARIOS,
        e.SITE, e.BASE, e.PORTE,
        p.nome as nome_pesquisa,
        p.id_modelo_classificacao_lead_fk,
        qt.nome as nome_questionario,
        cl.cor as cor_classificacao
    FROM pesquisa_empresa pe
    LEFT JOIN empresas e ON pe.id_empresa_fk = e.ID_EMPRESA
    LEFT JOIN pesquisas p ON pe.id_pesquisa_fk = p.id
    LEFT JOIN questionario_template qt ON p.id_questionario_template_fk = qt.id
    LEFT JOIN classificacao_leads_modelos_itens cl
        ON pe.nota_total >= cl.faixa_minima
       AND pe.nota_total <= cl.faixa_maxima
       AND cl.id_modelo_fk = p.id_modelo_classificacao_lead_fk
       AND cl.ativo = 'S'
    WHERE pe.id = ?
");
$stmt->bind_param('i', $id);
$stmt->execute();
$pesquisa = $stmt->get_result()->fetch_assoc();

if (!$pesquisa) {
    die('Pesquisa não encontrada.');
}

$idModeloClassificacaoPesquisa = (int)($pesquisa['id_modelo_classificacao_lead_fk'] ?? 0);
if ($idModeloClassificacaoPesquisa <= 0) {
    $idModeloClassificacaoPesquisa = garantir_modelo_classificacao_lead_padrao($conn);
}

// Buscar status do questionário
$nome_status_questionario = '-';
if (!empty($pesquisa['id_status_questionario_fk'])) {
    $stmt_st = $conn->prepare("SELECT nome_status FROM statusdoquestionario WHERE id_status = ?");
    $stmt_st->bind_param('i', $pesquisa['id_status_questionario_fk']);
    $stmt_st->execute();
    $rs = $stmt_st->get_result()->fetch_assoc();
    if ($rs) $nome_status_questionario = $rs['nome_status'];
}

// Buscar contatos
$stmt_contatos = $conn->prepare("
    SELECT ce.*, cs.contato_status as status_nome 
    FROM contatos_empresa ce 
    LEFT JOIN contato_status cs ON ce.idcontato_status = cs.idcontato_status 
    WHERE ce.id_empresa = ?
        AND cs.contato_status = 'Positiva'
        ORDER BY ce.nome ASC
");
$stmt_contatos->bind_param('i', $pesquisa['id_empresa_fk']);
$stmt_contatos->execute();
$contatos = $stmt_contatos->get_result();

// Buscar perguntas
$stmt_perguntas = $conn->prepare("
    SELECT qtp.* FROM questionario_template_perguntas qtp
    LEFT JOIN questionario_template qt ON qtp.id_questionario_template_fk = qt.id
    LEFT JOIN pesquisas p ON p.id_questionario_template_fk = qt.id
    WHERE p.id = ?
    ORDER BY qtp.ordem ASC
");
$stmt_perguntas->bind_param('i', $pesquisa['id_pesquisa_fk']);
$stmt_perguntas->execute();
$perguntas_result = $stmt_perguntas->get_result();
$perguntas_lista = [];
while ($pergunta_row = $perguntas_result->fetch_assoc()) {
    $perguntas_lista[] = $pergunta_row;
}

// Buscar respostas
$respostas_existentes = [];
$stmt_respostas = $conn->prepare("SELECT id_pergunta_fk, resposta FROM pesquisa_respostas WHERE id_pesquisa_empresa_fk = ?");
$stmt_respostas->bind_param('i', $id);
$stmt_respostas->execute();
$res = $stmt_respostas->get_result();
while ($row = $res->fetch_assoc()) {
    $respostas_existentes[$row['id_pergunta_fk']] = $row['resposta'];
}

// Recalcular nota no PDF a partir das respostas salvas para manter consistência com o questionário
$nota_total = 0.0;
foreach ($perguntas_lista as $pergunta_meta) {
    $id_pergunta_meta = (int)($pergunta_meta['id'] ?? 0);
    if ($id_pergunta_meta <= 0 || !isset($respostas_existentes[$id_pergunta_meta])) {
        continue;
    }

    $nota_total += calcular_nota_resposta_pdf(
        $respostas_existentes[$id_pergunta_meta],
        $pergunta_meta['tipo_resposta'] ?? '',
        $pergunta_meta['opcoes'] ?? ''
    );
}

$classificacao = '-';
$cor_classificacao = '#6c757d';
$stmt_classif_pdf = $conn->prepare("SELECT classificacao, cor FROM classificacao_leads_modelos_itens WHERE id_modelo_fk = ? AND ativo = 'S' AND ? >= faixa_minima AND ? <= faixa_maxima ORDER BY ordem LIMIT 1");
if ($stmt_classif_pdf) {
    $stmt_classif_pdf->bind_param('idd', $idModeloClassificacaoPesquisa, $nota_total, $nota_total);
    $stmt_classif_pdf->execute();
    $classif_pdf = $stmt_classif_pdf->get_result()->fetch_assoc();
    if ($classif_pdf) {
        $classificacao = $classif_pdf['classificacao'] ?? '-';
        $cor_classificacao = $classif_pdf['cor'] ?? '#6c757d';
    }
    $stmt_classif_pdf->close();
}
$nome_empresa_pdf = 'Empresa';
if (!empty(trim($pesquisa['NOME_FANTASIA'] ?? ''))) {
    $nome_empresa_pdf = trim($pesquisa['NOME_FANTASIA']);
} elseif (!empty(trim($pesquisa['EMPRESA'] ?? ''))) {
    $nome_empresa_pdf = trim($pesquisa['EMPRESA']);
}
$nome_questionario_pdf = !empty(trim($pesquisa['nome_questionario'] ?? '')) ? trim($pesquisa['nome_questionario']) : 'questionario';
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($nome_empresa_pdf) ?> - <?= htmlspecialchars($pesquisa['nome_pesquisa'] ?? 'Pesquisa') ?> - Questionário #<?= $id ?></title>
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }
        
        :root {
            --ink: #1b2a4a;
            --ink-light: #2d4a7a;
            --accent: #c0392b;
            --steel: #34495e;
            --line: #bdc3c7;
            --bg: #ecf0f1;
            --bg-alt: #f7f9fa;
            --white: #ffffff;
            --success: #27ae60;
            --warning: #e67e22;
        }
        
        @media print {
            body { margin: 0; padding: 8px; font-size: 11.05pt; background: white; }
            .no-print { display: none !important; }
            .section { page-break-inside: auto; break-inside: auto; }
            .container { box-shadow: none; border: 1px solid #ccc; }
            .container, .content, .section, .section-body, .question-card, .contato-card {
                overflow: visible !important;
            }
            .section-header, .question-header, .contato-card-header {
                page-break-after: avoid;
                break-after: avoid-page;
            }
            .contato-card, .question-card, .field, .observation-box {
                page-break-inside: avoid;
                break-inside: avoid-page;
            }
        }
        
        body {
            font-family: 'Consolas', 'Courier New', 'Lucida Console', monospace;
            background: var(--bg);
            color: var(--ink);
            line-height: 1.45;
            padding: 20px;
            font-size: 16.25px;
        }
        
        .container {
            max-width: 1000px;
            margin: 0 auto;
            background: var(--white);
            border: 2px solid var(--ink);
            overflow: hidden;
        }
        
        /* Header - estilo blueprint/técnico */
        .header {
            background: var(--ink);
            color: var(--white);
            padding: 16px 24px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 10px;
            border-bottom: 3px solid var(--accent);
        }
        .header-left { flex: 1; }
        .header-pesquisa {
            font-size: 1.1em;
            font-weight: 700;
            letter-spacing: 1.5px;
            text-transform: uppercase;
        }
        .header-subtitle {
            font-size: 0.78em;
            opacity: 0.65;
            margin-top: 4px;
            letter-spacing: 0.5px;
        }
        .header-actions { display: flex; gap: 8px; }
        
        .btn {
            padding: 7px 14px;
            border: 1px solid rgba(255,255,255,0.3);
            border-radius: 2px;
            cursor: pointer;
            font-size: 0.78em;
            font-weight: 600;
            font-family: inherit;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 5px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            transition: all 0.15s;
        }
        .btn:hover { opacity: 0.8; }
        .btn-primary { background: var(--accent); color: var(--white); border-color: var(--accent); }
        .btn-secondary { background: transparent; color: var(--white); }
        
        /* Score Card - barra de indicadores */
        .score-card {
            background: var(--bg-alt);
            border-bottom: 2px solid var(--ink);
            padding: 12px 24px;
            display: flex;
            align-items: center;
            gap: 28px;
            flex-wrap: wrap;
        }
        .score-item { display: flex; align-items: center; gap: 8px; }
        .score-label {
            font-size: 0.72em;
            color: var(--steel);
            text-transform: uppercase;
            letter-spacing: 1px;
            font-weight: 700;
        }
        .score-value { font-size: 1.4em; font-weight: 700; color: var(--ink); }
        .score-badge {
            padding: 3px 10px;
            border-radius: 2px;
            font-weight: 700;
            font-size: 0.78em;
            letter-spacing: 0.5px;
            text-transform: uppercase;
        }
        
        /* Sections */
        .content { padding: 20px 24px; }
        
        .section {
            margin-bottom: 18px;
            border: 1px solid var(--line);
            overflow: hidden;
        }
        
        .section-header {
            background: var(--ink);
            color: var(--white);
            padding: 8px 14px;
            font-weight: 700;
            font-size: 0.78em;
            text-transform: uppercase;
            letter-spacing: 1.5px;
            border-bottom: 2px solid var(--accent);
        }
        
        .section-body {
            padding: 14px;
            background: var(--white);
        }
        
        /* Field Grid */
        .field-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: 10px; }
        .field-grid-2 { grid-template-columns: repeat(2, 1fr); }
        .field-grid-3 { grid-template-columns: repeat(3, 1fr); }
        .field-grid-4 { grid-template-columns: repeat(4, 1fr); }
        
        .field { display: flex; flex-direction: column; gap: 1px; }
        .field-label {
            font-size: 0.65em;
            color: var(--steel);
            text-transform: uppercase;
            font-weight: 700;
            letter-spacing: 1px;
        }
        .field-value {
            font-size: 0.85em;
            color: var(--ink);
            padding: 5px 8px;
            background: var(--bg-alt);
            border: 1px solid var(--line);
            border-left: 3px solid var(--ink-light);
            min-height: 28px;
            display: flex;
            align-items: center;
        }
        .field-full { grid-column: 1 / -1; }
        
        /* Contato Cards */
        .contatos-grid {
            display: grid;
            grid-template-columns: 1fr;
            gap: 10px;
        }
        .contato-card {
            border: 1px solid var(--line);
            border-left: 3px solid var(--ink-light);
            padding: 10px 12px;
            background: var(--bg-alt);
            font-size: 0.96em;
        }
        .contato-card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 6px;
            padding-bottom: 5px;
            border-bottom: 1px dashed var(--line);
        }
        .contato-card-nome {
            font-weight: 700;
            font-size: 1.14em;
            color: var(--ink);
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        .contato-tag {
            font-size: 0.84em;
            padding: 2px 7px;
            border: 1px solid var(--ink-light);
            color: var(--ink-light);
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        .contato-card-grid {
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
            gap: 4px;
        }
        .contato-field {
            display: flex;
            gap: 4px;
            line-height: 1.6;
        }
        .contato-field-label {
            color: var(--steel);
            font-weight: 700;
            font-size: 1.02em;
            white-space: nowrap;
            min-width: 50px;
        }
        .contato-field-value {
            color: var(--ink);
            font-size: 1.02em;
            word-break: break-all;
        }
        .contato-field-full { grid-column: 1 / -1; }
        
        /* Questions */
        .question-card {
            border: 1px solid var(--line);
            margin-bottom: 8px;
            overflow: hidden;
        }
        .question-header {
            background: var(--bg-alt);
            padding: 8px 12px;
            border-bottom: 1px solid var(--line);
            display: flex;
            align-items: flex-start;
            gap: 8px;
        }
        .question-number {
            background: var(--ink);
            color: var(--white);
            width: 20px; height: 20px;
            display: flex; align-items: center; justify-content: center;
            font-size: 0.7em; font-weight: 700; flex-shrink: 0;
        }
        .question-text { font-weight: 600; color: var(--ink); flex: 1; font-size: 0.85em; }
        .question-answer {
            padding: 8px 12px;
            background: var(--white);
            border-left: 3px solid var(--ink-light);
            color: var(--ink);
            font-size: 0.82em;
        }
        .question-answer:empty::before { content: '—'; color: var(--line); }
        
        /* Observations */
        .observation-box {
            background: var(--bg-alt);
            border: 1px solid var(--line);
            border-left: 3px solid var(--warning);
            padding: 10px;
            min-height: 50px;
            font-size: 0.82em;
            line-height: 1.6;
        }
        .observation-box:empty::before { content: 'Sem observações registradas.'; color: var(--steel); font-style: italic; }
        
        /* Footer */
        .footer {
            background: var(--ink);
            padding: 10px 24px;
            text-align: center;
            color: rgba(255,255,255,0.5);
            font-size: 0.7em;
            letter-spacing: 1px;
            text-transform: uppercase;
            border-top: 2px solid var(--accent);
        }
        
        @media (max-width: 768px) {
            .field-grid-2, .field-grid-3, .field-grid-4 { grid-template-columns: 1fr; }
            .contatos-grid { grid-template-columns: 1fr; }
            .contato-card-grid { grid-template-columns: 1fr; }
            .header { flex-direction: column; text-align: center; }
        }

        /* Regras usadas no html2pdf (tela), para evitar corte de linhas/cards */
        body.pdf-export .container,
        body.pdf-export .content,
        body.pdf-export .section,
        body.pdf-export .section-body,
        body.pdf-export .question-card,
        body.pdf-export .contato-card {
            overflow: visible !important;
        }

        body.pdf-export .section {
            page-break-inside: auto;
            break-inside: auto;
        }

        body.pdf-export .section-header,
        body.pdf-export .question-header,
        body.pdf-export .contato-card-header {
            page-break-after: avoid;
            break-after: avoid-page;
        }

        body.pdf-export .contato-card,
        body.pdf-export .question-card,
        body.pdf-export .field,
        body.pdf-export .observation-box {
            page-break-inside: avoid;
            break-inside: avoid-page;
        }
    </style>
</head>
<body>

<div class="container">
    <!-- Header -->
    <div class="header">
        <div class="header-left">
            <div class="header-pesquisa"><?= htmlspecialchars($pesquisa['nome_pesquisa'] ?? 'Pesquisa') ?></div>
            <div class="header-subtitle">REF #<?= $id ?> &mdash; <?= htmlspecialchars($pesquisa['NOME_FANTASIA'] ?? 'Empresa') ?> &mdash; <?= htmlspecialchars($pesquisa['nome_questionario'] ?? '') ?></div>
        </div>
        <div class="header-actions no-print">
            <button type="button" onclick="baixarPdfPesquisa()" class="btn btn-primary">BAIXAR PDF</button>
            <a href="responder_pesquisa.php?id=<?= $id ?>" class="btn btn-secondary">&larr; VOLTAR</a>
        </div>
    </div>
    
    <!-- Score Card -->
    <div class="score-card">
        <div class="score-item">
            <span class="score-label">Nota Total:</span>
            <span class="score-value"><?= number_format($nota_total, 0) ?></span>
        </div>
        <div class="score-item">
            <span class="score-label">Classificação:</span>
            <span class="score-badge" style="background-color: <?= $cor_classificacao ?>; color: white;">
                <?= htmlspecialchars($classificacao) ?>
            </span>
        </div>
        <div class="score-item">
            <span class="score-label">Status:</span>
            <span class="score-badge" style="background: var(--warning); color: white;">
                <?= htmlspecialchars($nome_status_questionario) ?>
            </span>
        </div>
    </div>
    
    <div class="content">

        <!-- Dados Cadastrais -->
        <div class="section">
            <div class="section-header">Dados Cadastrais</div>
            <div class="section-body">
                <div class="field-grid field-grid-2">
                    <div class="field">
                        <span class="field-label">Razão Social</span>
                        <span class="field-value"><?= htmlspecialchars($pesquisa['EMPRESA'] ?? '-') ?></span>
                    </div>
                    <div class="field">
                        <span class="field-label">Nome Fantasia</span>
                        <span class="field-value"><?= htmlspecialchars($pesquisa['NOME_FANTASIA'] ?? '-') ?></span>
                    </div>
                </div>
                <div class="field-grid field-grid-3" style="margin-top: 15px;">
                    <div class="field">
                        <span class="field-label">CNPJ</span>
                        <span class="field-value"><?= htmlspecialchars($pesquisa['CNPJ'] ?? '-') ?></span>
                    </div>
                    <div class="field">
                        <span class="field-label">CNAE</span>
                        <span class="field-value"><?= htmlspecialchars($pesquisa['CNAE'] ?? '-') ?></span>
                    </div>
                    <div class="field">
                        <span class="field-label">Telefone</span>
                        <span class="field-value"><?= formatar_telefone($pesquisa['DDD'], $pesquisa['TEL']) ?></span>
                    </div>
                </div>
                <div class="field-grid field-grid-4" style="margin-top: 15px;">
                    <div class="field" style="grid-column: span 2;">
                        <span class="field-label">Endereço</span>
                        <span class="field-value"><?= htmlspecialchars(trim(($pesquisa['RUA'] ?? '') . ', ' . ($pesquisa['NUMERO'] ?? '') . ' ' . ($pesquisa['COMPL_NUM'] ?? ''))) ?></span>
                    </div>
                    <div class="field">
                        <span class="field-label">Bairro</span>
                        <span class="field-value"><?= htmlspecialchars($pesquisa['BAIRRO'] ?? '-') ?></span>
                    </div>
                    <div class="field">
                        <span class="field-label">CEP</span>
                        <span class="field-value"><?= htmlspecialchars($pesquisa['CEP'] ?? '-') ?></span>
                    </div>
                </div>
                <div class="field-grid field-grid-4" style="margin-top: 15px;">
                    <div class="field">
                        <span class="field-label">Cidade</span>
                        <span class="field-value"><?= htmlspecialchars($pesquisa['CIDADE'] ?? '-') ?></span>
                    </div>
                    <div class="field">
                        <span class="field-label">UF</span>
                        <span class="field-value"><?= htmlspecialchars($pesquisa['UF'] ?? '-') ?></span>
                    </div>
                    <div class="field">
                        <span class="field-label">Funcionários</span>
                        <span class="field-value"><?= htmlspecialchars($pesquisa['FUNCIONARIOS'] ?? '-') ?></span>
                    </div>
                    <div class="field">
                        <span class="field-label">Porte</span>
                        <span class="field-value"><?= htmlspecialchars($pesquisa['PORTE'] ?? '-') ?></span>
                    </div>
                </div>
                <div class="field-grid" style="margin-top: 15px;">
                    <div class="field field-full">
                        <span class="field-label">Site</span>
                        <span class="field-value"><?= htmlspecialchars($pesquisa['SITE'] ?? '-') ?></span>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Contatos -->
        <div class="section">
            <div class="section-header">Contatos do Questionario</div>
            <div class="section-body">
                <?php if ($contatos->num_rows > 0): ?>
                <div class="contatos-grid">
                    <?php $contatos->data_seek(0); while($c = $contatos->fetch_assoc()): 
                        $nome_completo = trim(($c['nome'] ?? '') . ' ' . ($c['sobrenome'] ?? ''));
                        $endereco_contato = trim(($c['endereco'] ?? '') . ((!empty($c['numero'])) ? ', ' . $c['numero'] : '') . ((!empty($c['complemento'])) ? ' ' . $c['complemento'] : ''));
                        $cidade_uf_cep = trim(
                            ($c['bairro'] ?? '') . 
                            ((!empty($c['cidade'])) ? ' - ' . $c['cidade'] : '') . 
                            ((!empty($c['uf'])) ? '/' . $c['uf'] : '') . 
                            ((!empty($c['cep'])) ? ' - CEP ' . $c['cep'] : '')
                        );
                    ?>
                    <div class="contato-card">
                        <div class="contato-card-header">
                            <span class="contato-card-nome"><?= htmlspecialchars($nome_completo ?: '-') ?></span>
                            <?php if (!empty($c['status_nome'])): ?>
                                <span class="contato-tag"><?= htmlspecialchars($c['status_nome']) ?></span>
                            <?php endif; ?>
                        </div>
                        <div class="contato-card-grid">
                            <div class="contato-field">
                                <span class="contato-field-label">Status:</span>
                                <span class="contato-field-value"><?= htmlspecialchars($c['status_nome'] ?? '-') ?></span>
                            </div>
                            <div class="contato-field">
                                <span class="contato-field-label">Cargo:</span>
                                <span class="contato-field-value"><?= htmlspecialchars($c['cargo'] ?? '-') ?></span>
                            </div>
                            <div class="contato-field">
                                <span class="contato-field-label">Area:</span>
                                <span class="contato-field-value"><?= htmlspecialchars($c['depto'] ?? '-') ?></span>
                            </div>
                            <div class="contato-field">
                                <span class="contato-field-label">Sexo:</span>
                                <span class="contato-field-value"><?= htmlspecialchars($c['sexo'] ?? '-') ?></span>
                            </div>
                            <div class="contato-field">
                                <span class="contato-field-label">Tel:</span>
                                <span class="contato-field-value"><?= formatar_telefone($c['ddd'], $c['tel']) ?></span>
                            </div>
                            <div class="contato-field">
                                <span class="contato-field-label">Cel:</span>
                                <span class="contato-field-value"><?= formatar_telefone($c['ddd'], $c['celular']) ?></span>
                            </div>
                            <div class="contato-field">
                                <span class="contato-field-label">Ramal:</span>
                                <span class="contato-field-value"><?= htmlspecialchars($c['ramal'] ?? '-') ?></span>
                            </div>
                            <div class="contato-field contato-field-full">
                                <span class="contato-field-label">Email:</span>
                                <span class="contato-field-value"><?= htmlspecialchars($c['email'] ?? '-') ?></span>
                            </div>
                            <?php if (!empty($c['linkedin'])): ?>
                            <div class="contato-field contato-field-full">
                                <span class="contato-field-label">LinkedIn:</span>
                                <span class="contato-field-value"><?= htmlspecialchars($c['linkedin']) ?></span>
                            </div>
                            <?php endif; ?>
                            <?php if (!empty($endereco_contato)): ?>
                            <div class="contato-field contato-field-full">
                                <span class="contato-field-label">Ender.:</span>
                                <span class="contato-field-value"><?= htmlspecialchars($endereco_contato) ?></span>
                            </div>
                            <?php endif; ?>
                            <?php if (!empty($cidade_uf_cep)): ?>
                            <div class="contato-field contato-field-full">
                                <span class="contato-field-label">Local:</span>
                                <span class="contato-field-value"><?= htmlspecialchars($cidade_uf_cep) ?></span>
                            </div>
                            <?php endif; ?>
                            <?php if (!empty($c['observacoes'])): ?>
                            <div class="contato-field contato-field-full">
                                <span class="contato-field-label">Obs:</span>
                                <span class="contato-field-value"><?= htmlspecialchars($c['observacoes']) ?></span>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endwhile; ?>
                </div>
                <?php else: ?>
                <div style="text-align: center; color: var(--steel); padding: 16px; font-size: 0.82em;">
                    Nenhum contato cadastrado.
                </div>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Questões de Qualificação -->
        <?php if (count($perguntas_lista) > 0): ?>
        <div class="section">
            <div class="section-header">Questões de Qualificação</div>
            <div class="section-body">
                <?php 
                $num = 1;
                foreach($perguntas_lista as $p): 
                    $resp = $respostas_existentes[$p['id']] ?? '';
                    $is_sub = !empty($p['id_pergunta_pai']);

                    // Mostrar no PDF apenas sub-perguntas que foram respondidas
                    if ($is_sub && !resposta_tem_conteudo_pdf($resp, $p['tipo_resposta'] ?? '')) {
                        continue;
                    }
                    
                    // Verificar se é campos_personalizados
                    $is_campos_pers = ($p['tipo_resposta'] === 'campos_personalizados');
                    $resp_limpa = $resp;
                    if (!$is_campos_pers && strpos($resp, '|') !== false) {
                        $partes = explode('|', $resp);
                        $textos = [];
                        for ($i = 0; $i < count($partes); $i += 2) {
                            $txt = trim((string)($partes[$i] ?? ''));
                            if ($txt !== '') $textos[] = $txt;
                        }
                        $resp_limpa = !empty($textos) ? implode(', ', $textos) : '';
                    }
                ?>
                <div class="question-card" style="<?= $is_sub ? 'margin-left: 20px; border-left: 3px solid #ffc107;' : '' ?>">
                    <div class="question-header">
                        <span class="question-number"><?= htmlspecialchars($p['numero']) ?></span>
                        <span class="question-text"><?= htmlspecialchars($p['pergunta']) ?></span>
                    </div>
                    <?php if ($is_campos_pers): ?>
                        <?php 
                        $campos_vals_pdf = json_decode($resp, true);
                        $campos_def_pdf = json_decode($p['opcoes'], true);
                        if (is_array($campos_def_pdf) && is_array($campos_vals_pdf)):
                        ?>
                        <div class="question-answer" style="padding: 10px 12px;">
                            <?php foreach($campos_def_pdf as $campo_pdf): 
                                $cn = $campo_pdf['nome'] ?? '';
                                $cv = $campos_vals_pdf[$cn] ?? '-';
                            ?>
                            <div style="margin-bottom: 4px;">
                                <strong style="font-size: 0.85em; color: var(--steel);"><?= htmlspecialchars($cn) ?>:</strong>
                                <span><?= htmlspecialchars($cv ?: '-') ?></span>
                            </div>
                            <?php endforeach; ?>
                        </div>
                        <?php else: ?>
                        <div class="question-answer"><?= nl2br(htmlspecialchars($resp_limpa ?: '-')) ?></div>
                        <?php endif; ?>
                    <?php else: ?>
                        <div class="question-answer"><?= nl2br(htmlspecialchars($resp_limpa ?: '-')) ?></div>
                    <?php endif; ?>
                </div>
                <?php $num++; endforeach; ?>
            </div>
        </div>
        <?php endif; ?>
        
        <!-- Observações -->
        <div class="section">
            <div class="section-header">Observações</div>
            <div class="section-body">
                <div class="field" style="margin-bottom: 15px;">
                    <span class="field-label">Observações Gerais</span>
                    <div class="observation-box"><?= nl2br(htmlspecialchars($pesquisa['observacoes_gerais'] ?? '')) ?></div>
                </div>
                <?php if (!empty($pesquisa['mensagem_fechamento'])): ?>
                <div class="field">
                    <span class="field-label">Mensagem de Fechamento</span>
                    <div class="observation-box"><?= nl2br(htmlspecialchars($pesquisa['mensagem_fechamento'])) ?></div>
                </div>
                <?php endif; ?>

            </div>
        </div>
        
        <!-- Agendamento de Reunião -->
        <?php if (!empty($pesquisa['agendar_reuniao']) && $pesquisa['agendar_reuniao'] === 'S'): ?>
        <div class="section">
            <div class="section-header">Reunião Agendada</div>
            <div class="section-body">
                <div class="field-grid field-grid-2">
                    <div class="field">
                        <span class="field-label">Data da Reunião</span>
                        <span class="field-value"><?= $pesquisa['data_reuniao'] ? date('d/m/Y', strtotime($pesquisa['data_reuniao'])) : '-' ?></span>
                    </div>
                    <div class="field">
                        <span class="field-label">Horário da Reunião</span>
                        <span class="field-value"><?= htmlspecialchars($pesquisa['horario_reuniao'] ?? '-') ?></span>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
    
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
<script>
function gerarNomeArquivoPdf() {
    var nomeEmpresa = <?= json_encode($nome_empresa_pdf, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
    var nomeQuestionario = <?= json_encode($nome_questionario_pdf, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;

    return (String(nomeEmpresa) + '_' + String(nomeQuestionario) + '_REF_' + <?= (int)$id ?>)
        .normalize('NFD')
        .replace(/[\u0300-\u036f]/g, '')
        .replace(/[^a-zA-Z0-9_-]+/g, '_')
        .replace(/_+/g, '_')
        .replace(/^_|_$/g, '');
}

function baixarPdfPesquisa() {
    var arquivo = gerarNomeArquivoPdf();
    var alvo = document.querySelector('.container');

    if (!alvo || typeof html2pdf === 'undefined') {
        document.title = arquivo;
        window.print();
        return;
    }

    document.body.classList.add('pdf-export');

    var opcoes = {
        margin: [8, 8, 8, 8],
        filename: arquivo + '.pdf',
        image: { type: 'jpeg', quality: 0.98 },
        html2canvas: {
            scale: 2,
            useCORS: true,
            ignoreElements: function (element) {
                return element.classList && element.classList.contains('no-print');
            }
        },
        jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' },
        pagebreak: {
            mode: ['avoid-all', 'css', 'legacy'],
            avoid: ['.question-card', '.contato-card', '.observation-box', '.section-header', '.question-header', '.contato-card-header']
        }
    };

    html2pdf()
        .set(opcoes)
        .from(alvo)
        .save()
        .finally(function () {
            document.body.classList.remove('pdf-export');
        });
}
</script>

</body>
</html>
<?php $conn->close(); ?>
