<?php
include 'koneksi.php';

$tanggal_mulai = '-';
$id_sortasi = '-';
$kode_sortasi = '-';

// Ambil id_produksi dari URL (jika ada)
if (isset($_GET['id_produksi']) && is_numeric($_GET['id_produksi'])) {
    $id_produksi = intval($_GET['id_produksi']);
} else {
    // Ambil produksi terakhir yang punya data pelayuan
    $query_last = "
        SELECT pm.id_produksi, pm.tanggal_mulai
        FROM produksi_master pm
        JOIN pengeringan pl ON pm.id_produksi = pl.id_produksi
        GROUP BY pm.id_produksi
        ORDER BY pm.id_produksi DESC
        LIMIT 1
    ";
    $result_last = mysqli_query($conn, $query_last);
    if ($result_last && mysqli_num_rows($result_last) > 0) {
        $row_last = mysqli_fetch_assoc($result_last);
        $id_produksi = $row_last['id_produksi'];
        $tanggal_mulai = $row_last['tanggal_mulai'];
    } else {
        echo "<script>
            alert('Belum ada produksi yang memiliki data oksidasi. Silakan buat produksi baru.');
            window.location.href = 'index.php';
        </script>";
        exit;
    }
}

// Validasi id_produksi di produksi_master
$query_master = "SELECT tanggal_mulai FROM produksi_master WHERE id_produksi = $id_produksi";
$result_master = mysqli_query($conn, $query_master);
if ($result_master && mysqli_num_rows($result_master) > 0) {
    $row_master = mysqli_fetch_assoc($result_master);
    $tanggal_mulai = $row_master['tanggal_mulai'];
} else {
    echo "<script>
        alert('Produksi dengan ID $id_produksi tidak ditemukan.');
        window.location.href = 'index.php';
    </script>";
    exit;
}

// Cek apakah ada data pelayuan untuk id_produksi ini
$query_sortasi = "SELECT id_sortasi, kode_sortasi FROM sortasi WHERE id_produksi = $id_produksi LIMIT 1";
$result_sortasi = mysqli_query($conn, $query_sortasi);

if ($result_sortasi && mysqli_num_rows($result_sortasi) > 0) {
    $row_sortasi = mysqli_fetch_assoc($result_sortasi);
    $id_sortasi = $row_sortasi['id_sortasi'];
    $kode_sortasi = $row_sortasi['kode_sortasi'];
} else {
    // Cari produksi lain yang masih punya data pelayuan
    $query_lain = "SELECT DISTINCT id_produksi FROM sortasi ORDER BY id_produksi DESC LIMIT 1";
    $result_lain = mysqli_query($conn, $query_lain);

    if ($result_lain && mysqli_num_rows($result_lain) > 0) {
        $row_lain = mysqli_fetch_assoc($result_lain);
        $id_produksi_baru = $row_lain['id_produksi'];

        // Redirect ke produksi lain yang masih punya pelayuan
        header("Location: sortasi.php?id_produksi=$id_produksi_baru&status=dialihkan");
        exit;
    } else {
        // Tidak ada pelayuan sama sekali
        echo "<script>
            alert('Data sortasi kosong! Silakan buat produksi dan data sortasi baru.');
            window.location.href = 'index.php';
        </script>";
        exit;
    }
}

// 1. Ambil berat awal dari pengeringan
$query_awal = mysqli_query($conn, "SELECT id_pengeringan, berat_kering FROM pengeringan WHERE id_produksi = $id_produksi LIMIT 1");
$row_awal = mysqli_fetch_assoc($query_awal);
$id_pengeringan = $row_awal['id_pengeringan'];
$berat_awal = floatval($row_awal['berat_kering']);

// 2. Hitung total berat keluar berdasarkan kode_sortasi
$query_sortasi_total = mysqli_query($conn, "
    SELECT SUM(berat_sortasi + berat_rusak) AS total_keluar
    FROM sortasi 
    WHERE id_produksi = $id_produksi AND id_pengeringan = $id_pengeringan
");
$row_sortasi = mysqli_fetch_assoc($query_sortasi_total);
$total_keluar = floatval($row_sortasi['total_keluar'] ?? 0);

// 3. Hitung sisa
$sisa_berat_kering = $berat_awal - $total_keluar;


$jenis_teh = [];
$result_jenis_teh = mysqli_query($conn, "SELECT id_teh, kelas_mutu, mutu, grade FROM jenis_teh ORDER BY kelas_mutu ASC, mutu ASC");
while ($row = mysqli_fetch_assoc($result_jenis_teh)) {
    $jenis_teh[] = $row;
}
// Ambil kode_sortasi lama jika sudah ada
$query_kode = mysqli_query($conn, "
    SELECT kode_sortasi 
    FROM sortasi 
    WHERE id_produksi = $id_produksi 
      AND id_pengeringan = $id_pengeringan 
    LIMIT 1
");

if (mysqli_num_rows($query_kode) > 0) {
    $row_kode = mysqli_fetch_assoc($query_kode);
    $kode_sortasi = $row_kode['kode_sortasi'];
} else {
    $kode_sortasi = "SO/$id_produksi/$id_pengeringan";
}

// Hitung total teh bagus dan rusak berdasarkan id_produksi dan id_pengeringan
$query_summary = mysqli_query($conn, "
    SELECT 
        SUM(berat_sortasi) AS total_bagus,
        SUM(berat_rusak) AS total_rusak
    FROM sortasi
    WHERE id_produksi = $id_produksi AND id_pengeringan = $id_pengeringan
");

// Ambil total bagus & rusak untuk id_produksi yang sedang di-loop
$query_summary = mysqli_query($conn, "
    SELECT 
        SUM(berat_sortasi) AS total_bagus,
        SUM(berat_rusak) AS total_rusak
    FROM sortasi
    WHERE id_produksi = $id_produksi
");
$row_summary = mysqli_fetch_assoc($query_summary);

// Berat kering dari grup (harus sudah ada sebelumnya dari query produksi)
$total_bagus = floatval($row_summary['total_bagus'] ?? 0);
$total_rusak = floatval($row_summary['total_rusak'] ?? 0);
$persen_bagus = $berat_awal > 0 ? round(($total_bagus / $berat_awal) * 100, 1) : 0;
$persen_rusak = $berat_awal > 0 ? round(($total_rusak / $berat_awal) * 100, 1) : 0;

$summary = [
    'total_bagus' => $total_bagus,
    'total_rusak' => $total_rusak,
    'persen_bagus' => $persen_bagus,
    'persen_rusak' => $persen_rusak
];


?>

<!DOCTYPE html>
<html :class="{ 'theme-dark': dark }" x-data="data()" lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Sortasi</title>
    <link
      href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap"
      rel="stylesheet"
    />
    <link rel="stylesheet" href="./assets/css/tailwind.output.css" />
    <script
      src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/dist/alpine.min.js"
      defer
    ></script>
    <script src="./assets/js/init-alpine.js"></script>
  </head>
  <body>
    <div
      class="flex h-screen bg-gray-50 dark:bg-gray-900"
      :class="{ 'overflow-hidden': isSideMenuOpen}"
    >
      <!-- Desktop sidebar -->
      <?php
      $currentPage = basename($_SERVER['PHP_SELF']);
      include 'sidebar.php';
      ?>
     <?php include 'header.php'; ?>
        <main class="h-full pb-16 overflow-y-auto">
          <div class="container grid px-6 mx-auto">
            <h2
              class="my-6 text-2xl font-semibold text-gray-700 dark:text-gray-200"
            >
              Data Sortasi
            </h2>
          <div x-data="{ open: false }">
  <!-- Tombol Tambah Data -->
  <div class="flex justify-start w-auto mb-4">
    <button @click="open = true"
      class="inline-block px-4 py-2 text-sm font-medium text-white bg-blue-500 hover:bg-blue-600 rounded">
      + Tambah Data
    </button>
  </div>

  <!-- Modal Overlay -->
  <div x-show="open"
       class="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50 overflow-y-auto"
       x-transition:enter="transition ease-out duration-300"
       x-transition:enter-start="opacity-0"
       x-transition:enter-end="opacity-100"
       x-transition:leave="transition ease-in duration-200"
       x-transition:leave-start="opacity-100"
       x-transition:leave-end="opacity-0">

    <!-- Modal Box -->
    <div class="bg-white dark:bg-gray-800 p-6 rounded-xl w-full max-w-4xl mx-4 overflow-y-auto max-h-[90vh]"> 
  <h2 class="text-lg font-semibold mb-4 text-gray-800 dark:text-white">
    Tambah Data Sortasi
  </h2>

 <form action="tambah_sortasi.php" method="POST">
<input type="hidden" name="id_sortasi" value="<?= htmlspecialchars($id_sortasi) ?>">
<input type="hidden" name="kode_sortasi" value="<?= htmlspecialchars($kode_sortasi) ?>">
<input type="hidden" name="id_produksi" value="<?= htmlspecialchars($id_produksi) ?>">
<input type="hidden" name="id_teh" value="<?= htmlspecialchars($id_teh) ?>">
<input type="hidden" name="id_pengeringan" value="<?= htmlspecialchars($id_pengeringan) ?>">
<input type="hidden" name="berat_kering" value="<?= $berat_awal ?>">

  <!-- Kode Produksi -->
  <div class="mb-4">
    <label class="block text-gray-700 dark:text-gray-300">Kode Produksi</label>
    <input type="text" class="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:text-white" 
           value="<?= htmlspecialchars($kode_sortasi) ?>" readonly>
  </div>

  <!-- Tanggal Mulai -->
  <div class="mb-4">
    <label class="block text-gray-700 dark:text-gray-300">Tanggal Mulai</label>
    <input type="text" name="tanggal_mulai" class="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:text-white"
           value="<?= $tanggal_mulai ?>" readonly>
  </div>

  <!-- Berat Oksidasi -->
  <div class="mb-4">
    <label class="block text-gray-700 dark:text-gray-300">Berat Kering (kg)</label>
    <input type="text" value="<?= htmlspecialchars($sisa_berat_kering) ?>" readonly
           class="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:text-white">
  </div>

  <div id="dataContainer">
<div class="mb-4 flex items-end gap-6 group-item">
  <!-- Kondisi Teh -->
  <div class="w-1/4">
    <label class="block text-gray-700 dark:text-gray-300">Kondisi Teh</label>
    <select name="kondisi[]" class="kondisiSelect w-full px-3 py-2 border rounded dark:bg-gray-700 dark:text-white"
            required onchange="toggleKondisi(this)">
      <option value="">-- Pilih Kondisi --</option>
      <option value="Bagus">Bagus</option>
      <option value="Rusak">Rusak</option>
    </select>
  </div>

  <!-- Jenis Teh -->
  <div class="w-1/4">
    <label class="block text-gray-700 dark:text-gray-300">Jenis Teh</label>
    <select name="id_teh[]" required class="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:text-white">
      <option value="">-- Pilih Jenis Teh --</option>
      <?php foreach ($jenis_teh as $teh): ?>
        <option value="<?= $teh['id_teh'] ?>">
          <?= htmlspecialchars($teh['kelas_mutu'] . ' - ' . $teh['mutu'] . ' (' . $teh['grade'] . ')') ?>
        </option>
      <?php endforeach; ?>
    </select>
  </div>

  <!-- Berat Teh -->
  <div class="w-1/4 beratSortasiGroup">
    <label class="block text-gray-700 dark:text-gray-300">Berat Teh (kg)</label>
    <input type="number" step="0.01" name="berat_sortasi[]" 
           class="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:text-white">
  </div>

  <!-- Berat Rusak -->
  <div class="w-1/4 beratRusakGroup hidden">
    <label class="block text-gray-700 dark:text-gray-300">Berat Teh Rusak (kg)</label>
    <input type="number" step="0.01" name="berat_rusak[]"
           class="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:text-white">
  </div>

  <!-- Tombol X -->
  <div class="pt-6">
<button type="button" onclick="removeRow(this)"
  class="px-3 py-2 bg-red-500 text-xs font-medium text-white bg-red-600 hover:bg-red-700 rounded">
  &times;
</button>

  </div>
  </div>
</div>

<button type="button" onclick="addRow()"
  class="px-4 py-2 bg-gray-300 dark:bg-gray-600 text-gray-800 dark:text-white rounded hover:bg-gray-400 dark:hover:bg-gray-500">
  + Tambah Data
</button>

  <!-- Keterangan -->
  <div class="mb-4">
    <label class="block text-gray-700 dark:text-gray-300">Keterangan</label>
    <textarea name="keterangan" required
              class="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:text-white"></textarea>
  </div>

  <!-- Tombol -->
  <div class="flex justify-end space-x-2">
    <button type="button" @click="open = false"
      class="px-4 py-2 bg-gray-300 dark:bg-gray-600 text-gray-800 dark:text-white rounded hover:bg-gray-400 dark:hover:bg-gray-500">
      Batal
    </button>
    <button type="submit"
      class="inline-block px-4 py-2 text-sm font-medium text-white bg-blue-500 hover:bg-blue-600 rounded">
      Simpan
    </button>
  </div>
</form>


</div>
  </div>
</div>

  <div class="w-full overflow-hidden rounded-lg shadow-xs" max-w-xl mx-auto>
    <div class="w-full overflow-x-auto" max-w-xl mx-auto>
      <table class="w-full whitespace-no-wrap">
        <thead>
         
        </thead>
        <tbody class="bg-white divide-y dark:divide-gray-700 dark:bg-gray-800">
  <?php
  include 'koneksi.php';
  $no = 1;
  $query = mysqli_query($conn, "
    SELECT p.*, 
      m.tanggal_mulai, 
      pp.berat_kering,
          p.grade, 
    p.kelas_mutu, 
    p.mutu
    FROM sortasi p
    JOIN produksi_master m ON p.id_produksi = m.id_produksi
    LEFT JOIN pengeringan pp ON p.id_pengeringan = pp.id_pengeringan
    LEFT JOIN jenis_teh j ON p.id_teh = j.id_teh
    ORDER BY p.id_produksi DESC, p.id_sortasi ASC
  ");

  $currentProduksi = null;
  $totalBagus = 0;
  $totalRusak = 0;
  $beratKering = 0;

  while($row = mysqli_fetch_assoc($query)) {

    // Cek apakah produksi berubah
   if ($currentProduksi !== $row['id_produksi']) {
  // Reset nomor urut
  $no = 1;

  // Kalau bukan produksi pertama, tampilkan tfoot sebelumnya
  if ($currentProduksi !== null) {
?>
  <tr class="bg-gray-100 dark:bg-gray-900 text-sm font-semibold text-gray-800 dark:text-white">
    <td colspan="3" class="px-4 py-3 text-right">Total Teh Bagus:</td>
    <td colspan="2" class="px-4 py-3">
      <?= $totalBagus ?> Kg (<?= $beratKering > 0 ? round(($totalBagus / $beratKering) * 100, 1) : 0 ?>%)
    </td>
    <td colspan="2">Total Teh Rusak: <?= $totalRusak ?> Kg (<?= $beratKering > 0 ? round(($totalRusak / $beratKering) * 100, 1) : 0 ?>%)</td>
    <td colspan="3"></td>
  </tr>
<?php
      }

      // Reset total untuk produksi baru
      $totalBagus = 0;
      $totalRusak = 0;
      $beratKering = floatval($row['berat_kering']);
      $currentProduksi = $row['id_produksi'];
?>
  <!-- Judul Produksi Baru -->
  <tr class="bg-gray-200 text-gray-900 dark:text-white font-bold">
    <td colspan="10" class="px-4 py-2">
      Produksi: <?= htmlspecialchars($row['kode_sortasi']) ?> | Tanggal: <?= htmlspecialchars($row['tanggal_mulai']) ?>
    </td>
  </tr>
  <tr class="text-xs font-semibold tracking-wide text-left text-gray-500 uppercase border-b dark:border-gray-700 bg-gray-50 dark:text-gray-400 dark:bg-gray-800">
           <th class="px-4 py-3">No</th>
           <th class="px-4 py-3">Kode Produksi</th>
           <th class="px-4 py-3">Tanggal Produksi</th>
           <th class="px-4 py-3">Berat Kering</th>
          <th class="px-4 py-3">Berat Teh</th>
          <th class="px-4 py-3">Jenis Teh</th>
          <th class="px-4 py-3">Grade</th>
          <th class="px-4 py-3">Kondisi Teh</th>
          <th class="px-4 py-3">Keterangan</th>
          <th class="px-4 py-3">Aksi</th>
          </tr>
<?php
    }

    // Tambahkan berat
    if ($row['kondisi'] === 'Rusak') {
      $totalRusak += floatval($row['berat_rusak']);
    } else {
      $totalBagus += floatval($row['berat_sortasi']);
    }
?>

<tr x-data="{ editOpen: false }" class="text-gray-700 dark:text-gray-400">
  <td class="px-4 py-3"><?= $no++; ?></td>
  <td class="px-4 py-3"><?= htmlspecialchars($row['kode_sortasi']); ?></td>
  <td class="px-4 py-3"><?= htmlspecialchars($row['tanggal_mulai']); ?></td>
  <td class="px-4 py-3"><?= htmlspecialchars($row['berat_kering']); ?> Kg</td>
  <td class="px-4 py-3">
    <?= htmlspecialchars($row['kondisi'] === 'Rusak' ? $row['berat_rusak'] : $row['berat_sortasi']); ?> Kg
  </td>
  <td class="px-4 py-3"><?= htmlspecialchars($row['kelas_mutu'] . ' - ' . $row['mutu']); ?></td>
  <td class="px-4 py-3">Grade <?= htmlspecialchars($row['grade']); ?></td>
  <td class="px-4 py-3">
  <span class="px-2 py-1 text-xs font-semibold rounded 
    <?= $row['kondisi'] === 'Rusak' ? 'px-2 py-1 font-semibold leading-tight text-red-700 bg-red-100 rounded-full dark:bg-red-700 dark:text-red-100'
     : 'px-2 py-1 font-semibold leading-tight text-green-700 bg-green-100 rounded-full dark:bg-green-700 dark:text-green-100' ?>">
    <?= htmlspecialchars($row['kondisi']); ?>
  </span>
</td>

  <td class="px-4 py-3"><?= htmlspecialchars($row['keterangan']); ?></td>
  <td class="px-4 py-3">
    <div class="flex space-x-2">
      <a href="update_sortasi.php?id_sortasi=<?= $row['id_sortasi'] ?>"
         @click.prevent="editOpen = true"
         class="inline-block px-3 py-1 text-xs font-medium text-gray-800 bg-gray-200 hover:bg-gray-300 rounded dark:text-white dark:bg-gray-600 dark:hover:bg-gray-700">
        Edit
      </a>
      <a href="hapus_sortasi.php?id_sortasi=<?= $row['id_sortasi']; ?>"
         onclick="return confirm('Yakin ingin menghapus data ini?')"
         class="inline-block px-3 py-1 text-xs font-medium text-white bg-red-600 hover:bg-red-700 rounded">
        Delete
      </a>
    </div>

    <!-- Modal Edit -->
    <div x-show="editOpen"
         class="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50 overflow-y-auto"
         x-transition:enter="transition ease-out duration-300"
         x-transition:enter-start="opacity-0"
         x-transition:enter-end="opacity-100"
         x-transition:leave="transition ease-in duration-200"
         x-transition:leave-start="opacity-100"
         x-transition:leave-end="opacity-0">
      
      <!-- Modal Box -->
      <div class="bg-white dark:bg-gray-800 p-6 rounded-xl w-full max-w-4xl mx-4 overflow-y-auto max-h-[90vh]">
        <h2 class="text-lg font-semibold mb-4 text-gray-800 dark:text-white">
          Edit Data Sortasi
        </h2>

       <form action="update_sortasi.php" method="POST">
<input type="hidden" name="id_sortasi[]" value="<?= $row['id_sortasi'] ?>">
<input type="hidden" name="kode_sortasi" value="<?= htmlspecialchars($kode_sortasi) ?>">
<input type="hidden" name="id_produksi" value="<?= htmlspecialchars($id_produksi) ?>">
<input type="hidden" name="id_teh" value="<?= htmlspecialchars($id_teh) ?>">
<input type="hidden" name="id_pengeringan" value="<?= htmlspecialchars($id_pengeringan) ?>">
<input type="hidden" name="berat_kering" value="<?= $berat_awal ?>">

  <!-- Kode Produksi -->
  <div class="mb-4">
    <label class="block text-gray-700 dark:text-gray-300">Kode Produksi</label>
    <input type="text" value="<?= htmlspecialchars($kode_sortasi) ?>" readonly 
           class="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:text-white">
  </div>

  <!-- Tanggal Mulai -->
  <div class="mb-4">
    <label class="block text-gray-700 dark:text-gray-300">Tanggal Mulai</label>
    <input type="text" value="<?= htmlspecialchars($tanggal_mulai) ?>" readonly
           class="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:text-white">
  </div>
  <div class="mb-4">
    <label class="block text-gray-700 dark:text-gray-300">Berat Kering (kg)</label>
    <input type="text" value="<?= htmlspecialchars($sisa_berat_kering) ?>" readonly
           class="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:text-white">
  </div>

 
 <div id="dataContainer">
      <div class="mb-4 flex items-end gap-6 group-item">

        <!-- Kondisi Teh -->
        <div class="w-1/4">
          <label class="block text-gray-700 dark:text-gray-300">Kondisi Teh</label>
          <select name="kondisi[]" class="kondisiSelect w-full px-3 py-2 border rounded dark:bg-gray-700 dark:text-white" required onchange="toggleKondisi(this)">
            <option value="">-- Pilih Kondisi --</option>
            <option value="Bagus" <?= $row['kondisi'] === 'Bagus' ? 'selected' : '' ?>>Bagus</option>
            <option value="Rusak" <?= $row['kondisi'] === 'Rusak' ? 'selected' : '' ?>>Rusak</option>
          </select>
        </div>

        <!-- Jenis Teh -->
        <div class="w-1/4">
          <label class="block text-gray-700 dark:text-gray-300">Jenis Teh</label>
          <select name="id_teh[]" required class="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:text-white">
            <option value="">-- Pilih Jenis Teh --</option>
            <?php foreach ($jenis_teh as $teh): ?>
              <option value="<?= $teh['id_teh'] ?>" <?= $row['id_teh'] == $teh['id_teh'] ? 'selected' : '' ?>>
                <?= htmlspecialchars($teh['kelas_mutu'] . ' - ' . $teh['mutu'] . ' (' . $teh['grade'] . ')') ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <!-- Berat Teh -->
        <div class="w-1/4 beratSortasiGroup">
          <label class="block text-gray-700 dark:text-gray-300">Berat Teh (kg)</label>
          <input type="number" step="0.01" name="berat_sortasi[]" value="<?= $row['berat_sortasi'] ?>" class="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:text-white">
        </div>

        <!-- Berat Rusak -->
        <div class="w-1/4 beratRusakGroup <?= $row['kondisi'] === 'Rusak' ? '' : 'hidden' ?>">
          <label class="block text-gray-700 dark:text-gray-300">Berat Teh Rusak (kg)</label>
          <input type="number" step="0.01" name="berat_rusak[]" value="<?= $row['berat_rusak'] ?>" class="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:text-white">
        </div>

        <!-- Tombol X untuk baris edit lama (opsional bisa dikunci) -->
          <div class="pt-6">
<button type="button" onclick="removeRow(this)"
  class="px-3 py-2 bg-red-500 text-xs font-medium text-white bg-red-600 hover:bg-red-700 rounded">
  &times;
</button>

  </div>
  </div>
</div>

<button type="button" onclick="addRow()"
  class="px-4 py-2 bg-gray-300 dark:bg-gray-600 text-gray-800 dark:text-white rounded hover:bg-gray-400 dark:hover:bg-gray-500">
  + Tambah Data
</button>

  <!-- Keterangan -->
  <div class="mb-4">
    <label class="block text-gray-700 dark:text-gray-300">Keterangan</label>
    <textarea name="keterangan" required
              class="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:text-white"><?= htmlspecialchars($row['keterangan']); ?></textarea>
  </div>

  <!-- Tombol -->
  <div class="flex justify-end space-x-2">
    <a href="sortasi.php?id_produksi=<?= $id_produksi ?>" 
       class="px-4 py-2 bg-gray-300 dark:bg-gray-600 text-gray-800 dark:text-white rounded hover:bg-gray-400 dark:hover:bg-gray-500">
      Batal
    </a>
    <button type="submit"
            class="inline-block px-4 py-2 text-sm font-medium text-white bg-blue-500 hover:bg-blue-600 rounded">
      Update
    </button>
  </div>
</form>

      </div>
    </div>
  </td>
</tr>

  <?php } ?>
<script>
function toggleKondisi(selectElement) {
  const group = selectElement.closest('.group-item');
  const kondisi = selectElement.value;
  const sortasiGroup = group.querySelector('.beratSortasiGroup');
  const rusakGroup = group.querySelector('.beratRusakGroup');

  if (kondisi === "Bagus") {
    sortasiGroup.classList.remove('hidden');
    rusakGroup.classList.add('hidden');
  } else if (kondisi === "Rusak") {
    sortasiGroup.classList.add('hidden');
    rusakGroup.classList.remove('hidden');
  } else {
    sortasiGroup.classList.remove('hidden');
    rusakGroup.classList.add('hidden');
  }
}

function addRow() {
  const container = document.getElementById('dataContainer');
  const originalRow = container.querySelector('.group-item');

  if (!originalRow) {
    console.error("Element .group-item tidak ditemukan");
    return;
  }

  const newRow = originalRow.cloneNode(true);

  // Reset value input dan select
  newRow.querySelector('select[name="kondisi[]"]').value = "";
  newRow.querySelector('select[name="id_teh[]"]').value = "";
  newRow.querySelector('input[name="berat_sortasi[]"]').value = "";
  newRow.querySelector('input[name="berat_rusak[]"]').value = "";

  // Reset tampilan kondisi
  newRow.querySelector('.beratSortasiGroup').classList.remove('hidden');
  newRow.querySelector('.beratRusakGroup').classList.add('hidden');

  // Re-bind event onchange untuk select kondisi
  const kondisiSelect = newRow.querySelector('.kondisiSelect');
  kondisiSelect.addEventListener('change', function () {
    toggleKondisi(this);
  });

  container.appendChild(newRow);
}

function removeRow(button) {
  const container = document.getElementById('dataContainer');
  const allRows = container.querySelectorAll('.group-item');

  if (allRows.length > 1) {
    button.closest('.group-item').remove();
  }
}
</script>

        </tbody>
         <tfoot>
    <tr class="bg-gray-100 dark:bg-gray-900 text-sm font-semibold text-gray-800 dark:text-white">
  <td colspan="3" class="px-4 py-3 text-right">Total Teh Bagus:</td>
  <td colspan="2" class="px-4 py-3">
    <?= $totalBagus ?> Kg (<?= $beratKering > 0 ? round(($totalBagus / $beratKering) * 100, 1) : 0 ?>%)
  </td>
  <td colspan="2">Total Teh Rusak: <?= $totalRusak ?> Kg (<?= $beratKering > 0 ? round(($totalRusak / $beratKering) * 100, 1) : 0 ?>%)</td>
  <td colspan="3"></td>
</tr>
</tfoot>

      </table>
    </div>
  </div>
</div>
      </div>
    </div>
  </body>
</html>
