<?php

session_start();
if (!isset($_SESSION['username'])) {
    header('Location: users.php');
    exit;
}

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


$masuk_data = [];
$q1 = $conn->query("SELECT nama, SUM(jumlah) AS total FROM obat_masuk GROUP BY nama");
if ($q1) {
    while ($row = $q1->fetch_assoc()) {
        $masuk_data[$row['nama']] = (int)$row['total'];
    }
}

$keluar_data = [];
$q2 = $conn->query("SELECT nama, SUM(jumlah) AS total FROM obat_keluar GROUP BY nama");
if ($q2) {
    while ($row = $q2->fetch_assoc()) {
        $keluar_data[$row['nama']] = (int)$row['total'];
    }
}


$expired_data = [];
$q3 = $conn->query("SELECT nama, SUM(jumlah) AS total FROM obat_masuk WHERE tanggal < CURDATE() GROUP BY nama");
if ($q3) {
    while ($row = $q3->fetch_assoc()) {
        $expired_data[$row['nama']] = (int)$row['total'];
    }
}


$all_names = array_unique(array_merge(array_keys($masuk_data), array_keys($keluar_data), array_keys($expired_data)));
sort($all_names);

$labels = json_encode($all_names, JSON_UNESCAPED_UNICODE);
$data_masuk  = [];
$data_keluar = [];
$data_expired = [];
foreach ($all_names as $nama) {
    $data_masuk[]   = $masuk_data[$nama]   ?? 0;
    $data_keluar[]  = $keluar_data[$nama]  ?? 0;
    $data_expired[] = $expired_data[$nama] ?? 0;
}


$total_masuk_all   = array_sum($data_masuk);
$total_keluar_all  = array_sum($data_keluar);
$total_sisa_all    = max(0, $total_masuk_all - $total_keluar_all);
$total_expired_all = array_sum($data_expired);


$obat_sql = "
    SELECT om.nama,
           IFNULL(tm.total_masuk,0) AS total_masuk,
           IFNULL(tk.total_keluar,0) AS total_keluar,
           (IFNULL(tm.total_masuk,0) - IFNULL(tk.total_keluar,0)) AS sisa_obat,
           MAX(om.tanggal) AS tanggal_kadaluarsa
    FROM obat_masuk om
    LEFT JOIN (
        SELECT nama, SUM(jumlah) AS total_masuk
        FROM obat_masuk
        GROUP BY nama
    ) tm ON tm.nama = om.nama
    LEFT JOIN (
        SELECT nama, SUM(jumlah) AS total_keluar
        FROM obat_keluar
        GROUP BY nama
    ) tk ON tk.nama = om.nama
    GROUP BY om.nama
    ORDER BY om.nama ASC
";
$obat_list = $conn->query($obat_sql);
?>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Beranda Pengolahan Obat</title>
  <link href="https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;500;600&display=swap" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  <style>
    * { margin: 0; padding: 0; box-sizing: border-box; }
    body {
      font-family: 'Poppins', sans-serif;
      background-image: url('hutan.jpg');
      background-size: cover;
      background-position: center;
      background-attachment: fixed;
      color: #333;
    }
    header {
      background: rgba(61, 43, 226, 0.9);
      color: white;
      padding: 20px;
      text-align: center;
      box-shadow: 0 2px 8px rgba(0,0,0,0.2);
    }
    .container { display: flex; min-height: 100vh; }
    .sidebar {
      width: 240px;
      background: rgba(61, 43, 226, 0.9);
      padding-top: 20px;
      box-shadow: 2px 0 8px rgba(0,0,0,0.2);
    }
    .sidebar a {
      display: block;
      padding: 15px 25px;
      color: white;
      text-decoration: none;
      font-weight: 500;
      transition: background-color 0.3s ease;
    }
    .sidebar a:hover { background: rgba(255, 255, 255, 0.15); }
    .main { flex: 1; padding: 30px; }
    .card {
      background: rgba(255, 255, 255, 0.85);
      padding: 25px;
      border-radius: 12px;
      margin-bottom: 25px;
      box-shadow: 0 4px 10px rgba(0,0,0,0.1);
      backdrop-filter: blur(5px);
    }
    .card h2 { margin-bottom: 12px; color: #4a148c; font-size: 20px; }
    canvas {
      margin-top: 20px;
      background: #fff;
      padding: 15px;
      border-radius: 10px;
      box-shadow: 0 3px 10px rgba(0,0,0,0.1);
      max-height: 400px;
    }
    .stat-summary {
      display: flex;
      flex-wrap: wrap;
      gap: 16px;
      margin-top: 20px;
      justify-content: flex-start;
    }
    .stat-box {
      flex: 1 1 160px;
      min-width: 160px;
      padding: 16px;
      border-radius: 10px;
      background: rgba(255,255,255,0.95);
      box-shadow: 0 2px 6px rgba(0,0,0,0.1);
      text-align: center;
    }
    .stat-box h3 { font-size: 16px; margin-bottom: 8px; font-weight: 600; color: #4a148c; }
    .stat-box .angka { font-size: 22px; font-weight: 700; line-height: 1; }
    .stat-box.masuk  .angka { color: #42a5f5; }
    .stat-box.keluar .angka { color: #ef5350; }
    .stat-box.sisa   .angka { color: #66bb6a; }
    .stat-box.expired .angka { color: #8e24aa; }
    .table-expired {
      width: 100%;
      border-collapse: collapse;
      margin-top: 10px;
      background: #fff;
      font-size: 14px;
      overflow-x: auto; 
    }
    .table-expired th, .table-expired td {
      padding: 8px 10px;
      border: 1px solid rgba(0,0,0,0.15);
      text-align: center;
    }
    .table-expired thead th {
      background: #f8bbd0;
      color: #333;
      font-weight: 600;
      white-space: nowrap;
      
    }
    .table-expired tbody tr:nth-child(even) { background: rgba(0,0,0,0.03); }
    .table-expired tbody tr:hover { background: rgba(138,43,226,0.10); }
    .catatan-wrapper {
      max-width: 100%;
    }
    .catatan-wrapper p {
      font-size: 14px;
      line-height: 1.8;
      color: #333;
      text-align: justify;
      background: #fffde7;
      padding: 15px 20px;
      border-radius: 8px;
      border: 1px solid rgba(0,0,0,0.2);
      box-shadow: inset 0 0 3px rgba(0,0,0,0.15);
      text-indent: 30px;
    }
    @media (max-width: 768px) {
      .container { flex-direction: column; }
      .sidebar { width: 100%; display: flex; overflow-x: auto; }
      .sidebar a { flex: 1; text-align: center; font-size: 14px; }
      .stat-summary { justify-content: center; }
      .table-expired { font-size: 13px; }
      .card { padding: 20px; }
      .table-expired {font-size: 14px; }
}
    
  </style>
</head>
<body>

<header>
  <h1>Selamat Datang Di Aplikasi Pengolahan Data Obat Klinik NBC</h1>
</header>

<div class="container">
  <div class="sidebar">
    <a href="home.php"><i class='bx bx-home'></i> Home</a>
    <a href="data-obat.php"><i class='bx bx-data-obat'></i> Daftar Obat</a>
    <a href="obat-masuk.php"><i class='bx bx-obat-masuk'></i> Obat Masuk</a>
    <a href="obat-keluar.php"><i class='bx bx-obat keluar'></i> Obat Keluar</a>
    <a href="laporan.php"><i class='bx bx-bar-laporan'></i> Laporan</a>
    <a href="pemesanan-obat.php"><i class='bx bx-pemesanan-obat'></i> Pemesanan Obat</a>
    <a href="users.php"><i class='bx bx-log-out'></i> Keluar</a>
  </div>

  <div class="main">
    <div class="card">
      <h2>Aplikasi Pengolahan Data Obat Berbasis Web Pada Klinik PT. Sindo Lumber Kabupaten Barito Selatan</h2>
    </div>

    <div class="card">
      <h2>Tentang PT. Sindo Lumber</h2>
      <div class="catatan-wrapper">
        <p>
          PT. Sindo Lumber merupakan perusahaan pemegang Hak Pengusaha Hutan (HPH) 
          yang beroperasi di Kabupaten Barito Selatan, Kalimantan Tengah, tepatnya di Desa Ngurit.
          Perusahaan ini bergerak di bidang industri kehutanan, khususnya dalam pengolahan hasil hutan kayu secara berkelanjutan. 
          PT. Sindo Lumber merupakan anak perusahaan dari PT. Surya Satya Timur Group, yang memiliki komitmen terhadap pengelolaan
          hutan lestari dengan prinsip berkelanjutan secara lingkungan, sosial, dan ekonomi (Buku Data Pokok IUPHHK PT. Sindo Lumber).
          Sebagai salah satu Perusahaan yang bergerak di bidang pengolahan kayu, PT. Sindo Lumber memiliki fasilitas klinik yang berfungsi 
          untuk memberikan pelayanan bagi karyawan maupun warga setempat, Klinik ini memiliki peran penting dalam mendukung kesehatan kerja 
          dan menjaga produktivitas tenaga kerja di lingkungan perusahaan.
        </p>
      </div>
    </div>

    <div class="card">
      <h2>📊 Statistik Stok Obat</h2>
      <canvas id="obatChart"></canvas>
      <div class="stat-summary">
        <div class="stat-box masuk">
          <h3>Total Obat Masuk</h3>
          <div class="angka"><?= number_format($total_masuk_all) ?></div>
        </div>
        <div class="stat-box keluar">
          <h3>Total Obat Keluar</h3>
          <div class="angka"><?= number_format($total_keluar_all) ?></div>
        </div>
        <div class="stat-box sisa">
          <h3>Sisa Obat</h3>
          <div class="angka"><?= number_format($total_sisa_all) ?></div>
        </div>
        <div class="stat-box expired">
          <h3>Obat Expired</h3>
          <div class="angka"><?= number_format($total_expired_all) ?></div>
        </div>
      </div>
    </div>

  
    <div class="card">
      <h2>Stok Obat Klinik NBC</h2>
      <?php if ($obat_list && $obat_list->num_rows > 0): ?>
      <table class="table-expired">
        <thead>
          <tr>
            <th>No</th>
            <th>Nama Obat</th>
            <th>Obat Masuk</th>
            <th>Obat Keluar</th>
            <th>Sisa Obat</th>
            <th>Keterangan</th>
            <th>Tanggal Kadaluarsa</th>
          </tr>
        </thead>
        <tbody>
        <?php $no=1; while($row = $obat_list->fetch_assoc()):
            $sisa = (int)$row['sisa_obat'];
            $tgl_kadaluarsa = $row['tanggal_kadaluarsa'];
            $status = 'Ada';
            $today = date('Y-m-d'); 
            $kadaluarsa = date('Y-m-d', strtotime($tgl_kadaluarsa));
            $is_expired = $kadaluarsa < $today;
            $is_habis = $sisa <= 0;
            if ($is_expired && $is_habis) {
            $status = 'Expired & Habis';
            } elseif ($is_expired) {
            $status = 'Expired';
            } elseif ($is_habis) {
            $status = 'Habis';
            }

        ?>
          <tr>
            <td><?= $no++ ?></td>
            <td><?= htmlspecialchars($row['nama']) ?></td>
            <td><?= number_format((int)$row['total_masuk']) ?></td>
            <td><?= number_format((int)$row['total_keluar']) ?></td>
            <td><?= number_format($sisa) ?></td>
            <td><?= $status ?></td>
            <td><?= date('d-m-Y', strtotime($tgl_kadaluarsa)) ?></td>
          </tr>
        <?php endwhile; ?>
        </tbody>
      </table>
      <?php else: ?>
        <em>Data obat belum tersedia.</em>
      <?php endif; ?>
    </div>
  </div>
</div>

<script>
const ctx = document.getElementById('obatChart');
new Chart(ctx, {
  type: 'bar',
  data: {
    labels: <?= $labels ?>,
    datasets: [
      { label: 'Obat Masuk', data: <?= json_encode($data_masuk) ?>, backgroundColor: '#42a5f5' },
      { label: 'Obat Keluar', data: <?= json_encode($data_keluar) ?>, backgroundColor: '#ef5350' },
      { label: 'Obat Expired', data: <?= json_encode($data_expired) ?>, backgroundColor: '#8e24aa' }
    ]
  },
  options: {
    responsive: true,
    plugins: {
      title: { display: true, text: 'Jumlah Obat Masuk, Keluar & Expired Berdasarkan Nama Obat' },
      legend: { position: 'top' },
      tooltip: {
        callbacks: {
          label: function(context) {
            const label = context.dataset.label || '';
            const value = context.parsed.y ?? 0;
            return label + ': ' + new Intl.NumberFormat('id-ID').format(value);
          }
        }
      }
    },
    scales: {
      y: { beginAtZero: true, title: { display: true, text: 'Jumlah' } },
      x: { title: { display: true, text: 'Nama Obat' } }
    }
  }
});
</script>

</body>
</html>
