<?php
$autoload = __DIR__ . '/vendor/autoload.php';
if (file_exists($autoload)) {
    require $autoload;
} else {
  
    $PHPSPREADSHEET_AVAILABLE = false;
}

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Fill;

$mysqli = new mysqli('localhost', 'root', '', 'klinik');
if ($mysqli->connect_error) {
    die('Koneksi gagal: ' . $mysqli->connect_error);
}

$jenis = 'obat_keluar';


function kolomAda($mysqli, $table, $col){
    $q = $mysqli->query('SELECT DATABASE() AS db');
    $db = $q ? $q->fetch_assoc()['db'] : '';
    $db = $mysqli->real_escape_string($db);
    $sql = "SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='$db' AND TABLE_NAME='$table' AND COLUMN_NAME='$col' LIMIT 1";
    $r = $mysqli->query($sql);
    return ($r && $r->num_rows > 0);
}

function autoMigrateObatKeluar($mysqli){
    $cek = $mysqli->query("SHOW TABLES LIKE 'obat_keluar'");
    if (!$cek || $cek->num_rows === 0){
        $mysqli->query("CREATE TABLE obat_keluar (
            id INT AUTO_INCREMENT PRIMARY KEY,
            nama VARCHAR(100) NOT NULL,
            satuan VARCHAR(50) DEFAULT '',
            jumlah INT NOT NULL,
            tanggal_keluar DATE NOT NULL,
            nama_pasien VARCHAR(100) DEFAULT '',
            kegunaan VARCHAR(255) DEFAULT ''
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
        return;
    }
    if (kolomAda($mysqli, 'obat_keluar', 'tanggal') && !kolomAda($mysqli, 'obat_keluar', 'tanggal_keluar')){
        $mysqli->query("ALTER TABLE obat_keluar CHANGE COLUMN tanggal tanggal_keluar DATE NOT NULL");
    }
    if (!kolomAda($mysqli, 'obat_keluar', 'satuan')){
        $mysqli->query("ALTER TABLE obat_keluar ADD COLUMN satuan VARCHAR(50) DEFAULT '' AFTER nama");
    }
    if (!kolomAda($mysqli, 'obat_keluar', 'nama_pasien')){
        $mysqli->query("ALTER TABLE obat_keluar ADD COLUMN nama_pasien VARCHAR(100) DEFAULT '' AFTER tanggal_keluar");
    }
    if (!kolomAda($mysqli, 'obat_keluar', 'kegunaan')){
        $mysqli->query("ALTER TABLE obat_keluar ADD COLUMN kegunaan VARCHAR(255) DEFAULT '' AFTER nama_pasien");
    }
}

autoMigrateObatKeluar($mysqli);


$sqlCek = "SELECT id FROM konfigurasi_laporan WHERE jenis_laporan=? LIMIT 1";
if ($stmt = $mysqli->prepare($sqlCek)) {
    $stmt->bind_param('s', $jenis);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($res->num_rows === 0) {
        $today = date('Y-m-d');
        $sqlIns = "INSERT INTO konfigurasi_laporan (jenis_laporan, kop1, kop2, kop3, ttd_tanggal, ttd_diketahui, ttd_jabatan_diketahui, ttd_dibuat, ttd_jabatan_dibuat) VALUES (?, 'DAFTAR OBAT KELUAR KLINIK NBC', 'PERIODE MARET - MEI 2025', 'PT. SINDO LUMBER - PT. INDEXIM UTAMA', ?, '', '', '', '')";
        if ($ins = $mysqli->prepare($sqlIns)) {
            $ins->bind_param('ss', $jenis, $today);
            $ins->execute();
            $ins->close();
        }
    }
    $stmt->close();
}


$sqlCfg = "SELECT * FROM konfigurasi_laporan WHERE jenis_laporan=? LIMIT 1";
$stmtCfg = $mysqli->prepare($sqlCfg);
$stmtCfg->bind_param('s', $jenis);
$stmtCfg->execute();
$config = $stmtCfg->get_result()->fetch_assoc();
$stmtCfg->close();


function tgl_indo($tgl){
    if (!$tgl || $tgl === '0000-00-00') return 'dd-mm-yyyy';
    $bulan = [1 => 'Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'];
    $p = explode('-', $tgl); 
    if (count($p) != 3) return htmlspecialchars($tgl);
    $y = $p[0]; $m = (int)$p[1]; $d = (int)$p[2];
    $b = $bulan[$m] ?? $m;
    return $d . ' ' . $b . ' ' . $y;
}


if (isset($_GET['hapus'])){
    $id = (int)$_GET['hapus'];
    $mysqli->query("DELETE FROM obat_keluar WHERE id=$id");
    echo "<script>alert('Data berhasil dihapus!');window.location.href='obat-keluar.php';</script>";
    exit;
}


$edit_mode = false; 
$edit_data = null;
if (isset($_GET['edit'])){
    $id_edit = (int)$_GET['edit'];
    $resEdit = $mysqli->query("SELECT * FROM obat_keluar WHERE id=$id_edit");
    if ($resEdit && $resEdit->num_rows > 0){
        $edit_mode = true;
        $edit_data = $resEdit->fetch_assoc();
    }
}


if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_obat'])){
    $nama = trim($_POST['nama']);
    $satuan = trim($_POST['satuan']);
    $jumlah = (int)$_POST['jumlah'];
    $tanggal_keluar = $_POST['tanggal_keluar'];
    $nama_pasien = trim($_POST['nama_pasien'] ?? '');
    $kegunaan = trim($_POST['kegunaan'] ?? '');

    if ($nama && $jumlah && $tanggal_keluar){
        if (isset($_POST['id_edit'])){
            $id = (int)$_POST['id_edit'];
            $stmt = $mysqli->prepare("UPDATE obat_keluar SET nama=?, satuan=?, jumlah=?, tanggal_keluar=?, nama_pasien=?, kegunaan=? WHERE id=?");
            $stmt->bind_param('ssisssi', $nama, $satuan, $jumlah, $tanggal_keluar, $nama_pasien, $kegunaan, $id);
        } else {
            $stmt = $mysqli->prepare("INSERT INTO obat_keluar (nama, satuan, jumlah, tanggal_keluar, nama_pasien, kegunaan) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->bind_param('ssisss', $nama, $satuan, $jumlah, $tanggal_keluar, $nama_pasien, $kegunaan);
        }
        $stmt->execute();
        $stmt->close();
        echo "<script>window.location.href='obat-keluar.php';</script>";
        exit;
    }
}


$data = $mysqli->query("SELECT * FROM obat_keluar ORDER BY tanggal_keluar DESC, id DESC");


$query_obat = $mysqli->query("SELECT id, nama_obat, fungsi_obat FROM data_obat ORDER BY nama_obat ASC");
$obat_options = [];
while ($obat = $query_obat->fetch_assoc()) {
    $obat_options[] = $obat;
}



if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['field'],$_POST['value']) && !isset($_POST['submit_obat'])){
    $allowed=['kop1','kop2','kop3','ttd_tanggal','ttd_diketahui','ttd_jabatan_diketahui','ttd_dibuat','ttd_jabatan_dibuat'];
    $field=$_POST['field'];
    $value=$_POST['value'];
    if (in_array($field,$allowed)){
        if ($field==='ttd_tanggal'){
            $value=substr($value,0,10);
            if (!preg_match('/^\d{4}-\d{2}-\d{2}$/',$value)){
                $value=date('Y-m-d');
            }
        }
        $sqlUpd="UPDATE konfigurasi_laporan SET $field=? WHERE jenis_laporan=?";
        $stmt_upd=$mysqli->prepare($sqlUpd);
        $stmt_upd->bind_param('ss',$value,$jenis);
        $stmt_upd->execute();
        $stmt_upd->close();
        exit; 
    }
}


$data=$mysqli->query("SELECT * FROM obat_keluar ORDER BY tanggal_keluar DESC, id DESC");


if (isset($_GET['export']) && $_GET['export'] === 'excel') {
    if (isset($PHPSPREADSHEET_AVAILABLE) && $PHPSPREADSHEET_AVAILABLE === false) {
        echo "<script>alert('Library PhpSpreadsheet belum terpasang. Jalankan: composer require phpoffice/phpspreadsheet');window.location='obat-keluar.php';</script>";
        exit;
    }

    $cfgQ = $mysqli->query("SELECT * FROM konfigurasi_laporan WHERE jenis_laporan='obat_keluar' LIMIT 1");
    $cfg   = $cfgQ ? $cfgQ->fetch_assoc() : $config;
    $res   = $mysqli->query("SELECT * FROM obat_keluar ORDER BY tanggal_keluar DESC, id DESC");

    $spreadsheet = new Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();

  
    $sheet->getColumnDimension('A')->setWidth(5);   
    $sheet->getColumnDimension('B')->setWidth(30);  
    $sheet->getColumnDimension('C')->setWidth(12);  
    $sheet->getColumnDimension('D')->setWidth(10);  
    $sheet->getColumnDimension('E')->setWidth(18);  
    $sheet->getColumnDimension('F')->setWidth(25);  
    $sheet->getColumnDimension('G')->setWidth(35);  

    $logoKiri = __DIR__.'/logokiri.png';
    if (file_exists($logoKiri)) {
        $drawingLeft = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
        $drawingLeft->setName('Logo Kiri');
        $drawingLeft->setPath($logoKiri);
        $drawingLeft->setHeight(70); // px
        $drawingLeft->setCoordinates('A1');
        $drawingLeft->setOffsetX(5);
        $drawingLeft->setOffsetY(2);
        $drawingLeft->setWorksheet($sheet);
    }
    $logoKanan = __DIR__.'/logokanan.png';
    if (file_exists($logoKanan)) {
        $drawingRight = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
        $drawingRight->setName('Logo Kanan');
        $drawingRight->setPath($logoKanan);
        $drawingRight->setHeight(70);
        $drawingRight->setCoordinates('H1');
        $drawingRight->setOffsetX(-5);
        $drawingRight->setOffsetY(2);
        $drawingRight->setWorksheet($sheet);
    }
 
    $sheet->setCellValue('A1', $cfg['kop1']);
    $sheet->setCellValue('A2', $cfg['kop2']);
    $sheet->setCellValue('A3', $cfg['kop3']);
    $sheet->mergeCells('A1:G1');
    $sheet->mergeCells('A2:G2');
    $sheet->mergeCells('A3:G3');
    $sheet->getStyle('A1:A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
    $sheet->getStyle('A1:A3')->getFont()->setBold(true)->setSize(14)->setName('Times New Roman');

   
    $sheet->setCellValue('A4', 'TAHUN 2025');
    $sheet->mergeCells('A4:G4');
    $sheet->getStyle('A4')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
    $sheet->getStyle('A4')->getFont()->setBold(true)->setSize(12)->setName('Times New Roman');

    $headers = ['No','Nama Obat','Satuan','Jumlah','Tanggal Keluar','Nama Pasien','Kegunaan'];
    $col = 'A';
    foreach ($headers as $h) {
        $sheet->setCellValue($col.'6', $h);
        $col++;
    }
    $headerRange = 'A6:G6';
    $sheet->getStyle($headerRange)->getFont()->setBold(true)->setName('Times New Roman');
    $sheet->getStyle($headerRange)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER)->setVertical(Alignment::VERTICAL_CENTER);
    $sheet->getStyle($headerRange)->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB('FF388E3C'); // hijau sesuai tampilan
    $sheet->getStyle($headerRange)->getFont()->getColor()->setARGB('FFFFFFFF');
    $sheet->getRowDimension(6)->setRowHeight(22);

   
    $rowNum = 7;
    $no = 1;
    if ($res) {
        while ($r = $res->fetch_assoc()) {
            $sheet->setCellValue('A'.$rowNum, $no++);
            $sheet->setCellValue('B'.$rowNum, $r['nama']);
            $sheet->setCellValue('C'.$rowNum, $r['satuan']);
            $sheet->setCellValue('D'.$rowNum, (int)$r['jumlah']);
            $sheet->setCellValue('E'.$rowNum, date('d-m-Y', strtotime($r['tanggal_keluar'])));
            $sheet->setCellValue('F'.$rowNum, $r['nama_pasien']);
            $sheet->setCellValue('G'.$rowNum, $r['kegunaan']);
            $rowNum++;
        }
    }

    $lastDataRow = $rowNum - 1;
    if ($lastDataRow < 7) {
       
        $sheet->mergeCells('A7:G7');
        $sheet->setCellValue('A7','Belum ada data.');
        $lastDataRow = 7;
    }

    $sheet->getStyle('A6:G'.$lastDataRow)->getBorders()->getAllBorders()->setBorderStyle(Border::BORDER_THIN);

  
    $sheet->getStyle('A6:G'.$lastDataRow)->getFont()->setName('Times New Roman')->setSize(11);

    $startTTD = $lastDataRow + 3; 
    $tgl_indo = tgl_indo($cfg['ttd_tanggal']);

 
    $sheet->setCellValue('A'.$startTTD, 'Disetujui oleh,');
    $sheet->mergeCells('A'.$startTTD.':C'.$startTTD);

    
    $sheet->setCellValue('E'.$startTTD, 'Ngurit Base Camp, '.$tgl_indo);
    $sheet->mergeCells('E'.$startTTD.':G'.$startTTD);

    $sheet->setCellValue('E'.($startTTD+1), 'Dibuat oleh,');
    $sheet->mergeCells('E'.($startTTD+1).':G'.($startTTD+1));

   
    $spaceRow = $startTTD + 5;

   
    $sheet->setCellValue('A'.$spaceRow, $cfg['ttd_diketahui'] ?: '_________________');
    $sheet->mergeCells('A'.$spaceRow.':C'.$spaceRow);
    $sheet->getStyle('A'.$spaceRow)->getFont()->setUnderline(true);

    $sheet->setCellValue('A'.($spaceRow+1), $cfg['ttd_jabatan_diketahui'] ?: 'Jabatan');
    $sheet->mergeCells('A'.($spaceRow+1).':C'.($spaceRow+1));


    $sheet->setCellValue('E'.$spaceRow, $cfg['ttd_dibuat'] ?: '_________________');
    $sheet->mergeCells('E'.$spaceRow.':G'.$spaceRow);
    $sheet->getStyle('E'.$spaceRow)->getFont()->setUnderline(true);

    $sheet->setCellValue('E'.($spaceRow+1), $cfg['ttd_jabatan_dibuat'] ?: 'Jabatan');
    $sheet->mergeCells('E'.($spaceRow+1).':G'.($spaceRow+1));

 
    $sheet->getStyle('A'.$startTTD.':G'.($spaceRow+1))->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);

    $fname = 'Data_Obat_Keluar_'.date('Ymd_His').'.xlsx';
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="'.$fname.'"');
    header('Cache-Control: max-age=0');
    $writer = new Xlsx($spreadsheet);
    $writer->save('php://output');
    exit;
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8" />
  <title>Data Obat Keluar</title>
  <style>
    body, table, input, button, .kop-surat h2, .kop-surat h3, .kop-surat h4, .ttd-box {
      font-family: 'Times New Roman', Times, serif;
    }
    body {
      background: #fff;
      padding: 30px;
    }
    .kop-surat {
      position: relative;
      text-align: center;
      border-bottom: 3px solid #000;
      padding-bottom: 10px;
      margin-bottom: 20px;
    }
    .kop-surat img.kiri { position: absolute; left: 0; top: 0; width: 80px; }
    .kop-surat img.kanan { position: absolute; right: 0; top: 0; width: 80px; }
    .kop-surat h2, .kop-surat h3, .kop-surat h4 { margin: 2px 0; }

    .btn-container {
      display: flex;
      justify-content: center;
      gap: 10px;
      margin-bottom: 15px;
    }
    .print-btn {
      background: #0d47a1;
      color: white;
      padding: 10px 20px;
      border-radius: 6px;
      text-decoration: none;
    }
    .print-btn:hover { background: #08306b; }
    .home-btn {
      background: #630b57ff;
      color: white;
      padding: 10px 20px;
      border-radius: 6px;
      text-decoration: none;
    }
    .home-btn:hover { background: #1a5e0aff; }

    .form-input {
      max-width: 900px;
      margin: 5px auto;
      padding: 20px;
      background: #f7f7f7;
      border: 1px solid #ccc;
      border-radius: 8px;
    }
    .form-row {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(120px,1fr));
      gap: 10px;
      width: 100%;
    }
    .form-row .wide { grid-column: span 2; }
    input, button {
      width: 100%;
      padding: 10px;
      margin: 4px 0;
      border: 1px solid #ccc;
      border-radius: 6px;
      box-sizing: border-box;
    }
    button {
      background: #149e32ff;
      color: white;
      cursor: pointer;
      margin-top: 12px;
    }

    table {
      width: 100%;
      border-collapse: collapse;
      margin-top: 30px;
      font-size: 14px;
    }
    th, td {
      border: 1px solid #000;
      padding: 8px;
      text-align: center;
      vertical-align: middle;
    }
    th {
      background-color: #388e3fff;
      color: #000;
      -webkit-print-color-adjust: exact;
      print-color-adjust: exact;
    }

    .aksi a {
      padding: 6px 12px;
      text-decoration: none;
      border-radius: 4px;
      color: white;
      margin: 2px;
      display: inline-block;
    }
    .edit { background-color: #f9a825; }
    .hapus { background-color: #e53935; }

    .ttd-container {
      display: flex; justify-content: space-between; margin-top: 60px; padding: 0 40px;
    }
    .ttd-box { width: 45%; text-align: center; }
    .ttd-space { height: 60px; }
    .nama u, .nama span, .ttd-box span.editable-date, .ttd-box u, .ttd-box span[id] { cursor: pointer; }

    @media print {
      .form-input, .btn-container, .aksi { display: none !important; }
      body { margin: 20px; font-size: 11pt; }
      th { background-color: #388e3c !important; color: #fff !important; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
    }
  </style>
  <script>
    function postField(field, value, callback){
      fetch('', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: `field=${field}&value=${encodeURIComponent(value)}`
      }).then(r=>{if(callback)callback();});
    }

    function buatEditable(id, field){
      if(field === 'ttd_tanggal'){
        editTanggal(id, field);
        return;
      }
      const el = document.getElementById(id);
      const old = el.innerText.trim();
      el.contentEditable = true;
      el.focus();
      el.onblur = () => {
        el.contentEditable = false;
        const val = el.innerText.trim();
        postField(field, val);
      };
      el.onkeydown = (e) => {
        if (e.key === 'Enter') {
          e.preventDefault();
          el.blur();
        }
      };
    }

    function editTanggal(id, field){
      const el = document.getElementById(id);
      const current = el.dataset.date || '';
      const inp = document.createElement('input');
      inp.type = 'date';
      inp.value = current;
      inp.onblur = ()=>simpanTanggal(inp, id, field);
      inp.onkeydown = e=>{if(e.key==='Enter'){e.preventDefault();inp.blur();}};
      el.innerHTML = '';
      el.appendChild(inp);
      inp.focus();
    }

    function simpanTanggal(inp, id, field){
      const val = inp.value; 
      postField(field, val, ()=>{
        document.getElementById(id).dataset.date = val;
        document.getElementById(id).innerText = formatIndo(val);
      });
    }

    function formatIndo(ymd){
      if(!ymd) return 'dd-mm-yyyy';
      const bln = ['', 'Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember'];
      const p = ymd.split('-');
      if(p.length!==3) return ymd;
      const y=p[0], m=parseInt(p[1],10), d=parseInt(p[2],10);
      return d+" "+(bln[m]||m)+" "+y;
    }
  </script>
</head>
<body>

<?php $tgl_indo = tgl_indo($config['ttd_tanggal']); ?>


<div class="btn-container">
  <a href="#" class="print-btn" onclick="window.print()">🖨️ Cetak </a>
  <a href="?export=excel" class="home-btn">📥 Expor</a>
  <a href="home.php" class="home-btn">🏠 Kembali </a>
</div>

<div class="form-input">
  <form method="POST">
    <?php if ($edit_mode): ?>
      <input type="hidden" name="id_edit" value="<?php echo $edit_data['id']; ?>">
    <?php endif; ?>
    
    <div style="display: flex; flex-wrap: wrap; gap: 10px; margin-bottom: 10px;">
      <select name="nama" id="nama_obat" required onchange="updateKegunaan()" style="padding: 8px 12px; border-radius: 5px; border: 1px solid #ccc; min-width: 150px;">
        <option value="">Pilih Obat</option>
        <?php foreach ($obat_options as $obat): ?>
          <option value="<?php echo htmlspecialchars($obat['nama_obat']); ?>" 
                  data-fungsi="<?php echo htmlspecialchars($obat['fungsi_obat']); ?>"
                  <?php if ($edit_mode && ($edit_data['nama'] ?? '') === $obat['nama_obat']) echo 'selected'; ?>>
            <?php echo htmlspecialchars($obat['nama_obat']); ?>
          </option>
        <?php endforeach; ?>
      </select>
      <input type="text" name="satuan" placeholder="Satuan" required value="<?php echo htmlspecialchars($edit_data['satuan'] ?? ''); ?>" style="padding: 8px 12px; border-radius: 5px; border: 1px solid #ccc;">
      <input type="number" name="jumlah" placeholder="Jumlah Keluar" required value="<?php echo htmlspecialchars($edit_data['jumlah'] ?? ''); ?>" style="padding: 8px 12px; border-radius: 5px; border: 1px solid #ccc;">
      <input type="date" name="tanggal_keluar" required value="<?php echo htmlspecialchars($edit_data['tanggal_keluar'] ?? ''); ?>" style="padding: 8px 12px; border-radius: 5px; border: 1px solid #ccc;">
      <input type="text" name="nama_pasien" placeholder="Nama Pasien" value="<?php echo htmlspecialchars($edit_data['nama_pasien'] ?? ''); ?>" style="padding: 8px 12px; border-radius: 5px; border: 1px solid #ccc; flex: 1;">
    </div>
    <input type="text" name="kegunaan" id="kegunaan" placeholder="Kegunaan" value="<?php echo htmlspecialchars($edit_data['kegunaan'] ?? ''); ?>" readonly style="width: 100%; padding: 8px 12px; border-radius: 5px; border: 1px solid #ccc; margin-bottom: 10px;">
    <button type="submit" name="submit_obat" style="width: 100%; padding: 12px; background-color: #1ca02c; color: white; font-weight: bold; border: none; border-radius: 5px;">
      <?php echo $edit_mode ? 'Update Obat' : 'Tambah'; ?>
    </button>
  </form>
</div>


<div class="kop-surat">
  <img src="logokiri.png" class="kiri" alt="Logo Kiri">
  <img src="logokanan.png" class="kanan" alt="Logo Kanan">
  <h2 id="kop1" onclick="buatEditable('kop1','kop1')"><?php echo htmlspecialchars($config['kop1']); ?></h2>
  <h3 id="kop2" onclick="buatEditable('kop2','kop2')"><?php echo htmlspecialchars($config['kop2']); ?></h3>
  <h4 id="kop3" onclick="buatEditable('kop3','kop3')"><?php echo htmlspecialchars($config['kop3']); ?></h4>
  <h4>TAHUN 2025</h4>
</div>



<table>
  <thead>
    <tr>
      <th>No</th>
      <th>Obat</th>
      <th>Satuan</th>
      <th>Jumlah</th>
      <th>Keluar</th>
      <th>Pasien</th>
      <th>Kegunaan</th>
      <th class="aksi">Aksi</th>
    </tr>
  </thead>
  <tbody>
    <?php if ($data && $data->num_rows > 0): $no = 1; while ($row = $data->fetch_assoc()): ?>
    <tr>
      <td><?php echo $no++; ?></td>
      <td><?php echo htmlspecialchars($row['nama']); ?></td>
      <td><?php echo htmlspecialchars($row['satuan']); ?></td>
      <td><?php echo (int)$row['jumlah']; ?></td>
      <td><?php echo date('d-m-Y', strtotime($row['tanggal_keluar'])); ?></td>
      <td><?php echo htmlspecialchars($row['nama_pasien']); ?></td>
      <td><?php echo htmlspecialchars($row['kegunaan']); ?></td>
      <td class="aksi">
        <a href="?edit=<?php echo $row['id']; ?>" class="edit">Edit</a>
        <a href="?hapus=<?php echo $row['id']; ?>" class="hapus" onclick="return confirm('Yakin ingin menghapus?')">Hapus</a>
      </td>
    </tr>
    <?php endwhile; else: ?>
    <tr><td colspan="8">Belum ada data.</td></tr>
    <?php endif; ?>
  </tbody>
</table>

<div class="ttd-container">
  <div class="ttd-box">
    <div>Disetujui oleh,</div>
    <div class="ttd-space"></div>
    <div class="nama">
      <u id="ttd_diketahui" onclick="buatEditable('ttd_diketahui','ttd_diketahui')"><?php echo $config['ttd_diketahui'] ?: '_________________'; ?></u><br>
      <span id="ttd_jabatan_diketahui" onclick="buatEditable('ttd_jabatan_diketahui','ttd_jabatan_diketahui')"><?php echo $config['ttd_jabatan_diketahui'] ?: 'Jabatan'; ?></span>
    </div>
  </div>
  <div class="ttd-box">
    <div>Ngurit Base Camp, <span id="ttd_tanggal" data-date="<?php echo htmlspecialchars($config['ttd_tanggal']); ?>" onclick="buatEditable('ttd_tanggal','ttd_tanggal')"><?php echo $tgl_indo; ?></span></div>
    <div>Dibuat oleh,</div>
    <div class="ttd-space"></div>
    <div class="nama">
      <u id="ttd_dibuat" onclick="buatEditable('ttd_dibuat','ttd_dibuat')"><?php echo $config['ttd_dibuat'] ?: '_________________'; ?></u><br>
      <span id="ttd_jabatan_dibuat" onclick="buatEditable('ttd_jabatan_dibuat','ttd_jabatan_dibuat')"><?php echo $config['ttd_jabatan_dibuat'] ?: 'Jabatan'; ?></span>
    </div>
  </div>
</div>
<script>
function updateKegunaan() {
    const obatSelect = document.getElementById('nama_obat');
    const kegunaanField = document.getElementById('kegunaan');
    
    if (obatSelect.selectedIndex > 0) {
        const selectedOption = obatSelect.options[obatSelect.selectedIndex];
        kegunaanField.value = selectedOption.getAttribute('data-fungsi') || '';
    } else {
        kegunaanField.value = '';
    }
}
</script>
</body>
</html> 