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

session_start();
require "../config.php";

/* ================= FILTER ================= */
$where = "WHERE 1=1";

/* SEARCH */
if(isset($_GET['search']) && $_GET['search'] != ""){
    $s = $conn->real_escape_string($_GET['search']);
    $where .= " AND nama LIKE '%$s%'";
}

/* FILTER TANGGAL */
if(isset($_GET['filter']) && $_GET['filter'] != ""){

    $filter = $_GET['filter'];

    if($filter == "hari" && !empty($_GET['tanggal'])){
        $tanggal = $_GET['tanggal'];
        $where .= " AND DATE(created_at) = '$tanggal'";
    }
    elseif($filter == "bulan"){
        $where .= " AND MONTH(created_at)=MONTH(CURDATE()) 
                    AND YEAR(created_at)=YEAR(CURDATE())";
    }
    elseif($filter == "tahun"){
        $where .= " AND YEAR(created_at)=YEAR(CURDATE())";
    }
}

/* ================= PAGINATION ================= */

$limit = 10;

$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;

if($page < 1){
    $page = 1;
}

$offset = ($page - 1) * $limit;

/* TOTAL DATA */
$totalData = $conn->query("
SELECT COUNT(*) as total 
FROM survei_kepuasan
$where
")->fetch_assoc()['total'];

$totalPage = ceil($totalData / $limit);

/* DATA */
$data = $conn->query("
SELECT * FROM survei_kepuasan
$where 
ORDER BY id DESC 
LIMIT $limit OFFSET $offset
");

/* ================= DATA RATA-RATA ================= */
$labelsChart = [];
$dataChart = [];

for($i=1; $i<=10; $i++){

    $labelsChart[] = "P".$i;

    $q = $conn->query("
        SELECT AVG(p$i) as rata
        FROM survei_kepuasan
        $where
    ");

    $r = $q->fetch_assoc();

    $dataChart[] = round($r['rata'], 2);
}

/* ================= DATA PIE PER PERTANYAAN ================= */

$chartData = [];

for($i=1; $i<=10; $i++){

    $chartData[$i] = [
        "Sangat Baik" => 0,
        "Baik" => 0,
        "Cukup" => 0,
        "Kurang" => 0
    ];

    $q = $conn->query("
        SELECT p$i 
        FROM survei_kepuasan 
        $where
    ");

    while($r = $q->fetch_assoc()){

        $nilai = (int)$r["p$i"];

        if($nilai == 4){
            $chartData[$i]["Sangat Baik"]++;
        }
        elseif($nilai == 3){
            $chartData[$i]["Baik"]++;
        }
        elseif($nilai == 2){
            $chartData[$i]["Cukup"]++;
        }
        elseif($nilai == 1){
            $chartData[$i]["Kurang"]++;
        }
    }
}
?>

<?php include 'layout.php'; ?>

<h3 class="mb-3">📊 Data Survei Kepuasan</h3>

<!-- ================= GRAFIK + DETAIL ================= -->

<div class="card shadow mb-4">
<div class="card-body">

<div class="row align-items-center">

<!-- GRAFIK -->
<div class="col-md-4 text-center">

<h5 class="mb-3">
Grafik Keseluruhan
</h5>

<div style="max-width:250px; margin:auto;">
<canvas id="chartUtama"></canvas>
</div>

<div class="mt-4">

<?php for($i=1; $i<=10; $i++){ ?>

<button
class="btn btn-outline-primary btn-sm m-1"
data-bs-toggle="modal"
data-bs-target="#modalP<?= $i ?>">

P<?= $i ?>

</button>

<?php } ?>

</div>

</div>

<!-- TABEL -->
<div class="col-md-8">

<h5 class="mb-3">
Rata-rata Nilai Kuisioner
</h5>

<table class="table table-bordered table-striped">

<tr class="table-dark text-center">
<th>Pertanyaan</th>
<th>Rata-rata</th>
<th>Persentase</th>
</tr>

<?php foreach($labelsChart as $i => $label){ ?>

<tr>

<td><?= $label ?></td>

<td class="text-center">
<?= $dataChart[$i] ?>
</td>

<td class="text-center">
<?= round(($dataChart[$i] / 4) * 100,2) ?>%
</td>

</tr>

<?php } ?>

</table>

</div>

</div>

</div>
</div>
<!-- ================= MODAL PER PERTANYAAN ================= -->

<?php for($i=1; $i<=10; $i++){ ?>

<div class="modal fade"
id="modalP<?= $i ?>"
tabindex="-1">

<div class="modal-dialog modal-sm">
<div class="modal-content">

<div class="modal-header">

<h5 class="modal-title">
Grafik Kuisioner P<?= $i ?>
</h5>

<button
type="button"
class="btn-close"
data-bs-dismiss="modal">
</button>

</div>

<div class="modal-body text-center">

<div style="max-width:220px; margin:auto;">
<canvas id="chartP<?= $i ?>"></canvas>
</div>

<button
class="btn btn-success mt-3"
onclick="downloadChart('chartP<?= $i ?>', 'Kuisioner_P<?= $i ?>')">

Download Grafik
</button>

</div>

</div>
</div>

</div>


<?php } ?>



<!-- ================= DETAIL ================= -->
<div class="card shadow mb-4">
<div class="card-body">


<!-- ================= FILTER ================= -->
<form method="GET" class="row mb-3">

<div class="col-md-3 mb-2">
<input type="text" 
name="search" 
class="form-control"
placeholder="Cari Nama..."
value="<?= $_GET['search'] ?? '' ?>">
</div>

<div class="col-md-2 mb-2">
<select name="filter" class="form-control">

<option value="">Semua</option>

<option value="hari"
<?= (@$_GET['filter']=="hari") ? "selected" : "" ?>>
Harian
</option>

<option value="bulan"
<?= (@$_GET['filter']=="bulan") ? "selected" : "" ?>>
Bulanan
</option>

<option value="tahun"
<?= (@$_GET['filter']=="tahun") ? "selected" : "" ?>>
Tahunan
</option>

</select>
</div>

<div class="col-md-2 mb-2">
<input type="date"
name="tanggal"
class="form-control"
value="<?= $_GET['tanggal'] ?? '' ?>">
</div>

<div class="col-md-2 mb-2">
<button class="btn btn-primary w-100">
Cari
</button>
</div>

<div class="col-md-3 mb-2">
<a href="export_survei.php?<?= http_build_query($_GET) ?>"
class="btn btn-success w-100">
Export Excel
</a>
</div>

</form>

<!-- ================= TABLE ================= -->
<div class="table-responsive">

<table class="table table-bordered table-hover survei-table align-middle">

<thead class="table-dark">

<tr>

<th width="5%">No</th>
<th width="18%">Nama</th>
<th width="22%">Email</th>
<th width="12%">Pekerjaan</th>
<th width="8%">Nilai</th>
<th width="20%">Tanggal</th>
<th width="10%">Aksi</th>

</tr>

</thead>

<tbody>

<?php
$no = 1;

while($d = $data->fetch_assoc()){

    $total = 0;
    $count = 0;

    for($i=1; $i<=10; $i++){

        if($d["p$i"]){

            $total += $d["p$i"];
            $count++;
        }
    }

    $nilai = $count ? round($total/$count,2) : 0;
?>

<tr>

<td class="text-center">
<?= $no++ ?>
</td>

<td>
<?= $d['nama'] ?>
</td>

<td class="email-col">
<?= $d['email'] ?>
</td>

<td class="text-center">
<?= $d['pekerjaan'] ?>
</td>

<td class="text-center">

<span class="badge bg-success nilai-badge">
<?= $nilai ?>
</span>

</td>

<td class="text-center tanggal-col">
<?= date('d-m-Y H:i', strtotime($d['created_at'])) ?>
</td>

<td class="text-center">

<a href="detail_survei?id=<?= $d['id'] ?>"
class="btn btn-primary btn-sm btn-lihat">

Lihat

</a>

</td>

</tr>

<?php } ?>

</tbody>

</table>
<?php if($totalPage > 1){ ?>

<nav class="mt-3">
<ul class="pagination justify-content-center">

<?php if($page > 1){ ?>
<li class="page-item">
<a class="page-link" href="?page=<?= $page-1 ?>">
Previous
</a>
</li>
<?php } ?>

<?php for($i=1; $i <= $totalPage; $i++){ ?>

<li class="page-item <?= ($i == $page) ? 'active' : '' ?>">
<a class="page-link" href="?page=<?= $i ?>">
<?= $i ?>
</a>
</li>

<?php } ?>

<?php if($page < $totalPage){ ?>
<li class="page-item">
<a class="page-link" href="?page=<?= $page+1 ?>">
Next
</a>
</li>
<?php } ?>

</ul>
</nav>

<?php } ?>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>

<script>

const chartData = <?= json_encode($chartData) ?>;

/* ================= GRAFIK UTAMA ================= */

const totalKeseluruhan = {
    "Sangat Baik": 0,
    "Baik": 0,
    "Cukup": 0,
    "Kurang": 0
};

for(let i=1; i<=10; i++){

    totalKeseluruhan["Sangat Baik"] += chartData[i]["Sangat Baik"];
    totalKeseluruhan["Baik"] += chartData[i]["Baik"];
    totalKeseluruhan["Cukup"] += chartData[i]["Cukup"];
    totalKeseluruhan["Kurang"] += chartData[i]["Kurang"];
}

new Chart(document.getElementById('chartUtama'), {

    type: 'pie',

    data: {

        labels: [
            'Sangat Baik',
            'Baik',
            'Cukup',
            'Kurang'
        ],

        datasets: [{

            data: [
                totalKeseluruhan["Sangat Baik"],
                totalKeseluruhan["Baik"],
                totalKeseluruhan["Cukup"],
                totalKeseluruhan["Kurang"]
            ],

            backgroundColor: [
                '#198754',
                '#0d6efd',
                '#ffc107',
                '#dc3545'
            ]
        }]
    },

    options: {

        responsive: true,

        plugins: {

            legend: {
                position: 'bottom'
            },

            datalabels: {

                color: '#fff',

                font: {
                    weight: 'bold'
                },

                formatter: (value, context) => {

                    let total = context.dataset.data.reduce(
                        (a, b) => a + b,
                        0
                    );

                    let persen = total
                        ? ((value / total) * 100).toFixed(1)
                        : 0;

                    return persen + '%';
                }
            }
        }
    },

    plugins: [ChartDataLabels]
});

/* ================= GRAFIK PER PERTANYAAN ================= */

for(let i=1; i<=10; i++){

    new Chart(document.getElementById('chartP'+i), {

        type: 'pie',

        data: {

            labels: [
                'Sangat Baik',
                'Baik',
                'Cukup',
                'Kurang'
            ],

            datasets: [{

                data: [
                    chartData[i]["Sangat Baik"],
                    chartData[i]["Baik"],
                    chartData[i]["Cukup"],
                    chartData[i]["Kurang"]
                ],

                backgroundColor: [
                    '#198754',
                    '#0d6efd',
                    '#ffc107',
                    '#dc3545'
                ]
            }]
        },

        options: {

            responsive: true,

            plugins: {

                legend: {
                    position: 'bottom'
                },

                datalabels: {

                    color: '#fff',

                    font: {
                        weight: 'bold'
                    },

                    formatter: (value, context) => {

                        let total = context.dataset.data.reduce(
                            (a, b) => a + b,
                            0
                        );

                        let persen = total
                            ? ((value / total) * 100).toFixed(1)
                            : 0;

                        return persen + '%';
                    }
                }
            }
        },

        plugins: [ChartDataLabels]
    });
}

/* ================= DOWNLOAD CHART ================= */
/* ================= DOWNLOAD CHART ================= */

function downloadChart(canvasId, filename){

    const canvas = document.getElementById(canvasId);

    const link = document.createElement('a');

    link.download = filename + '.png';

    link.href = canvas.toDataURL('image/png');

    link.click();
}

</script>
<style>

/* ================= TABLE ================= */



.survei-table{
    width:100%;
    table-layout:fixed;
    font-size:13px;
}

.survei-table th{
    white-space:nowrap;
    padding:10px 6px;
    text-align:center;
    vertical-align:middle;
}

.survei-table td{
    padding:8px 6px;
    vertical-align:middle;
}

.survei-table tbody tr:hover{
    background:#f8f9fa;
}

.email-col{
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
    font-size:12px;
}

.tanggal-col{
    white-space:nowrap;
    font-size:12px;
}

.nilai-badge{
    font-size:12px;
    padding:5px 8px;
    border-radius:6px;
}

.btn-lihat{
    font-size:12px;
    padding:4px 10px;
    white-space:nowrap;
}


</style>
<?php include 'layout_footer.php'; ?>
