<?php
session_start();
include 'koneksi.php';

$id_user = $_SESSION['id_user'] ?? 1;
$id_produksi = null;
$tanggal_mulai = '-';

// Ambil id_produksi dari URL atau fallback ke produksi terakhir
if (isset($_GET['id_produksi']) && is_numeric($_GET['id_produksi'])) {
    $id_produksi = intval($_GET['id_produksi']);
} else {
    $query_last = "
        SELECT pm.id_produksi, pm.tanggal_mulai
        FROM produksi_master pm
        JOIN pengeringan pl ON pm.id_produksi = pl.id_produksi
        ORDER BY pm.id_produksi DESC
        LIMIT 1
    ";
    $result_last = mysqli_query($conn, $query_last);
    if ($row_last = mysqli_fetch_assoc($result_last)) {
        $id_produksi = $row_last['id_produksi'];
        $tanggal_mulai = $row_last['tanggal_mulai'];
    } else {
        echo "<script>alert('Tidak ada data produksi tersedia.'); window.location.href='index.php';</script>";
        exit;
    }
}

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

// Ambil kode_sortasi pertama sebagai default tampilan (untuk ditampilkan saja, bukan untuk disubmit)
$query_kode = mysqli_query($conn, "
    SELECT kode_pengepakan FROM pengepakan 
    WHERE id_produksi = $id_produksi 
    ORDER BY id_pengepakan ASC LIMIT 1
");
$kode_pengepakan = ($row_kode = mysqli_fetch_assoc($query_kode)) ? $row_kode['kode_pengepakan'] : '-';

// Ambil total berat teh bagus untuk produksi ini
$query_total = mysqli_query($conn, "
    SELECT SUM(berat_sortasi) AS total_bagus 
    FROM sortasi 
    WHERE id_produksi = $id_produksi
");
$row_total = mysqli_fetch_assoc($query_total);
$berat_sortasi = floatval($row_total['total_bagus'] ?? 0);

// Ambil mutu terakhir untuk ditampilkan
$query_mutu = mysqli_query($conn, "
    SELECT jt.mutu
    FROM sortasi s
    JOIN jenis_teh jt ON s.id_teh = jt.id_teh
    WHERE s.id_produksi = $id_produksi AND s.berat_sortasi > 0
    ORDER BY s.id_sortasi DESC
    LIMIT 1
");
$row_mutu = mysqli_fetch_assoc($query_mutu);
$mutu = $row_mutu['mutu'] ?? '-';

// Tidak perlu ambil `id_sortasi` atau pengepakan tertentu di sini,
// karena akan dipilih langsung oleh user di form dropdown.
?>



<!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>Pengepakan</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>
    <!-- You need focus-trap.js to make the modal accessible -->
    <script src="./assets/js/focus-trap.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 grid px-6 mx-auto">
            <h2
              class="my-6 text-2xl font-semibold text-gray-700 dark:text-gray-200"
            >
              Data Pengepakan
            </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"
       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 Pengepakan
  </h2>

 <form action="tambah_pengepakan.php" method="POST" class="space-y-4">
  <input type="hidden" name="id_produksi" value="<?= $id_produksi ?>">
  <input type="hidden" name="id_user" value="<?= $id_user ?>">

  <!-- Info Kode & Tanggal -->
  <div class="grid grid-cols-2 gap-4">
    <div>
      <label class="block text-gray-700 font-semibold">Kode Pengepakan</label>
      <input type="text" value="<?= $kode_pengepakan ?>" readonly
             class="w-full px-3 py-2 border rounded bg-gray-200 dark:bg-gray-700 dark:text-white">
    </div>
    <div>
      <label class="block text-gray-700 font-semibold">Tanggal Mulai Produksi</label>
      <input type="date" value="<?= $tanggal_mulai ?>" readonly
             class="w-full px-3 py-2 border rounded bg-gray-200 dark:bg-gray-700 dark:text-white">
    </div>
  </div>

  <!-- Dropdown Pilih Sortasi (satu baris unik) -->
  <div>
    <label class="block font-semibold text-gray-700">Pilih Data Sortasi</label>
   <select name="id_sortasi" class="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:text-white" required>
  <option value="">-- Pilih Berat - Kelas Mutu - Mutu - Grade --</option>
  <?php
  $query_dropdown = mysqli_query($conn, "
  SELECT s.id_sortasi, s.berat_sortasi, s.berat_rusak, s.kondisi, jt.kelas_mutu, jt.mutu, jt.grade
  FROM sortasi s
  JOIN jenis_teh jt ON jt.id_teh = s.id_teh
  WHERE s.id_produksi = $id_produksi
    AND s.berat_sortasi > 0
    AND s.id_sortasi NOT IN (SELECT id_sortasi FROM pengepakan)
");

  while ($row = mysqli_fetch_assoc($query_dropdown)) {
    $label = "{$row['berat_sortasi']}Kg - {$row['kelas_mutu']} -{$row['mutu']} - {$row['grade']}";
    echo "<option value=\"{$row['id_sortasi']}\">$label</option>";
  }
  ?>
</select>

  </div>

  <!-- Jenis Kemasan -->
  <div>
    <label class="block font-semibold text-gray-700">Jenis Kemasan</label>
    <select name="jenis_kemasan" required class="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:text-white">
      <option value="">-- Pilih Jenis Kemasan --</option>
      <option value="Paper Sak">Paper Sak</option>
      <option value="Karung Plastik">Karung Plastik</option>
      <option value="Carton Box">Carton Box</option>
    </select>
  </div>

  <!-- Jumlah Kemasan -->
  <div>
    <label class="block font-semibold text-gray-700">Jumlah Kemasan</label>
    <input type="number" name="jumlah_kemasan" required
           class="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:text-white">
  </div>

  <!-- Keterangan -->
  <div>
    <label class="block font-semibold text-gray-700">Keterangan (opsional)</label>
    <textarea name="keterangan" rows="2"
              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="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700">
      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';

$query = mysqli_query($conn, "
SELECT pk.*, 
       pm.kode_produksi, 
       pm.tanggal_mulai, 
       pm.tanggal_selesai,   -- ✅ tambahkan ini
       pm.status,            -- ✅ tambahkan ini juga jika perlu
       st.berat_sortasi, 
       st.berat_rusak, 
       st.kondisi,
       jt.kelas_mutu, 
       jt.mutu, 
       jt.grade
FROM pengepakan pk
JOIN sortasi st ON st.id_sortasi = pk.id_sortasi
JOIN jenis_teh jt ON st.id_teh = jt.id_teh
JOIN produksi_master pm ON pk.id_produksi = pm.id_produksi
WHERE (st.berat_sortasi > 0 OR st.berat_rusak > 0)
ORDER BY pm.id_produksi DESC, pk.id_pengepakan ASC

");

$no = 1;
$currentProduksi = null;
$totalsPerGrade = [];
$jumlahKemasanPerGrade = [];
$beratPerGradeMutu = [];
$totalBeratPerProduksi = 0;


while($row = mysqli_fetch_assoc($query)) {
    if ($currentProduksi !== $row['id_produksi']) {
        $no = 1;

        // Jika bukan produksi pertama, tampilkan total sebelumnya
       if (!empty($jumlahKemasanPerGrade)) {
  echo '<tr class="bg-gray-100 dark:bg-gray-900 text-sm font-semibold text-gray-800 dark:text-white">';
  echo '<td colspan="10">';
  echo '<div class="px-4 py-2">Total Kemasan per Grade & Persentase:</div>';

  $totalSemuaKemasan = array_sum($jumlahKemasanPerGrade);

  foreach ($jumlahKemasanPerGrade as $grade => $jumlah) {
      $persentase = $totalSemuaKemasan > 0 ? round(($jumlah / $totalSemuaKemasan) * 100, 2) : 0;
      echo "<div class='px-4'>Grade " . htmlspecialchars($grade) . ": $jumlah Pack ($persentase%)</div>";
  }

  echo '</td></tr>';
        }

        $currentProduksi = $row['id_produksi'];
        echo '<tr class="bg-gray-200 text-gray-900 dark:text-white font-bold">';
       echo '<td colspan="10" class="px-4 py-2">
  <div style="display: flex; justify-content: space-between; align-items: center;">
    <span class="font-bold text-gray-800">
      Produksi: ' . htmlspecialchars($row['kode_pengepakan']) . ' | Tanggal: ' . htmlspecialchars($row['tanggal_mulai']) . '
    </span>';

if (!empty($row['tanggal_selesai'])) {
  echo '<span class="text-green-600 font-semibold">✅ Produksi Selesai pada ' . htmlspecialchars($row['tanggal_selesai']) . '</span>';
} else {
  echo '<button 
    class="bg-green-500 hover:bg-green-600 text-gray font-semibold text-sm px-3 py-1 rounded"
    onclick="selesaikanProduksi(' . $row['id_produksi'] . ', this)">
    ✅ Tandai Produksi Selesai
  </button>';
}

echo '</div></td>';


        echo '</tr>';

        echo '<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">';
        echo '<th class="px-4 py-3">No</th>';
        echo '<th class="px-4 py-3">Kode Pengepakan</th>';
        echo '<th class="px-4 py-3">Tanggal Produksi</th>';
        echo '<th class="px-4 py-3">Berat Hasil Sortasi</th>';
        echo '<th class="px-4 py-3">Mutu</th>';
        echo '<th class="px-4 py-3">Grade</th>';
        echo '<th class="px-4 py-3">Kondisi</th>';
        echo '<th class="px-4 py-3">Jenis Kemasan</th>';
        echo '<th class="px-4 py-3">Jumlah Kemasan</th>';
        echo '<th class="px-4 py-3">Keterangan</th>';
        echo '<th class="px-4 py-3">Aksi</th>';
        echo '</tr>';
    }

    // Hitung jumlah kemasan per grade
    $grade = $row['grade'];
    $jumlah = (int)$row['jumlah_kemasan'];
    if (!isset($jumlahKemasanPerGrade[$grade])) {
        $jumlahKemasanPerGrade[$grade] = 0;
    }
    $jumlahKemasanPerGrade[$grade] += $jumlah;
?>

<tr x-data="{ editOpen: false }" class="text-gray-700 dark:text-gray-400">
  <td class="px-4 py-3"><?php echo $no++; ?></td>
  <td class="px-4 py-3"><?php echo htmlspecialchars($row['kode_pengepakan']); ?></td>
  <td class="px-4 py-3"><?php echo htmlspecialchars($row['tanggal_mulai']); ?></td>
  <td class="px-4 py-3"><?php echo htmlspecialchars($row['berat_sortasi']); ?>Kg</td>
  <td class="px-4 py-3">
    <?php echo htmlspecialchars($row['kelas_mutu'] . ' - ' . $row['mutu']); ?>
</td>

  <td class="px-4 py-3">Grade <?php echo htmlspecialchars($row['grade']); ?></td>
  <td class="px-4 py-3"><?php echo htmlspecialchars($row['kondisi']); ?></td>
  <td class="px-4 py-3"><?php echo htmlspecialchars($row['jenis_kemasan']); ?></td>
  <td class="px-4 py-3"><?php echo htmlspecialchars($row['jumlah_kemasan']); ?></td>
  <td class="px-4 py-3"><?php echo htmlspecialchars($row['keterangan']); ?></td>
  <td class="px-4 py-3">
    <div class="flex space-x-2">
      <a href="update_pengepakan.php?id_pengepakan=<?= $row['id_pengepakan']; ?>"
         @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_pengepakan.php?id_pengepakan=<?= $row['id_pengepakan']; ?>"
         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 Pengepakan
        </h2>

        <form action="update_pengepakan.php" method="POST">
  <input type="hidden" name="id_pengepakan" value="<?= $row['id_pengepakan']; ?>">

    <div class="mb-4">
    <label class="block text-gray-700 dark:text-gray-300">Kode Produksi</label>
    <input type="text" name="kode_pengepakan" readonly
           class="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:text-white"
           value="<?= htmlspecialchars($row['kode_pengepakan']); ?>">
  </div>
  <div class="mb-4">
    <label class="block text-gray-700 dark:text-gray-300">Tanggal</label>
    <input type="date" name="tanggal_mulai" readonly
           class="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:text-white"
           value="<?= htmlspecialchars($row['tanggal_mulai']); ?>">
  </div>

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

  <div class="mb-4">
    <label class="block text-gray-700 dark:text-gray-300">Jenis Kemasan</label>
    <input type="text" name="jenis_kemasan" maxlength="50"
           class="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:text-white"
           value="<?= htmlspecialchars($row['jenis_kemasan']); ?>">
  </div>

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

  <div class="mb-4">
    <label class="block text-gray-700 dark:text-gray-300">Keterangan</label>
    <textarea name="keterangan"
              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
} // END WHILE

// Tampilkan total terakhir
if (!empty($jumlahKemasanPerGrade)) {
  echo '<tr class="bg-gray-100 dark:bg-gray-900 text-sm font-semibold text-gray-800 dark:text-white">';
  echo '<td colspan="10">';
  echo '<div class="px-4 py-2">Total Kemasan per Grade & Persentase:</div>';

  $totalSemuaKemasan = array_sum($jumlahKemasanPerGrade);

  foreach ($jumlahKemasanPerGrade as $grade => $jumlah) {
      $persentase = $totalSemuaKemasan > 0 ? round(($jumlah / $totalSemuaKemasan) * 100, 2) : 0;
      echo "<div class='px-4'>Grade " . htmlspecialchars($grade) . ": $jumlah Pack ($persentase%)</div>";
  }

  echo '</td></tr>';
}

?>

<script>
function selesaikanProduksi(id_produksi, button) {
  if (!confirm("Apakah Anda yakin ingin menyelesaikan produksi ini?")) return;

  fetch("update_selesai.php", {
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded"
    },
    body: "id_produksi=" + encodeURIComponent(id_produksi)
  })
  .then(response => response.text())
  .then(data => {
    if (data === "ok") {
      button.outerHTML = '<span class="text-green-600 font-semibold">Produksi Selesai ✅</span>';
    } else {
      alert("Gagal menyelesaikan produksi.");
    }
  })
  .catch(error => {
    alert("Terjadi kesalahan: " + error);
  });
}
</script>

  </body>
</html>
