<?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'); }

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>';
}

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

switch ($action) {

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

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

    $judul = "LAPORAN PERMINTAAN";
    $periode = bulan_tahun($bulan,$tahun);

    if (!class_exists('\Mpdf\Mpdf')) {
        echo base_css();
        header_instansi($judul);
        echo "<p>Periode: $periode</p>";
        echo "<table><thead><tr>
                <th>No</th><th>Tanggal Permintaan</th><th>Nama Pengaju</th><th>Divisi Pengaju</th>
                <th>Divisi Tujuan</th><th>Penanggung Jawab</th>
                <th>Tanggal Dibutuhkan</th><th>Detail Permintaan</th><th>Status</th>
              </tr></thead><tbody>";
        $no=1;
        while($row=$result->fetch_assoc()){
            echo "<tr>
              <td>".$no++."</td>
              <td>".tgl_indo($row['tanggal_permintaan'])."</td>
              <td>".h($row['nama_pengaju'])."</td>
              <td>".h($row['divisi_pengaju'])."</td>
              <td>".h($row['divisi_tujuan'])."</td>
              <td>".h($row['penanggung_jawab'])."</td>
              <td>".tgl_indo($row['tanggal_dibutuhkan'])."</td>
              <td>".h($row['detail_permintaan'])."</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($judul);
    echo "<p>Periode: $periode</p>";

    echo "<table>
      <thead>
        <tr>
          <th>No</th><th>Tanggal Permintaan</th><th>Nama Pengaju</th><th>Divisi Pengaju</th>
          <th>Divisi Tujuan</th><th>Penanggung Jawab</th>
          <th>Tanggal Dibutuhkan</th><th>Detail Permintaan</th><th>Status</th>
        </tr>
      </thead><tbody>";
    $no=1;
    while($row=$result->fetch_assoc()){
        echo "<tr>
          <td>".$no++."</td>
          <td>".tgl_indo($row['tanggal_permintaan'])."</td>
          <td>".h($row['nama_pengaju'])."</td>
          <td>".h($row['divisi_pengaju'])."</td>
          <td>".h($row['divisi_tujuan'])."</td>
          <td>".h($row['penanggung_jawab'])."</td>
          <td>".tgl_indo($row['tanggal_dibutuhkan'])."</td>
          <td>".h($row['detail_permintaan'])."</td>
          <td>".h($row['status'])."</td>
        </tr>";
    }
    echo "</tbody></table>";
    footer_ttd();

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


/* ======== LAPORAN PERMINTAAN PER PENANGGUNG JAWAB ======== */
case 'detailpdf':
    $nama = isset($_GET['nama']) ? $connection->real_escape_string($_GET['nama']) : '';
    $bulan = isset($_GET['from']) ? $_GET['from'] : date("m");
    $tahun = isset($_GET['to']) ? $_GET['to'] : date("Y");

    if($nama == '') die("Nama penanggung jawab tidak diberikan.");

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

    $judul = "LAPORAN PERMINTAAN - ".$nama;
    $periode = bulan_tahun($bulan,$tahun);

    if (!class_exists('\Mpdf\Mpdf')) {
        echo base_css();
        header_instansi($judul);
        echo "<p>Penanggung Jawab: ".$nama."<br>Periode: ".$periode."</p>";
        echo "<table><thead><tr>
                <th>No</th><th>Nama Pengaju</th><th>Divisi Pengaju</th>
                <th>Tgl Permintaan</th><th>Tgl Dibutuhkan</th>
                <th>Detail</th><th>Status</th>
              </tr></thead><tbody>";
        $no=1;
        while($r=$result->fetch_assoc()){
            echo "<tr>
              <td>".$no++."</td>
              <td>".h($r['nama_pengaju'])."</td>
              <td>".h($r['divisi_pengaju'])."</td>
              <td>".tgl_indo($r['tanggal_permintaan'])."</td>
              <td>".tgl_indo($r['tanggal_dibutuhkan'])."</td>
              <td>".h($r['detail_permintaan'])."</td>
              <td>".h($r['status'])."</td>
            </tr>";
        }
        echo "</tbody></table>";
        exit;
    }

    $mpdf = new \Mpdf\Mpdf(['mode'=>'utf-8','format'=>'A4-P']);
    ob_start();
    echo base_css();
    header_instansi($judul);
    echo "<p>Penanggung Jawab: ".$nama."<br>Periode: ".$periode."</p>";

    echo "<table>
      <thead>
        <tr>
          <th>No</th><th>Nama Pengaju</th><th>Divisi Pengaju</th>
          <th>Tgl Permintaan</th><th>Tgl Dibutuhkan</th>
          <th>Detail</th><th>Status</th>
        </tr>
      </thead><tbody>";
    $no=1;
    while($r=$result->fetch_assoc()){
        echo "<tr>
          <td>".$no++."</td>
          <td>".h($r['nama_pengaju'])."</td>
          <td>".h($r['divisi_pengaju'])."</td>
          <td>".tgl_indo($r['tanggal_permintaan'])."</td>
          <td>".tgl_indo($r['tanggal_dibutuhkan'])."</td>
          <td>".h($r['detail_permintaan'])."</td>
          <td>".h($r['status'])."</td>
        </tr>";
    }
    echo "</tbody></table>";
    footer_ttd();

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

default:
    echo "Parameter action tidak valid.";
    break;
}
?>
