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

$tahun = $_GET['tahun'] ?? date('Y');

header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=Rekap_Triwulan_$tahun.xls");

$qPerusahaan = mysqli_query($conn,"
SELECT
    nomor_sk,
    nama_perusahaan
FROM master_sk
ORDER BY nama_perusahaan ASC
");

$qData = mysqli_query($conn,"
SELECT
    nomor_sk,
    laporan_triwulan_ke
FROM rekomtek
WHERE tahun_laporan='$tahun'
AND status='Diterima'
");

$dataTriwulan = [];

while($r = mysqli_fetch_assoc($qData)){
    $dataTriwulan[$r['nomor_sk']]
                  [$r['laporan_triwulan_ke']] = true;
}
?>

<table border="1">

<tr style="background:#d9d9d9;">
    <th>No</th>
    <th>Nomor SK</th>
    <th>Nama Perusahaan</th>
    <th>TW I</th>
    <th>TW II</th>
    <th>TW III</th>
    <th>TW IV</th>
    <th>Progress</th>
</tr>

<?php

$no = 1;

while($d = mysqli_fetch_assoc($qPerusahaan)){

    $sk = $d['nomor_sk'];

    $jml = 0;

    if(isset($dataTriwulan[$sk]['Triwulan I'])) $jml++;
    if(isset($dataTriwulan[$sk]['Triwulan II'])) $jml++;
    if(isset($dataTriwulan[$sk]['Triwulan III'])) $jml++;
    if(isset($dataTriwulan[$sk]['Triwulan IV'])) $jml++;

    $progress = ($jml/4)*100;
?>

<tr>
    <td><?= $no++ ?></td>
    <td><?= $d['nomor_sk'] ?></td>
    <td><?= $d['nama_perusahaan'] ?></td>

   <td><?= isset($dataTriwulan[$sk]['Triwulan I']) ? 'V' : '-' ?></td>
<td><?= isset($dataTriwulan[$sk]['Triwulan II']) ? 'V' : '-' ?></td>
<td><?= isset($dataTriwulan[$sk]['Triwulan III']) ? 'V' : '-' ?></td>
<td><?= isset($dataTriwulan[$sk]['Triwulan IV']) ? 'V' : '-' ?></td>

    <td><?= $progress ?>%</td>
</tr>

<?php } ?>

</table>