<?php
session_start();
require_once '../../../library/sw-config.php';
require_once '../../../library/sw-function.php';
@include_once '../../../library/vendor/autoload.php';

// ========== CEK SESSION ==========
if (
    empty($_SESSION['SESSION_USER']) &&
    empty($_SESSION['SESSION_ID']) &&
    empty($_SESSION['SESSION_ADMIN']) &&
    empty($_SESSION['username'])
) {
    header('location:../../login/');
    exit;
}

// ========== HELPER ==========
function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
function bulan_tahun($bulan,$tahun){ return bulan_indo($bulan)." ".$tahun; }
function bulan_indo($bulan){
    $bulan_array = [
        "01"=>"Januari","02"=>"Februari","03"=>"Maret",
        "04"=>"April","05"=>"Mei","06"=>"Juni",
        "07"=>"Juli","08"=>"Agustus","09"=>"September",
        "10"=>"Oktober","11"=>"November","12"=>"Desember"
    ];
    $b = str_pad((int)$bulan, 2, "0", STR_PAD_LEFT);
    return isset($bulan_array[$b]) ? $bulan_array[$b] : $bulan;
}
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" alt="">
          </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>';
}

// Ambil struktur tabel aktivitas
function get_fields($conn){
    $cols = [];
    $res = $conn->query("SHOW COLUMNS FROM aktivitas");
    if($res && $res->num_rows){
        while($r = $res->fetch_assoc()){
            if($r['Field'] != 'id'){ // skip id
                $cols[] = $r['Field'];
            }
        }
    }
    return $cols;
}

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

switch ($action) {

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

        $query = "SELECT * FROM aktivitas WHERE MONTH(tanggal)='$bulan' AND YEAR(tanggal)='$tahun' ORDER BY tanggal DESC";
        $result = $connection->query($query);

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

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

        echo '<table><thead><tr><th>No</th>';
        foreach($fields as $f){ echo '<th>'.ucwords(str_replace("_"," ",$f)).'</th>'; }
        echo '</tr></thead><tbody>';

        $no=1;
        if ($result && $result->num_rows > 0) {
            while($row=$result->fetch_assoc()){
                echo '<tr><td>'.$no++.'</td>';
                foreach($fields as $f){
                    echo '<td>'.h($row[$f]).'</td>';
                }
                echo '</tr>';
            }
        } else {
            echo '<tr><td colspan="'.(count($fields)+1).'" align="center">Data tidak ditemukan</td></tr>';
        }
        echo '</tbody></table>';
        footer_ttd();

        $html = ob_get_clean();
        if ($mpdf) {
            $mpdf->WriteHTML($html);
            $mpdf->Output("Laporan-Aktivitas-$bulan-$tahun.pdf",'I');
        } else {
            echo $html;
        }
    break;

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

        $query = "SELECT * FROM aktivitas WHERE MONTH(tanggal)='$bulan' AND YEAR(tanggal)='$tahun' ORDER BY tanggal DESC";
        $result = $connection->query($query);

        if(empty($_GET['print'])){
            header("Content-type: application/vnd.ms-excel");
            header("Content-Disposition: attachment; filename=Laporan-Aktivitas-$bulan-$tahun.xls");
        }

        echo '<h2 style="text-align:center">LAPORAN AKTIVITAS</h2>';
        echo '<p>Periode: '.h(bulan_tahun($bulan,$tahun)).'</p>';

        echo '<table border="1" cellpadding="5" cellspacing="0" width="100%"><thead><tr><th>No</th>';
        foreach($fields as $f){ echo '<th>'.ucwords(str_replace("_"," ",$f)).'</th>'; }
        echo '</tr></thead><tbody>';

        $no=1;
        if ($result && $result->num_rows > 0) {
            while($row=$result->fetch_assoc()){
                echo '<tr><td>'.$no++.'</td>';
                foreach($fields as $f){
                    echo '<td>'.h($row[$f]).'</td>';
                }
                echo '</tr>';
            }
        } else {
            echo '<tr><td colspan="'.(count($fields)+1).'" align="center">Data tidak ditemukan</td></tr>';
        }
        echo '</tbody></table>';

        if(!empty($_GET['print'])){
            echo "<script>window.print();</script>";
        }
    break;

    /* ======== LAPORAN SEMUA DATA (PDF/EXCEL) ======== */
    case 'allpdf':
    case 'allexcel':
        $query = "SELECT * FROM aktivitas ORDER BY tanggal DESC";
        $result = $connection->query($query);

        if($action=='allpdf'){
            $mpdf = class_exists('\Mpdf\Mpdf') ? new \Mpdf\Mpdf(['mode'=>'utf-8','format'=>'A4-L']) : null;
            ob_start();
            echo base_css();
            header_instansi("LAPORAN AKTIVITAS (SEMUA)");
        } else {
            header("Content-type: application/vnd.ms-excel");
            header("Content-Disposition: attachment; filename=Laporan-Aktivitas-All.xls");
            echo '<h2 style="text-align:center">LAPORAN AKTIVITAS (SEMUA)</h2>';
        }

        echo '<table border="1" cellpadding="5" cellspacing="0" width="100%"><thead><tr><th>No</th>';
        foreach($fields as $f){ echo '<th>'.ucwords(str_replace("_"," ",$f)).'</th>'; }
        echo '</tr></thead><tbody>';

        $no=1;
        if ($result && $result->num_rows > 0) {
            while($row=$result->fetch_assoc()){
                echo '<tr><td>'.$no++.'</td>';
                foreach($fields as $f){
                    echo '<td>'.h($row[$f]).'</td>';
                }
                echo '</tr>';
            }
        } else {
            echo '<tr><td colspan="'.(count($fields)+1).'" align="center">Data tidak ditemukan</td></tr>';
        }
        echo '</tbody></table>';

        if($action=='allpdf' && $mpdf){
            footer_ttd();
            $html = ob_get_clean();
            $mpdf->WriteHTML($html);
            $mpdf->Output("Laporan-Aktivitas-All.pdf",'I');
        }
    break;

    default:
        echo '<div class="alert alert-warning">Parameter action tidak dikenali.</div>';
    break;
}
?>
