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

require_once '../../../library/sw-config.php';
require_once '../../../library/sw-function.php';
include_once '../../../library/vendor/autoload.php';

if (empty($_SESSION['SESSION_USER']) && empty($_SESSION['SESSION_ID'])) {
    die("Sesi login tidak ditemukan, silakan login ulang.");
}

// =================== HELPER ===================
function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

if (!function_exists('bulan_indo')) {
  function bulan_indo($bln){
    $bulan = [
      '01'=>'Januari','02'=>'Februari','03'=>'Maret','04'=>'April',
      '05'=>'Mei','06'=>'Juni','07'=>'Juli','08'=>'Agustus',
      '09'=>'September','10'=>'Oktober','11'=>'November','12'=>'Desember'
    ];
    return isset($bulan[$bln]) ? $bulan[$bln] : $bln;
  }
}

function bulan_tahun($bulan,$tahun){
    return bulan_indo(str_pad($bulan,2,'0',STR_PAD_LEFT))." ".$tahun;
}

function header_instansi($judul){
    echo '
    <div style="text-align:center; border-bottom:3px solid #000; padding-bottom:10px; margin-bottom:20px;">
      <table width="100%">
        <tr>
          <td width="80" align="center">
            <img src="../../../assets/logo.png" width="70">
          </td>
          <td align="center">
            <h3 style="margin:0;">INSTANSI ANDA</h3>
            <p style="margin:0;">Alamat lengkap instansi<br>
            Telp: (021) XXXXXXXX | Email: info@instansi.go.id</p>
          </td>
        </tr>
      </table>
    </div>
    <h2 style="text-align:center">'.$judul.'</h2>';
}

function footer_ttd(){
    echo '
    <br><br><br>
    <table width="100%">
      <tr>
        <td width="70%"></td>
        <td align="center">
          <p>Mengetahui,</p>
          <p><b>Pimpinan</b></p>
          <br><br><br>
          <p>(_________________)</p>
        </td>
      </tr>
    </table>';
}

function base_css(){
    return '
    <style>
      body { font-family: sans-serif; font-size: 12px; }
      table { border-collapse: collapse; width:100%; }
      table th, table td { border:1px solid #000; padding:6px; }
      table thead th { text-align:center; background:#f2f2f2; }
    </style>';
}

// =================== AMBIL ACTION ===================
$action = isset($_GET['action']) ? $_GET['action'] : '';

switch ($action) {

/* ======== LAPORAN SUPERVISI PER PERIODE (PDF) ======== */
case 'pdf':
    $bulan = isset($_GET['from']) ? $_GET['from'] : date("m");
    $tahun = isset($_GET['to']) ? $_GET['to'] : date("Y");

    $query = "SELECT * FROM supervisi WHERE MONTH(tanggal)='".(int)$bulan."' AND YEAR(tanggal)='".(int)$tahun."' ORDER BY tanggal DESC";
    $result = $connection->query($query);
    if(!$result){ die("Query Error: ".$connection->error); }

    if (!class_exists('\Mpdf\Mpdf')) {
        echo base_css();
        header_instansi("LAPORAN SUPERVISI");
        echo "<p>Periode: ".bulan_tahun($bulan,$tahun)."</p>";
        echo "<table><thead><tr>
                <th>No</th><th>Tanggal</th><th>Pimpinan</th><th>Karyawan</th>
                <th>Jabatan</th><th>Substansi</th><th>Lokasi</th>
                <th>Waktu</th><th>Status</th>
              </tr></thead><tbody>";
        $no=1;
        while($row=$result->fetch_assoc()){
            echo "<tr>
              <td>".$no++."</td>
              <td>".tgl_indo($row['tanggal'])."</td>
              <td>".h($row['pimpinan'])."</td>
              <td>".h($row['karyawan'])."</td>
              <td>".h($row['jabatan'])."</td>
              <td>".h($row['substansi'])."</td>
              <td>".h($row['lokasi'])."</td>
              <td>".h($row['waktu_mulai'])." - ".h($row['waktu_akhir'])."</td>
              <td>".h($row['status'])."</td>
            </tr>";
        }
        echo "</tbody></table>";
        exit;
    }

    $mpdf = new \Mpdf\Mpdf(['mode' => 'utf-8','format' => 'A4-L']);
    ob_start();

    echo base_css();
    header_instansi("LAPORAN SUPERVISI");
    echo '<p>Periode: '.bulan_tahun($bulan,$tahun).'</p>';

    echo '<table>
            <thead>
              <tr>
                <th>No</th><th>Tanggal</th><th>Pimpinan</th><th>Karyawan</th>
                <th>Jabatan</th><th>Substansi</th><th>Lokasi</th>
                <th>Waktu</th><th>Status</th>
              </tr>
            </thead><tbody>';
    $no=1;
    while($row=$result->fetch_assoc()){
        echo '<tr>
          <td>'.$no++.'</td>
          <td>'.tgl_indo($row['tanggal']).'</td>
          <td>'.h($row['pimpinan']).'</td>
          <td>'.h($row['karyawan']).'</td>
          <td>'.h($row['jabatan']).'</td>
          <td>'.h($row['substansi']).'</td>
          <td>'.h($row['lokasi']).'</td>
          <td>'.h($row['waktu_mulai']).' - '.h($row['waktu_akhir']).'</td>
          <td>'.h($row['status']).'</td>
        </tr>';
    }
    echo '</tbody></table>';
    footer_ttd();

    $html = ob_get_clean();
    $mpdf->WriteHTML($html);
    $mpdf->Output("Laporan-Supervisi-$bulan-$tahun.pdf",'I');
    break;

/* ======== LAPORAN SUPERVISI PER ORANG (PDF) ======== */
case 'detailpdf':
    $id    = isset($_GET['id']) ? mysqli_real_escape_string($connection, epm_decode($_GET['id'])) : 0;
    $bulan = isset($_GET['from']) ? $_GET['from'] : date("m");
    $tahun = isset($_GET['to']) ? $_GET['to'] : date("Y");

    $q_user = $connection->query("SELECT karyawan, jabatan FROM supervisi WHERE id='$id' LIMIT 1");
    if(!$q_user || $q_user->num_rows==0){ die("Data karyawan tidak ditemukan"); }
    $user   = $q_user->fetch_assoc();

    $query  = "SELECT * FROM supervisi WHERE karyawan='".$user['karyawan']."' AND MONTH(tanggal)='".(int)$bulan."' AND YEAR(tanggal)='".(int)$tahun."' ORDER BY tanggal ASC";
    $result = $connection->query($query);
    if(!$result){ die("Query Error: ".$connection->error); }

    if (!class_exists('\Mpdf\Mpdf')) {
        echo base_css();
        header_instansi("LAPORAN SUPERVISI PER ORANG");
        echo "<p>Nama: ".$user['karyawan']."<br>Jabatan: ".$user['jabatan']."<br>Periode: ".bulan_tahun($bulan,$tahun)."</p>";
        echo "<table><thead><tr>
                <th>No</th><th>Tanggal</th><th>Jam Masuk</th><th>Jam Pulang</th><th>Lokasi</th><th>Status</th>
              </tr></thead><tbody>";
        $no=1;
        while($row=$result->fetch_assoc()){
            echo "<tr>
              <td>".$no++."</td>
              <td>".tgl_indo($row['tanggal'])."</td>
              <td>".h($row['waktu_mulai'])."</td>
              <td>".h($row['waktu_akhir'])."</td>
              <td>".h($row['lokasi'])."</td>
              <td>".h($row['status'])."</td>
            </tr>";
        }
        echo "</tbody></table>";
        exit;
    }

    $mpdf = new \Mpdf\Mpdf(['mode'=>'utf-8','format'=>'A4-P']);
    ob_start();
    echo base_css();
    header_instansi("LAPORAN SUPERVISI PER ORANG");

    echo '<p>Nama: '.$user['karyawan'].'<br>Jabatan: '.$user['jabatan'].'<br>Periode: '.bulan_tahun($bulan,$tahun).'</p>';

    echo '<table border="1" cellpadding="5" cellspacing="0" width="100%">
            <thead>
              <tr>
                <th>No</th><th>Tanggal</th><th>Jam Masuk</th><th>Jam Pulang</th><th>Lokasi</th><th>Status</th>
              </tr>
            </thead><tbody>';
    $no=1;
    while($row=$result->fetch_assoc()){
        echo '<tr>
          <td>'.$no++.'</td>
          <td>'.tgl_indo($row['tanggal']).'</td>
          <td>'.h($row['waktu_mulai']).'</td>
          <td>'.h($row['waktu_akhir']).'</td>
          <td>'.h($row['lokasi']).'</td>
          <td>'.h($row['status']).'</td>
        </tr>';
    }
    echo '</tbody></table>';
    footer_ttd();

    $html = ob_get_clean();
    $mpdf->WriteHTML($html);
    $mpdf->Output("Laporan-Supervisi-".$user['karyawan']."-$bulan-$tahun.pdf",'I');
    break;

default:
    echo "Parameter action tidak valid.";
    break;

}
?>
