<?php
include 'koneksi.php';

$tanggal_mulai = '-';
$id_penggilingan = '-';
$kode_penggilingan = '-';

// 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 penggilingan 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 penggilingan. 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_penggilingan = "SELECT id_penggilingan, kode_penggilingan FROM penggilingan WHERE id_produksi = $id_produksi LIMIT 1";
$result_penggilingan = mysqli_query($conn, $query_penggilingan);

if ($result_penggilingan && mysqli_num_rows($result_penggilingan) > 0) {
    $row_penggilingan = mysqli_fetch_assoc($result_penggilingan);
    $id_penggilingan = $row_penggilingan['id_penggilingan'];
    $kode_penggilingan = $row_penggilingan['kode_penggilingan'];
} else {
    // Cari produksi lain yang masih punya data pelayuan
    $query_lain = "SELECT DISTINCT id_produksi FROM penggilingan 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: penggilingan.php?id_produksi=$id_produksi_baru&status=dialihkan");
        exit;
    } else {
        // Tidak ada pelayuan sama sekali
        echo "<script>
            alert('Data penggilingan kosong! Silakan buat produksi dan data penggilingan baru.');
            window.location.href = 'index.php';
        </script>";
        exit;
    }
}

// (Optional) Ambil jumlah pucuk dari penerimaan
$query_layu = "SELECT berat_layu FROM pelayuan WHERE id_produksi = $id_produksi LIMIT 1";
$result_layu = mysqli_query($conn, $query_layu);
$berat_layu = '-';
if ($result_layu && mysqli_num_rows($result_layu) > 0) {
    $row_layu = mysqli_fetch_assoc($result_layu);
    $berat_layu = $row_layu['berat_layu'];
}
?>

<!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>Penggilingan</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>
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.css"
    />
    <script
      src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"
      defer
    ></script>
    <script src="./assets/js/charts-lines.js" defer></script>
    <script src="./assets/js/charts-pie.js" defer></script>
    <script src="./assets/js/charts-bars.js" defer></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 px-6 mx-auto grid">
            <h2
              class="my-6 text-2xl font-semibold text-gray-700 dark:text-gray-200"
            >
              Data Penggilingan
            </h2>
         <!-- Tombol Tambah Data -->
<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"
       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-xl mx-4">
  <h2 class="text-lg font-semibold mb-4 text-gray-800 dark:text-white">
    Tambah Data Penggilingan
  </h2>

  <form action="tambah_penggilingan.php" method="POST">
 <input type="hidden" name="id_penggilingan" value="<?= htmlspecialchars($id_penggilingan) ?>">
<input type="hidden" name="id_produksi" value="<?= htmlspecialchars($id_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_penggilingan) ?>" readonly>
</div>

  <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>

  <div class="mb-4">
    <label class="block text-gray-700 dark:text-gray-300">Berat Layu (kg)</label>
    <input type="text" value="<?= htmlspecialchars($berat_layu) ?>" 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 Giling (kg)</label>
    <input type="number" step="0.01" name="berat_giling" required 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">Suhu Bubuk (°C)</label>
    <input type="number" name="suhu_bubuk" id="suhu_bubuk" step="0.1" required
           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">Kelembapan (%)</label>
    <input type="number" name="kelembapan" id="kelembapan" step="0.1" required
           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">Suhu Ruangan (°C)</label>
    <input type="number" name="suhu_ruangan" id="suhu_ruangan" step="0.1" required
           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">Standar Mutu Penggilingan</label>
    <div class="flex items-center space-x-2">
      <input type="checkbox" id="standar_penggilingan" name="standar_penggilingan" value="Memenuhi Standar" readonly disabled>
      <label for="standar_penggilingan" class="text-gray-700 dark:text-gray-300">
        Otomatis: Kelembapan ≥ 80% dan Suhu Ruangan 16–29°C
      </label>
    </div>
  </div>

  <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>

    <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="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">
        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>
          <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 Layu</th>
            <th class="px-4 py-3">Berat Hasil Giling</th>
            <th class="px-4 py-3">Suhu Bubuk</th>
            <th class="px-4 py-3">Kelembapan</th>
            <th class="px-4 py-3">Suhu Ruangan</th>
            <th class="px-4 py-3">Standar Mutu Penggilingan</th>
            <th class="px-4 py-3">Keterangan</th>
            <th class="px-4 py-3">Aksi</th>
          </tr>
        </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_layu
  FROM penggilingan p
  JOIN produksi_master m ON p.id_produksi = m.id_produksi
  LEFT JOIN pelayuan pp ON p.id_pelayuan = pp.id_pelayuan
  ORDER BY p.id_penggilingan ASC
");
while($row = mysqli_fetch_assoc($query)) {
?>
<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_penggilingan']); ?></td>
  <td class="px-4 py-3"><?= htmlspecialchars($row['tanggal_mulai']); ?></td>
  <td class="px-4 py-3"><?= htmlspecialchars($row['berat_layu']); ?> Kg</td>
  <td class="px-4 py-3"><?= htmlspecialchars($row['berat_giling']); ?> Kg</td>
  <td class="px-4 py-3"><?= htmlspecialchars($row['suhu_bubuk']); ?> °C</td>
  <td class="px-4 py-3"><?= htmlspecialchars($row['kelembapan']); ?> %</td>
  <td class="px-4 py-3"><?= htmlspecialchars($row['suhu_ruangan']); ?> °C</td>
  <td class="px-4 py-3"><?= htmlspecialchars($row['standar_penggilingan']); ?></td>
  <td class="px-4 py-3"><?= htmlspecialchars($row['keterangan']); ?></td>
  <td class="px-4 py-3">
    <div class="flex space-x-2">
      <!-- Tombol Edit -->
      <a href="update_penggilingan.php"
         @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>

      <!-- Tombol Delete -->
      <a href="hapus_penggilingan.php?id_penggilingan=<?= $row['id_penggilingan']; ?>"
         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"
         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-xl mx-4">
        <h2 class="text-lg font-semibold mb-4 text-gray-800 dark:text-white">
          Edit Data Penggilingan
        </h2>

        <form action="update_penggilingan.php" method="POST">
  <input type="hidden" name="id_penggilingan" value="<?= htmlspecialchars($id_penggilingan) ?>">
  <input type="hidden" name="id_produksi" value="<?= htmlspecialchars($id_produksi) ?>">


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

  <div>
    <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 focus:outline-none focus:ring-2 focus:ring-blue-500">
  </div>

  <div class="mb-4">
    <label class="block text-gray-700 dark:text-gray-300">Berat Layu (kg)</label>
    <input type="number" name="berat_layu" required disabled
      class="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:text-white"
      value="<?= htmlspecialchars($row['berat_layu']); ?>">
  </div>

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

  <div class="mb-4">
    <label class="block text-gray-700 dark:text-gray-300">Suhu Bubuk (°C)</label>
    <input type="number" name="suhu_bubuk" step="0.1" required
           class="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:text-white"
           value="<?= htmlspecialchars($row['suhu_bubuk']); ?>">
  </div>

  <div class="mb-4">
    <label class="block text-gray-700 dark:text-gray-300">Kelembapan (%)</label>
    <input type="number" name="kelembapan" step="0.1" required
           class="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:text-white"
           value="<?= htmlspecialchars($row['kelembapan']); ?>">
  </div>

  <div class="mb-4">
    <label class="block text-gray-700 dark:text-gray-300">Suhu Ruangan (°C)</label>
    <input type="number" name="suhu_ruangan" step="0.1" required
           class="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:text-white"
           value="<?= htmlspecialchars($row['suhu_ruangan']); ?>">
  </div>

<div class="mb-4">
    <label class="block text-gray-700 dark:text-gray-300">Standar Penggilingan</label>
    <input type="text" name="standar_penggilingan" disabled
           class="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:text-white"
           value="<?= htmlspecialchars($row['standar_penggilingan']); ?>">
    <p class="text-sm text-gray-500 dark:text-gray-400 mt-1 italic">Otomatis: Suhu Bubuk 60-70°C Kelembapan ≥ 80% dan Suhu Ruangan 16–29°C</p>
  </div>

  <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>

  <div class="flex justify-end space-x-2">
    <button type="button" @click="editOpen = 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">
      Update
    </button>
  </div>
</form>

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

  <?php } ?>
  <script>
function updateStandarPelayuan() {
  const suhuBubuk = parseFloat(document.getElementById('suhu_bubuk').value);
  const kelembapan = parseFloat(document.getElementById('kelembapan').value);
  const suhuRuangan = parseFloat(document.getElementById('suhu_ruangan').value);
  const standarInput = document.getElementById('standar_penggilingan');

  if (!isNaN(suhuBubuk) && !isNaN(kelembapan) && !isNaN(suhuRuangan)) {
    if (
      suhuBubuk >= 60 && suhuBubuk <= 70 &&
      kelembapan > 80 &&
      suhuRuangan >= 16 && suhuRuangan <= 29
    ) {
      standarInput.value = 'Memenuhi';
    } else {
      standarInput.value = 'Tidak Memenuhi';
    }
  } else {
    standarInput.value = '';
  }
}
</script>

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