<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800 fw-bold">Hasil Kuesioner Kepuasan Pelanggan</h1>

    <!-- Filter Form for Month and Year -->
    <div class="card card-neumorphic mb-4">
        <div class="card-header bg-transparent border-0 py-3">
            <h6 class="m-0 fw-bold text-dark">Filter Hasil Kuesioner</h6>
        </div>
        <div class="card-body">
            <form action="?page=survey_results" method="GET" class="form-inline">
                <input type="hidden" name="page" value="survey_results">
                <div class="row align-items-end">
                    <div class="col-md-4 mb-3">
                        <label for="monthFilter" class="form-label">Bulan:</label>
                        <select name="month" id="monthFilter" class="form-control">
                            <option value="">Semua Bulan</option>
                            <?php for ($m = 1; $m <= 12; $m++): ?>
                                <option value="<?= sprintf('%02d', $m) ?>" <?= (isset($month) && $month == sprintf('%02d', $m)) ? 'selected' : '' ?>>
                                    <?= date('F', mktime(0, 0, 0, $m, 1)) ?>
                                </option>
                            <?php endfor; ?>
                        </select>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label for="yearFilter" class="form-label">Tahun:</label>
                        <select name="year" id="yearFilter" class="form-control">
                            <option value="">Semua Tahun</option>
                            <?php for ($y = date('Y'); $y >= date('Y') - 5; $y--): ?>
                                <option value="<?= $y ?>" <?= (isset($year) && $year == $y) ? 'selected' : '' ?>>
                                    <?= $y ?>
                                </option>
                            <?php endfor; ?>
                        </select>
                    </div>
                    <div class="col-md-4 mb-3">
                        <button type="submit" class="btn btn-primary btn-neumorphic-sm w-100">Terapkan Filter</button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Button to show QR code/link for Survey Form -->
    <div class="d-flex justify-content-end mb-3">
        <button type="button" class="btn btn-info btn-neumorphic-sm" data-bs-toggle="modal" data-bs-target="#qrSurveyModal">
            <i class="bi bi-qr-code-scan me-2"></i> QR Code Kuesioner
        </button>
    </div>

    <!-- Modal for Survey QR Code -->
    <div class="modal fade" id="qrSurveyModal" tabindex="-1" aria-labelledby="qrSurveyModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content card-neumorphic">
                <div class="modal-header border-0 pb-0">
                    <h5 class="modal-title fw-bold" id="qrSurveyModalLabel">QR Code Kuesioner</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body text-center">
                    <p>Scan QR Code di bawah atau gunakan link berikut:</p>
                    <a href="<?php echo BASE_URL . '?page=survey_form'; ?>" target="_blank" id="surveyQrLink">
                        <?php echo BASE_URL . '?page=survey_form'; ?>
                    </a>
                    <div class="my-3">
                        <!-- QR Code Image will be loaded here dynamically or from API -->
                        <img src="https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=<?php echo BASE_URL . '?page=survey_form'; ?>" alt="QR Code Survey" class="img-fluid">
                    </div>
                    <button class="btn btn-outline-secondary btn-sm" onclick="copyToClipboard('surveyQrLink')"><i class="bi bi-copy me-2"></i> Salin Link</button>
                </div>
                <div class="modal-footer border-0 pt-0">
                    <button type="button" class="btn btn-secondary btn-neumorphic-sm" data-bs-dismiss="modal">Tutup</button>
                </div>
            </div>
        </div>
    </div>
    <!-- End Modal -->

    <div class="card card-neumorphic mb-4">
        <div class="card-header bg-transparent border-0 py-3 d-flex justify-content-between align-items-center">
            <h6 class="m-0 fw-bold text-dark">Ringkasan Rating</h6>
        </div>
        <div class="card-body">
            <?php if (!empty($questions)): ?>
                <?php foreach ($questions as $question): ?>
                    <?php if ($question['question_type'] === 'rating_5'): ?>
                        <div class="mb-3">
                            <h6 class="text-primary"><?php echo htmlspecialchars($question['question_text']); ?></h6>
                            <p class="mb-1">Rata-rata Rating: <span class="fw-bold fs-5"><?php echo number_format($average_ratings[$question['id']] ?? 0, 2); ?></span> / 5</p>
                            <div class="progress" style="height: 10px;">
                                <div class="progress-bar bg-primary" role="progressbar" style="width: <?php echo (($average_ratings[$question['id']] ?? 0) / 5) * 100; ?>%;" aria-valuenow="<?php echo ($average_ratings[$question['id']] ?? 0); ?>" aria-valuemin="0" aria-valuemax="5"></div>
                            </div>
                        </div>
                    <?php endif; ?>
                <?php endforeach; ?>

                <?php if (isset($overall_avg_rating)): ?>
                    <hr class="my-4">
                    <p class="fs-5 fw-bold text-dark">Rata-rata Kepuasan Keseluruhan: <span class="text-success"><?php echo number_format($overall_avg_rating, 2); ?></span> / 5</p>
                <?php endif; ?>

            <?php else: ?>
                <div class="alert alert-warning">Tidak ada pertanyaan survei rating yang tersedia.</div>
            <?php endif; ?>
        </div>
    </div>

    <div class="card card-neumorphic mb-4">
        <div class="card-header bg-transparent border-0 py-3">
            <h6 class="m-0 fw-bold text-dark">Respon Individual</h6>
        </div>
        <div class="card-body">
                            <?php if (!empty($grouped_responses)): ?>
                            <div class="table-responsive">
                                <table class="table table-hover" width="100%" cellspacing="0">
                                    <thead>
                                        <tr>
                                            <th>Nama</th>
                                            <th>Unit</th>
                                            <th>Email</th>
                                            <th>Waktu Submit</th>
                                            <th>Aksi</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($grouped_responses as $respondent_key => $data): ?>
                                            <tr>
                                                <td><?php echo htmlspecialchars($data['nama']); ?></td>
                                                <td><?php echo htmlspecialchars($data['unit']); ?></td>
                                                <td><?php echo htmlspecialchars($data['email']); ?></td>
                                                <td><?php echo htmlspecialchars(date('d-m-Y H:i', strtotime($data['created_at']))); ?></td>
                                                <td>
                                                    <button type="button" class="btn btn-sm btn-primary btn-neumorphic-sm" data-bs-toggle="modal" data-bs-target="#responseDetailModal" 
                                                        data-respondent-key="<?php echo htmlspecialchars($respondent_key); ?>"
                                                        onclick="showSurveyResponseDetails('<?php echo htmlspecialchars(json_encode($data['responses'])); ?>', '<?php echo htmlspecialchars($data['nama']); ?>')">
                                                        Detail
                                                    </button>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                            <!-- Pagination -->
                            <nav aria-label="Page navigation">
                                <ul class="pagination justify-content-center mt-4">
                                    <?php if ($page > 1): ?>
                                        <li class="page-item">
                                            <a class="page-link" href="?page=survey_results&month=<?= $month ?? '' ?>&year=<?= $year ?? '' ?>&p=<?= $page - 1 ?>" aria-label="Previous">
                                                <span aria-hidden="true">&laquo;</span>
                                            </a>
                                        </li>
                                    <?php endif; ?>
            
                                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                                        <li class="page-item <?= ($i == $page) ? 'active' : '' ?>">
                                            <a class="page-link" href="?page=survey_results&month=<?= $month ?? '' ?>&year=<?= $year ?? '' ?>&p=<?= $i ?>"><?= $i ?></a>
                                        </li>
                                    <?php endfor; ?>
            
                                    <?php if ($page < $total_pages): ?>
                                        <li class="page-item">
                                            <a class="page-link" href="?page=survey_results&month=<?= $month ?? '' ?>&year=<?= $year ?? '' ?>&p=<?= $page + 1 ?>" aria-label="Next">
                                                <span aria-hidden="true">&raquo;</span>
                                            </a>
                                        </li>
                                    <?php endif; ?>
                                </ul>
                            </nav>
                            <?php else: ?>
                                <div class="alert alert-info">Belum ada respon survei.</div>
                            <?php endif; ?>        </div>
    </div>

    <!-- Modal for Survey Response Details -->
    <div class="modal fade" id="responseDetailModal" tabindex="-1" aria-labelledby="responseDetailModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg">
            <div class="modal-content card-neumorphic">
                <div class="modal-header border-0 pb-0">
                    <h5 class="modal-title fw-bold" id="responseDetailModalLabel">Detail Respon Survei</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="responseDetailsContent">
                    <!-- Details will be loaded here by JavaScript -->
                </div>
                <div class="modal-footer border-0 pt-0">
                    <button type="button" class="btn btn-outline-secondary btn-neumorphic-sm" data-bs-dismiss="modal">Tutup</button>
                </div>
            </div>
        </div>
    </div>
    <!-- End Modal -->

<script>
    function showSurveyResponseDetails(responsesJson, respondentName) {
        const responses = JSON.parse(responsesJson);
        const modalTitle = document.getElementById('responseDetailModalLabel');
        const modalBody = document.getElementById('responseDetailsContent');
        
        modalTitle.innerText = 'Detail Respon dari ' + respondentName;
        modalBody.innerHTML = ''; // Clear previous content

        let html = '<ul class="list-group list-group-flush">';
        responses.forEach(response => {
            html += `<li class="list-group-item bg-transparent d-flex justify-content-between align-items-center border-0 py-2">
                        <span class="fw-bold">${response.question_text}</span>
                        <span>`;
            // Display rating as stars or text
            if (response.question_type === 'rating_5') {
                for (let i = 1; i <= 5; i++) {
                    html += `<i class="bi ${i <= response.response_value ? 'bi-star-fill text-warning' : 'bi-star text-muted'}"></i>`;
                }
                html += ` (${response.response_value})`;
            } else {
                html += `${response.response_value.replace(/\n/g, '<br>')}`; // Handle newlines for text responses
            }
            html += `   </span>
                    </li>`;
        });
        html += '</ul>';
        modalBody.innerHTML = html;
    }
</script>
</div>
