<?php
include 'koneksi.php';

$tanggal_mulai = '-';
$id_penerimaan = '-';
$kode_penerimaan = '-';

// 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 penerimaan
    $query_last = "
        SELECT pm.id_produksi, pm.tanggal_mulai
        FROM produksi_master pm
        JOIN penerimaan_pucuk pp ON pm.id_produksi = pp.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 penerimaan. 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;
}

// Ambil penerimaan pertama dari produksi aktif
$query_penerimaan = "SELECT id_penerimaan, kode_penerimaan FROM penerimaan_pucuk WHERE id_produksi = $id_produksi LIMIT 1";
$result_penerimaan = mysqli_query($conn, $query_penerimaan);

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

<!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>Penerimaan Pucuk</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>
    <script src="https://cdn.jsdelivr.net/npm/alpinejs@2.8.2" 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 Penerimaan Pucuk
            </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 Penerimaan Pucuk
  </h2>

<form action="tambah_pucuk.php" method="POST">
  <input type="hidden" name="id_penerimaan" value="<?= htmlspecialchars($id_penerimaan) ?>">
<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 Penerimaan</label>
  <input type="text" class="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:text-white" value="<?= htmlspecialchars($kode_penerimaan) ?>" 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 for="jumlah_pucuk" class="block text-gray-700 dark:text-gray-300">Jumlah Pucuk (kg)</label>
    <input type="number" id="jumlah_pucuk" name="jumlah_pucuk" min="0" step="0.1" required
           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>

  <!-- MC Basah -->
  <div class="mb-4">
    <label for="mc_basah" class="block text-gray-700 dark:text-gray-300">MC Basah (%)</label>
    <input type="number" id="mc_basah" name="mc_basah" min="0" max="100" step="0.1" required
           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>

  <!-- Kontaminasi -->
  <div class="mb-4">
    <label class="block text-gray-700 dark:text-gray-300">Kontaminasi</label>
    <div class="flex space-x-4 mt-1 text-gray-700 dark:text-gray-300">
      <label class="flex items-center">
        <input type="radio" name="kontaminasi" value="Ya" required
               class="mr-2">
        Ya
      </label>
      <label class="flex items-center">
        <input type="radio" name="kontaminasi" value="Tidak" required
               class="mr-2">
        Tidak
      </label>
    </div>
  </div>

  <!-- Standar Mutu (Auto Check) -->
  <div class="mb-4">
    <label class="block text-gray-700 dark:text-gray-300">Standar Mutu Pucuk</label>
    <div class="flex items-center space-x-2">
      <input type="checkbox" id="standar_pucuk" disabled
             class="form-checkbox text-green-500">
      <label for="standar_pucuk" class="text-gray-700 dark:text-gray-300">
        Memenuhi standar MC ≤ 60% dan Bebas Kontaminasi
      </label>
    </div>
  </div>

  <!-- Keterangan -->
  <div class="mb-4">
    <label for="keterangan" class="block text-gray-700 dark:text-gray-300">Keterangan</label>
    <textarea id="keterangan" name="keterangan" required
              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"></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="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500">
      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">Jumlah Pucuk</th>
            <th class="px-4 py-3">MC Basah</th>
            <th class="px-4 py-3">Kontaminasi</th>
            <th class="px-4 py-3">Standar Pucuk</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;
// Ambil data penerimaan_pucuk dan join ke produksi_master untuk dapatkan tanggal_mulai
$query = mysqli_query($conn, "
  SELECT p.*, m.tanggal_mulai 
  FROM penerimaan_pucuk p 
  JOIN produksi_master m ON p.id_produksi = m.id_produksi 
  ORDER BY p.id_penerimaan 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_penerimaan']); ?></td>
  <td class="px-4 py-3"><?= htmlspecialchars($row['tanggal_mulai']); ?></td>
<td class="px-4 py-3"><?= htmlspecialchars($row['jumlah_pucuk']); ?>Kg</td>
<td class="px-4 py-3"><?= htmlspecialchars($row['mc_basah']); ?>%</td>
  <td class="px-4 py-3"><?= htmlspecialchars($row['kontaminasi']); ?></td>
  <td class="px-4 py-3"><?= htmlspecialchars($row['standar_pucuk']); ?></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_pucuk.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_pucuk.php?id_penerimaan=<?= $row['id_penerimaan']; ?>&id_produksi=<?= $id_produksi ?>"
   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 Penerimaan Pucuk
        </h2>

       <form action="update_pucuk.php" method="POST">
        <input type="hidden" name="id_penerimaan" value="<?= htmlspecialchars($id_penerimaan) ?>">
  <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_penerimaan) ?>" 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">Jumlah Pucuk (kg)</label>
    <input type="number" name="jumlah_pucuk" required
           class="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:text-white"
           value="<?= htmlspecialchars($row['jumlah_pucuk']); ?>">
  </div>

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

  <div class="mb-4">
    <label class="block text-gray-700 dark:text-gray-300">Kontaminasi</label>
    <select name="kontaminasi" required
        class="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:text-white">
  <option value="Tidak" <?= $row['kontaminasi'] === 'Tidak' ? 'selected' : '' ?>>Tidak</option>
  <option value="Ya" <?= $row['kontaminasi'] === 'Ya' ? 'selected' : '' ?>>Ya</option>
</select>
  </div>

  <div class="mb-4">
    <label class="block text-gray-700 dark:text-gray-300">Standar Pucuk</label>
    <input type="text" name="standar_pucuk" disabled
           class="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:text-white"
           value="<?= htmlspecialchars($row['standar_pucuk']); ?>">
    <p class="text-sm text-gray-500 dark:text-gray-400 mt-1 italic">Otomatis berdasarkan MC ≥ 60 dan tidak terkontaminasi.</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 updateStandarPucuk() {
  const mc = parseFloat(document.getElementById('mc_basah').value);
  const kontaminasi = document.querySelector('input[name="kontaminasi"]:checked')?.value;
  const standarPucuk = document.getElementById('standar_pucuk');

  if (!isNaN(mc) && kontaminasi) {
    if (mc >= 60 && kontaminasi === 'Tidak') {
      standarPucuk.checked = true;
    } else {
      standarPucuk.checked = false;
    }
  }
  return true; // biar tetap submit
}
</script>
</tbody>
      </table>
    </div>
  </div>
</div>
</body>
</html>