<?php
require __DIR__ . '/vendor/autoload.php';

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

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


$jenis = 'pemesanan_obat';
$config = $mysqli->query("SELECT * FROM konfigurasi_laporan WHERE jenis_laporan='$jenis' LIMIT 1")->fetch_assoc();
if (!$config) {
    $mysqli->query("INSERT INTO konfigurasi_laporan (jenis_laporan, kop1, kop2, kop3, ttd_tanggal, ttd_diketahui, ttd_jabatan_diketahui, ttd_dibuat, ttd_jabatan_dibuat)
        VALUES ('$jenis','DAFTAR ORDERAN OBAT - OBATAN KLINIK','BULAN MARET - MEI 2025','PT. SINDO LUMBER - PT. INDEXIM UTAMA',CURDATE(),'Drs. Awiandie Tanseng','Manager Camp','Mitra Gempita, S.Kep, Ners','Kaur K3')");
    $config = $mysqli->query("SELECT * FROM konfigurasi_laporan WHERE jenis_laporan='$jenis' LIMIT 1")->fetch_assoc();
}
$cfg = $config;

function tglIndo($tgl){
    $bulan = [1=>'Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember'];
    $p = explode('-', $tgl);
    return isset($p[2]) ? $p[2].' '.$bulan[(int)$p[1]].' '.$p[0] : $tgl;
}
$tgl_tampil = tglIndo($cfg['ttd_tanggal']);


if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['aksi'])) {
    $nama       = trim($_POST['nama']);
    $satuan     = trim($_POST['satuan']);
    $jumlah     = (int)$_POST['jumlah'];
    $keterangan = trim($_POST['keterangan']);
    if ($_POST['aksi'] === 'tambah') {
        $stmt = $mysqli->prepare("INSERT INTO pemesanan_obat (nama, satuan, jumlah, keterangan) VALUES (?,?,?,?)");
        $stmt->bind_param("ssis", $nama, $satuan, $jumlah, $keterangan);
        $stmt->execute();
        $stmt->close();
    } elseif ($_POST['aksi'] === 'update') {
        $id = (int)$_POST['id_edit'];
        $stmt = $mysqli->prepare("UPDATE pemesanan_obat SET nama=?, satuan=?, jumlah=?, keterangan=? WHERE id=?");
        $stmt->bind_param("ssisi", $nama, $satuan, $jumlah, $keterangan, $id);
        $stmt->execute();
        $stmt->close();
    }
    header("Location: pemesanan-obat.php");
    exit;
}


if (isset($_GET['hapus'])) {
    $id = (int)$_GET['hapus'];
    $mysqli->query("DELETE FROM pemesanan_obat WHERE id=$id");
    header("Location: pemesanan-obat.php");
    exit;
}


$editData = null;
if (isset($_GET['edit'])) {
    $id = (int)$_GET['edit'];
    $editData = $mysqli->query("SELECT * FROM pemesanan_obat WHERE id=$id")->fetch_assoc();
}


$dataPemesanan = $mysqli->query("SELECT * FROM pemesanan_obat ORDER BY nama ASC");


$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 (isset($_GET['export']) && $_GET['export'] == 'excel') {
    $spreadsheet = new Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();

    if (file_exists('logokiri.png')) {
        $logoKiri = new Drawing();
        $logoKiri->setPath('logokiri.png');
        $logoKiri->setHeight(60);
        $logoKiri->setCoordinates('A1');
        $logoKiri->setWorksheet($sheet);
    }
   
    if (file_exists('logokanan.png')) {
        $logoKanan = new Drawing();
        $logoKanan->setPath('logokanan.png');
        $logoKanan->setHeight(60);
        $logoKanan->setCoordinates('E1');
        $logoKanan->setWorksheet($sheet);
    }

  
    $sheet->mergeCells('B1:D1')->setCellValue('B1', $cfg['kop1']);
    $sheet->mergeCells('B2:D2')->setCellValue('B2', $cfg['kop2']);
    $sheet->mergeCells('B3:D3')->setCellValue('B3', $cfg['kop3']);
    $sheet->getStyle('B1:B3')->getFont()->setBold(true)->setSize(14);
    $sheet->getStyle('B1:B3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
    $sheet->getStyle('A5:E5')->getBorders()->getBottom()->setBorderStyle(Border::BORDER_THICK);

 
    $header = ['No', 'Nama', 'Satuan', 'Jumlah', 'Kegunaan'];
    $sheet->fromArray($header, null, 'A6');
    $sheet->getStyle('A6:E6')->applyFromArray([
        'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
        'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => '388e3c']],
        'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER, 'vertical' => Alignment::VERTICAL_CENTER],
        'borders' => ['allBorders' => ['borderStyle' => Border::BORDER_THIN]]
    ]);

   
    $row = 7;
    $no = 1;
    $data = $mysqli->query("SELECT * FROM pemesanan_obat ORDER BY nama ASC");
    while ($r = $data->fetch_assoc()) {
        $sheet->setCellValue('A'.$row, $no++);
        $sheet->setCellValue('B'.$row, $r['nama']);
        $sheet->setCellValue('C'.$row, $r['satuan']);
        $sheet->setCellValue('D'.$row, $r['jumlah'] . ' ' . $r['satuan']);
        $sheet->setCellValue('E'.$row, $r['keterangan']);
        $sheet->getStyle("A{$row}:E{$row}")->getBorders()->getAllBorders()->setBorderStyle(Border::BORDER_THIN);
        $sheet->getStyle("A{$row}:E{$row}")->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
        $sheet->getStyle("A{$row}")->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
        $sheet->getStyle("C{$row}:D{$row}")->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
        $sheet->getStyle("E{$row}")->getAlignment()->setWrapText(true);
        $row++;
    }

   
    foreach (range('A','E') as $col) {
        $sheet->getColumnDimension($col)->setAutoSize(true);
    }

  
    $row += 2;
    $sheet->mergeCells("D$row:E$row")->setCellValue("D$row", "Ngurit Base Camp, " . $tgl_tampil);
    $row++;
    $sheet->setCellValue("C$row", "Disetujui oleh,");
    $sheet->setCellValue("E$row", "Dibuat oleh,");
    $row += 4;
    $sheet->setCellValue("C$row", $cfg['ttd_diketahui']);
    $sheet->setCellValue("E$row", $cfg['ttd_dibuat']);
    $row++;
    $sheet->setCellValue("C".$row, $cfg['ttd_jabatan_diketahui']);
    $sheet->setCellValue("E".$row, $cfg['ttd_jabatan_dibuat']);

    
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="pemesanan-obat.xlsx"');
    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>Pemesanan Obat</title>
<style>
  body {
     font-family:'Times New Roman',serif; 
     padding:30px; background:#fff;
     color:#000; 
    }
  .logo { 
    width:80px;
   }
  .header-table td { 
    text-align:center;
    vertical-align:middle;
   }
  .title div { 
    font-size:18px; 
    font-weight:bold; 
    line-height:1.4; 
  }
  .garis-bawah { 
    border-bottom:3px solid #000; 
    margin:10px 0 30px;
   }
  .btn-group {
     display:flex; 
     justify-content:center; 
     gap:15px; 
     margin-bottom:25px;
     flex-wrap:wrap; 
    }
  .btn-group a { 
    padding:10px 20px; 
    border-radius:6px;
    color:#fff;
    font-weight:bold;
    text-decoration:none;
   }
  .back-btn{
    background:#6a1b9a;
  } 
  .print-btn{
    background:#0d47a1;
  } 
  .excel-btn{
    background:#2e7d32;
  }
  .table-data { 
    width:100%; 
    border-collapse:collapse; 
    margin-bottom:30px; 
  }
  .table-data th,.table-data td{ 
    border:1px solid #000; 
    padding:8px; 
    text-align:center; 
  }
  .table-data th{ 
    background:#388e3c; 
    color:#fff; 
    -webkit-print-color-adjust:exact; 
    print-color-adjust:exact; 
  }
  .hapus-btn{ 
    background:#d32f2f; 
    color:#fff; 
    padding:5px 10px; 
    border-radius:4px; 
    text-decoration:none; 
  }
  .edit-btn{
     background:#f57c00; 
     color:#fff; 
     padding:5px 10px; 
     border-radius:4px; 
     text-decoration:none; 
    }
  .form-container{
     background:#f9f9f9; 
     border:1px solid #ccc; 
     padding:20px; 
     width:400px; 
     max-width:100%; 
     margin:40px auto 50px; 
     border-radius:8px; 
    }
  input,button,select{ 
    font-family:'Times New Roman'; 
    padding:8px; width:100%; 
    margin:5px 0; 
    border:1px solid #999; 
    border-radius:6px; 
  }
  button{ 
    background:#00796b; 
    color:#fff; 
    border:none; 
    cursor:pointer; } button:hover{background:#004d40;}
  [contenteditable]:focus{ 
    outline:2px solid #00f; 
    background:#e0f0ff; 
  }
  @media print { .btn-group,.form-container,.hapus-btn,.edit-btn,.no-print{display:none!important;} }
</style>
</head>
<body>
<br></br>

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


<div class="form-container no-print">
  <form method="POST">
    <?php if ($editData): ?>
      <input type="hidden" name="aksi" value="update">
      <input type="hidden" name="id_edit" value="<?= $editData['id'] ?>">
    <?php else: ?>
      <input type="hidden" name="aksi" value="tambah">
    <?php endif; ?>
    
    
    <select name="nama" id="nama_obat" required onchange="updateKegunaan()">
      <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 ($editData && ($editData['nama'] ?? '') === $obat['nama_obat']) echo 'selected'; ?>>
          <?php echo htmlspecialchars($obat['nama_obat']); ?>
        </option>
      <?php endforeach; ?>
    </select>
    <input type="text" name="satuan" id="satuan" placeholder="Satuan" value="<?= htmlspecialchars($editData['satuan'] ?? '') ?>" required>
    <input type="number" name="jumlah" placeholder="Jumlah" value="<?= htmlspecialchars($editData['jumlah'] ?? '') ?>" required>
    <input type="text" name="keterangan" id="keterangan" placeholder="Kegunaan" value="<?= htmlspecialchars($editData['keterangan'] ?? '') ?>" readonly>
    <button type="submit"><?= $editData ? 'Update Data' : 'Simpan' ?></button>
    <?php if ($editData): ?>
      <a href="pemesanan-obat.php" style="display:inline-block;margin-top:10px;text-align:center;">Batal</a>
    <?php endif; ?>
  </form>
</div>


<table class="header-table" width="100%">
  <tr>
    <td><img src="logokiri.png" class="logo" alt="Logo kiri"></td>
    <td class="title">
      <div contenteditable="true" data-field="kop1"><?= htmlspecialchars($cfg['kop1']) ?></div>
      <div contenteditable="true" data-field="kop2"><?= htmlspecialchars($cfg['kop2']) ?></div>
      <div contenteditable="true" data-field="kop3"><?= htmlspecialchars($cfg['kop3']) ?></div>
    </td>
    <td><img src="logokanan.png" class="logo" alt="Logo kanan"></td>
  </tr>
</table>
<div class="garis-bawah"></div>

<table class="table-data">
  <thead>
    <tr>
      <th>No</th><th>Nama</th><th>Satuan</th><th>Jumlah</th><th>Kegunaan</th><th class="no-print">Aksi</th>
    </tr>
  </thead>
  <tbody>
    <?php $no=1; while($r=$dataPemesanan->fetch_assoc()): ?>
    <tr>
      <td><?= $no++ ?></td>
      <td><?= htmlspecialchars($r['nama']) ?></td>
      <td><?= htmlspecialchars($r['satuan']) ?></td>
      <td><?= (int)$r['jumlah'] ?> <?= htmlspecialchars($r['satuan']) ?></td>
      <td><?= htmlspecialchars($r['keterangan']) ?></td>
      <td class="no-print">
        <a class="edit-btn" href="?edit=<?= $r['id'] ?>">Edit</a>
        <a class="hapus-btn" href="?hapus=<?= $r['id'] ?>" onclick="return confirm('Hapus?')">Hapus</a>
      </td>
    </tr>
    <?php endwhile; ?>
  </tbody>
</table>


<div style="margin-top:25px; font-family:'Times New Roman'; font-size:16px;">
  <table style="width:100%; text-align:center;">
    <tr>
      <td style="width:50%"></td>
      <td>Ngurit Base Camp, <span contenteditable="true" data-field="ttd_tanggal"><?= htmlspecialchars($tgl_tampil) ?></span></td>
    </tr>
    <tr><td>Disetujui oleh,</td><td>Dibuat oleh,</td></tr>
    <tr>
      <td style="padding-top:60px;">
        <div contenteditable="true" data-field="ttd_diketahui"><u><?= htmlspecialchars($cfg['ttd_diketahui']) ?></u></div>
        <div contenteditable="true" data-field="ttd_jabatan_diketahui"><?= htmlspecialchars($cfg['ttd_jabatan_diketahui']) ?></div>
      </td>
      <td style="padding-top:60px;">
        <div contenteditable="true" data-field="ttd_dibuat"><u><?= htmlspecialchars($cfg['ttd_dibuat']) ?></u></div>
        <div contenteditable="true" data-field="ttd_jabatan_dibuat"><?= htmlspecialchars($cfg['ttd_jabatan_dibuat']) ?></div>
      </td>
    </tr>
  </table>
</div>

<script>
function updateKegunaan() {
    const obatSelect = document.getElementById('nama_obat');
    const keteranganField = document.getElementById('keterangan');
    
    if (obatSelect.selectedIndex > 0) {
        const selectedOption = obatSelect.options[obatSelect.selectedIndex];
        keteranganField.value = selectedOption.getAttribute('data-fungsi') || '';
    } else {
        keteranganField.value = '';
    }
}
</script>

</body>
</html>
