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

require "../config.php";

/* ================= HEADER EXCEL ================= */
header("Content-type: application/vnd-ms-excel");
header("Content-Disposition: attachment; filename=Data_Survei.xls");

/* ================= 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'])){
        $where .= " AND DATE(created_at) = '".$_GET['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())";
    }
}

/* ================= AMBIL DATA ================= */
$data = $conn->query("SELECT * FROM survei_kepuasan $where ORDER BY id DESC");
?>

<table border="1">
<tr style="background:#000;color:#fff;text-align:center;">
<th>No</th>
<th>Nama</th>
<th>Email</th>
<th>Jenis Kelamin</th>
<th>NIK</th>
<th>Pekerjaan</th>
<th>Instansi</th>
<th>Pendidikan</th>
<th>No HP</th>
<th>Kota</th>
<th>Alamat</th>

<th>P1</th>
<th>P2</th>
<th>P3</th>
<th>P4</th>
<th>P5</th>
<th>P6</th>
<th>P7</th>
<th>P8</th>
<th>P9</th>
<th>P10</th>

<th>Rata-rata</th>
<th>Saran</th>
<th>Tanggal</th>
</tr>

<?php 
$no=1;

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

/* ================= HITUNG NILAI ================= */
$total = 0;
$count = 0;

for($i=1;$i<=10;$i++){
    if($d["p$i"]){
        $total += $d["p$i"];
        $count++;
    }
}

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

<tr>
<td><?= $no++ ?></td>
<td><?= $d['nama'] ?></td>
<td><?= $d['email'] ?></td>
<td><?= $d['jenis_kelamin'] ?></td>
<td><?= $d['nik'] ?></td>
<td><?= $d['pekerjaan'] ?></td>
<td><?= $d['instansi'] ?></td>
<td><?= $d['pendidikan'] ?></td>
<td><?= $d['no_hp'] ?></td>
<td><?= $d['kota'] ?></td>
<td><?= $d['alamat'] ?></td>

<td><?= $d['p1'] ?></td>
<td><?= $d['p2'] ?></td>
<td><?= $d['p3'] ?></td>
<td><?= $d['p4'] ?></td>
<td><?= $d['p5'] ?></td>
<td><?= $d['p6'] ?></td>
<td><?= $d['p7'] ?></td>
<td><?= $d['p8'] ?></td>
<td><?= $d['p9'] ?></td>
<td><?= $d['p10'] ?></td>

<td><?= $rata ?></td>
<td><?= $d['saran'] ?></td>
<td><?= $d['created_at'] ?></td>
</tr>

<?php } ?>

</table>