{% extends 'layouts/company.twig' %}
{% block title %}Respostas da Pesquisa - {{ product.nome }} - {{ app_name }}{% endblock %}
{% block content %}
<style>
.pq-review-page { max-width: 1180px; margin: 0 auto; }
.pq-review-hero {
    background: linear-gradient(135deg, #eff6ff 0%, #f8fafc 100%);
    border: 1px solid #dbeafe;
    border-radius: 18px;
    padding: 22px 24px;
    margin-bottom: 22px;
}
.pq-charts-grid {
    display: grid;
    grid-template-columns: 1fr;
    gap: 16px;
    margin-bottom: 28px;
}
@media (min-width: 992px) {
    .pq-charts-grid { grid-template-columns: 1fr 1fr; }
}
.pq-chart-card {
    border: 1px solid #e2e8f0;
    border-radius: 16px;
    background: #fff;
    padding: 16px 18px 12px;
    box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
}
.pq-chart-card h3 {
    font-size: 0.98rem;
    font-weight: 700;
    color: #0f172a;
    margin: 0 0 4px;
}
.pq-chart-meta {
    color: #64748b;
    font-size: 0.82rem;
    margin-bottom: 10px;
}
.pq-chart-wrap {
    position: relative;
    height: 260px;
}
.pq-response-card {
    border: 1px solid #e2e8f0;
    border-radius: 16px;
    background: #fff;
    margin-bottom: 16px;
    overflow: hidden;
}
.pq-response-head {
    display: flex;
    justify-content: space-between;
    gap: 12px;
    flex-wrap: wrap;
    padding: 16px 18px;
    background: #f8fafc;
    border-bottom: 1px solid #e2e8f0;
}
.pq-answer-grid {
    display: grid;
    grid-template-columns: 1fr;
    gap: 12px;
    padding: 16px 18px 18px;
}
@media (min-width: 992px) {
    .pq-answer-grid { grid-template-columns: 1fr 1fr; }
}
.pq-answer-item {
    border: 1px solid #e2e8f0;
    border-radius: 12px;
    padding: 12px 14px;
    background: #fcfdff;
}
.pq-answer-item .q {
    font-weight: 700;
    color: #0f172a;
    margin-bottom: 6px;
}
.pq-answer-item .a {
    color: #334155;
    white-space: pre-wrap;
}
</style>

<div class="pq-review-page">
    <div class="page-header">
        <div>
            <h1 class="page-title mb-1"><i class="bi bi-clipboard2-data me-2"></i>Respostas da Pesquisa</h1>
            <p class="text-muted mb-0">{{ product.nome }}</p>
        </div>
        <div class="page-actions">
            <a href="{{ url('products/' ~ product.id) }}" class="btn btn-outline-secondary">
                <i class="bi bi-arrow-left me-1"></i>Voltar ao produto
            </a>
        </div>
    </div>

    <div class="pq-review-hero">
        <div class="fw-semibold mb-1">{{ product.pesquisa_qualidade_titulo|default(product.nome) }}</div>
        <div class="text-muted small mb-3">
            {{ response_count }} resposta(s) · {{ eligible_count }} elegível(is) ao prêmio
            {% if questions|length > 0 %} · {{ questions|length }} pergunta(s){% endif %}
        </div>

        {% if winner_info %}
        <div class="alert alert-success mb-3" style="border-radius:14px;">
            <div class="fw-bold mb-1"><i class="bi bi-trophy-fill me-1"></i> Já houve ganhador para este prêmio</div>
            <div>
                <strong>E-mail do ganhador:</strong>
                {{ winner_info.email ? winner_info.email : winner_info.label }}
            </div>
            {% if winner_info.telefone %}
            <div><strong>Telefone:</strong> {{ winner_info.telefone }}</div>
            {% endif %}
            {% if winner_info.premio_data_fmt %}
            <div><strong>Data do prêmio:</strong> {{ winner_info.premio_data_fmt }}</div>
            {% endif %}
            {% if winner_info.sorteado_em_fmt %}
            <div class="small text-muted mt-1">Sorteado em {{ winner_info.sorteado_em_fmt }}</div>
            {% endif %}
        </div>
        {% endif %}

        {% if product.pesquisa_qualidade_premio_ativo and product.pesquisa_qualidade_premio_texto %}
        <div class="p-3 rounded-3" style="background:#fff7ed;color:#9a3412;font-weight:600;">
            {{ product.pesquisa_qualidade_premio_texto }}
        </div>
        {% endif %}
    </div>

    {% if charts is defined and charts|length > 0 %}
    <section class="mb-2">
        <h2 class="h5 mb-3"><i class="bi bi-pie-chart me-1"></i> Visão geral por pergunta</h2>
        <div class="pq-charts-grid">
            {% for chart in charts %}
            <div class="pq-chart-card">
                <h3>{{ chart.index }}. {{ chart.pergunta }}</h3>
                <div class="pq-chart-meta">
                    {{ chart.total }} resposta(s)
                    ·
                    {% if chart.chart_type == 'doughnut' %}Gráfico pizza{% else %}Gráfico de barras{% endif %}
                </div>
                <div class="pq-chart-wrap">
                    <canvas id="pqChart{{ loop.index0 }}" aria-label="Gráfico da pergunta {{ chart.index }}"></canvas>
                </div>
            </div>
            {% endfor %}
        </div>
    </section>
    {% endif %}

    <h2 class="h5 mb-3"><i class="bi bi-people me-1"></i> Respostas individuais</h2>

    {% if responses|length == 0 %}
        <div class="alert alert-light border">Nenhuma resposta recebida ainda.</div>
    {% else %}
        {% for resp in responses %}
        <article class="pq-response-card">
            <div class="pq-response-head">
                <div>
                    <div class="fw-semibold">
                        {% if resp.email %}{{ resp.email }}{% elseif resp.telefone %}{{ resp.telefone }}{% else %}Participante #{{ resp.id }}{% endif %}
                    </div>
                    <div class="small text-muted">
                        {% if resp.telefone and resp.email %}{{ resp.telefone }} · {% endif %}
                        {{ resp.created_at|date('d/m/Y H:i') }}
                    </div>
                </div>
                <div class="d-flex align-items-center gap-2 flex-wrap">
                    {% if resp.elegivel_premio %}
                        <span class="badge bg-success">Elegível ao prêmio</span>
                    {% else %}
                        <span class="badge bg-secondary">Somente pesquisa</span>
                    {% endif %}
                    <form method="post"
                          action="{{ url('products/' ~ product.id ~ '/pesquisa-qualidade/respostas/' ~ resp.id ~ '/delete') }}"
                          onsubmit="return confirm('Excluir esta resposta? Esta ação não pode ser desfeita.');">
                        <input type="hidden" name="_csrf_token" value="{{ csrf_token }}">
                        <button type="submit" class="btn btn-sm btn-outline-danger" title="Excluir resposta">
                            <i class="bi bi-trash"></i> Excluir
                        </button>
                    </form>
                </div>
            </div>

            <div class="pq-answer-grid">
                {% if resp.answers is defined and resp.answers|length > 0 %}
                    {% for answer in resp.answers %}
                    <div class="pq-answer-item">
                        <div class="q">{{ loop.index }}. {{ answer.pergunta }}</div>
                        <div class="a">{{ answer.resposta }}</div>
                    </div>
                    {% endfor %}
                {% else %}
                    <div class="text-muted px-1 py-2">Sem detalhe de respostas para este registro.</div>
                {% endif %}
            </div>
        </article>
        {% endfor %}
    {% endif %}
</div>

{% if charts is defined and charts|length > 0 %}
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>
<script>
(function () {
    const charts = {{ charts|json_encode|raw }};
    if (!Array.isArray(charts) || typeof Chart === 'undefined') return;

    charts.forEach(function (chart, idx) {
        const canvas = document.getElementById('pqChart' + idx);
        if (!canvas) return;

        const isPie = chart.chart_type === 'doughnut';
        new Chart(canvas, {
            type: isPie ? 'doughnut' : 'bar',
            data: {
                labels: chart.labels || [],
                datasets: [{
                    label: 'Respostas',
                    data: chart.values || [],
                    backgroundColor: chart.colors || [],
                    borderColor: isPie ? '#ffffff' : (chart.colors || []),
                    borderWidth: isPie ? 2 : 0,
                    borderRadius: isPie ? 0 : 8,
                    maxBarThickness: 48
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: isPie,
                        position: 'bottom'
                    },
                    tooltip: {
                        callbacks: {
                            label: function (ctx) {
                                const value = Number(ctx.raw || 0);
                                const total = Number(chart.total || 0);
                                const pct = total > 0 ? ((value / total) * 100).toFixed(1) : '0.0';
                                return (ctx.label || '') + ': ' + value + ' (' + pct + '%)';
                            }
                        }
                    }
                },
                scales: isPie ? {} : {
                    x: {
                        ticks: { autoSkip: false, maxRotation: 0, minRotation: 0 },
                        grid: { display: false }
                    },
                    y: {
                        beginAtZero: true,
                        ticks: { precision: 0 },
                        grid: { color: '#e2e8f0' }
                    }
                }
            }
        });
    });
})();
</script>
{% endif %}
{% endblock %}
