<?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; vertical-align:top; }
    table thead th { text-align:center; background:#f2f2f2; }
  </style>';
}

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

switch ($action) {

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

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

    $judul = "LAPORAN IBADAH BULAN ".strtoupper(bulan_tahun($bulan,$tahun));

    // --- Jika tanpa library mPDF (debug / fallback) ---
    if (!class_exists('\Mpdf\Mpdf')) {
        echo base_css();
        header_instansi($judul);
        echo "<table><thead><tr>
                <th>No</th><th>Tanggal</th><th>Nama</th>
                <th>Shalat Wajib</th><th>Shalat Sunnah</th>
                <th>Kebiasaan Baik</th><th>Dzikir</th><th>Tilawah</th><th>Catatan</th>
              </tr></thead><tbody>";
        $no=1;
        while($row=$result->fetch_assoc()){
            $wajib   = '';
            foreach(json_decode($row['shalat_wajib'],true) ?: [] as $s=>$v){ $wajib .= ucfirst($s).": ".$v."<br>"; }
            $sunnah  = implode(", ", json_decode($row['shalat_sunnah'],true) ?: []);
            $baik    = implode(", ", json_decode($row['kebiasaan_baik'],true) ?: []);
            echo "<tr>
              <td>".$no++."</td>
              <td>".tgl_indo($row['tanggal'])."</td>
              <td>".h($row['nama'])."</td>
              <td>".$wajib."</td>
              <td>".h($sunnah)."</td>
              <td>".h($baik)."</td>
              <td>".h($row['dzikir'])."</td>
              <td>".h($row['tilawah'])."</td>
              <td>".nl2br(h($row['catatan']))."</td>
            </tr>";
        }
        echo "</tbody></table>";
        footer_ttd();
        exit;
    }

    // --- Generate PDF ---
    $mpdf = new \Mpdf\Mpdf(['mode'=>'utf-8','format'=>'A4-L']);
    ob_start();
    echo base_css();
    header_instansi($judul);

    echo "<table>
      <thead>
        <tr>
          <th>No</th><th>Tanggal</th><th>Nama</th>
          <th>Shalat Wajib</th><th>Shalat Sunnah</th>
          <th>Kebiasaan Baik</th><th>Dzikir</th><th>Tilawah</th><th>Catatan</th>
        </tr>
      </thead><tbody>";
    $no=1;
    while($row=$result->fetch_assoc()){
        $wajib   = '';
        foreach(json_decode($row['shalat_wajib'],true) ?: [] as $s=>$v){ $wajib .= ucfirst($s).": ".$v."<br>"; }
        $sunnah  = implode(", ", json_decode($row['shalat_sunnah'],true) ?: []);
        $baik    = implode(", ", json_decode($row['kebiasaan_baik'],true) ?: []);
        echo "<tr>
          <td>".$no++."</td>
          <td>".tgl_indo($row['tanggal'])."</td>
          <td>".h($row['nama'])."</td>
          <td>".$wajib."</td>
          <td>".h($sunnah)."</td>
          <td>".h($baik)."</td>
          <td>".h($row['dzikir'])."</td>
          <td>".h($row['tilawah'])."</td>
          <td>".nl2br(h($row['catatan']))."</td>
        </tr>";
    }
    echo "</tbody></table>";
    footer_ttd();

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


/* ======== LAPORAN IBADAH PER ORANG ======== */
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 tidak diberikan.");

    $query = "SELECT * FROM ibadah 
              WHERE nama='$nama' 
              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); }

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

    // --- Fallback jika mPDF belum ada ---
    if (!class_exists('\Mpdf\Mpdf')) {
        echo base_css();
        header_instansi($judul);
        echo "<p>Nama: ".h($nama)."<br>Periode: ".$periode."</p>";
        echo "<table><thead><tr>
                <th>No</th><th>Tanggal</th>
                <th>Shalat Wajib</th><th>Shalat Sunnah</th>
                <th>Kebiasaan Baik</th><th>Dzikir</th><th>Tilawah</th><th>Catatan</th>
              </tr></thead><tbody>";
        $no=1;
        while($r=$result->fetch_assoc()){
            $wajib   = '';
            foreach(json_decode($r['shalat_wajib'],true) ?: [] as $s=>$v){ $wajib .= ucfirst($s).": ".$v."<br>"; }
            $sunnah  = implode(", ", json_decode($r['shalat_sunnah'],true) ?: []);
            $baik    = implode(", ", json_decode($r['kebiasaan_baik'],true) ?: []);
            echo "<tr>
              <td>".$no++."</td>
              <td>".tgl_indo($r['tanggal'])."</td>
              <td>".$wajib."</td>
              <td>".h($sunnah)."</td>
              <td>".h($baik)."</td>
              <td>".h($r['dzikir'])."</td>
              <td>".h($r['tilawah'])."</td>
              <td>".nl2br(h($r['catatan']))."</td>
            </tr>";
        }
        echo "</tbody></table>";
        footer_ttd();
        exit;
    }

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

    echo "<table>
      <thead>
        <tr>
          <th>No</th><th>Tanggal</th>
          <th>Shalat Wajib</th><th>Shalat Sunnah</th>
          <th>Kebiasaan Baik</th><th>Dzikir</th><th>Tilawah</th><th>Catatan</th>
        </tr>
      </thead><tbody>";
    $no=1;
    while($r=$result->fetch_assoc()){
        $wajib   = '';
        foreach(json_decode($r['shalat_wajib'],true) ?: [] as $s=>$v){ $wajib .= ucfirst($s).": ".$v."<br>"; }
        $sunnah  = implode(", ", json_decode($r['shalat_sunnah'],true) ?: []);
        $baik    = implode(", ", json_decode($r['kebiasaan_baik'],true) ?: []);
        echo "<tr>
          <td>".$no++."</td>
          <td>".tgl_indo($r['tanggal'])."</td>
          <td>".$wajib."</td>
          <td>".h($sunnah)."</td>
          <td>".h($baik)."</td>
          <td>".h($r['dzikir'])."</td>
          <td>".h($r['tilawah'])."</td>
          <td>".nl2br(h($r['catatan']))."</td>
        </tr>";
    }
    echo "</tbody></table>";
    footer_ttd();

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

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