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

$id_user = $_SESSION['id_user'] ?? 1;

// Fungsi untuk menambahkan data ke stok gudang jika belum ada
function addToStokGudang($conn, $id_pengepakan) {
    // Cek apakah sudah ada di stok gudang
    $check_query = "SELECT id_stok FROM stok_gudang WHERE id_pengepakan = ?";
    $check_stmt = $conn->prepare($check_query);
    $check_stmt->bind_param("i", $id_pengepakan);
    $check_stmt->execute();
    $check_result = $check_stmt->get_result();
    
    if ($check_result->num_rows == 0) {
        // Ambil data pengepakan
        $pengepakan_query = "SELECT * FROM pengepakan WHERE id_pengepakan = ? AND status = 'Selesai'";
        $pengepakan_stmt = $conn->prepare($pengepakan_query);
        $pengepakan_stmt->bind_param("i", $id_pengepakan);
        $pengepakan_stmt->execute();
        $pengepakan_result = $pengepakan_stmt->get_result();
        
        if ($pengepakan_result->num_rows > 0) {
            $pengepakan_data = $pengepakan_result->fetch_assoc();
            
            // Hitung total berat
            $total_berat = $pengepakan_data['berat_paket'] * $pengepakan_data['jumlah_kemasan'];
            
            // Insert ke stok gudang
            $insert_query = "INSERT INTO stok_gudang (id_pengepakan, kode_pengepakan, kelas_mutu, mutu, grade, berat_paket, jenis_kemasan, jumlah_kemasan, total_berat, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'Tersedia')";
            $insert_stmt = $conn->prepare($insert_query);
            $insert_stmt->bind_param("issssd sid",
                $pengepakan_data['id_pengepakan'],
                $pengepakan_data['kode_pengepakan'],
                $pengepakan_data['kelas_mutu'],
                $pengepakan_data['mutu'],
                $pengepakan_data['grade'],
                $pengepakan_data['berat_paket'],
                $pengepakan_data['jenis_kemasan'],
                $pengepakan_data['jumlah_kemasan'],
                $total_berat
            );
            $insert_stmt->execute();
        }
    }
}

// Proses semua data pengepakan yang selesai
$pengepakan_selesai_query = "SELECT id_pengepakan FROM pengepakan WHERE status = 'Selesai'";
$pengepakan_selesai_result = $conn->query($pengepakan_selesai_query);

while ($row = $pengepakan_selesai_result->fetch_assoc()) {
    addToStokGudang($conn, $row['id_pengepakan']);
}

// Ambil data stok gudang
$stok_query = "
    SELECT sg.*, p.tanggal_input as tanggal_pengepakan
    FROM stok_gudang sg
    LEFT JOIN pengepakan p ON sg.id_pengepakan = p.id_pengepakan
    ORDER BY sg.tanggal_masuk DESC
";
$stok_result = $conn->query($stok_query);

// Hitung total stok
$total_stok_query = "SELECT SUM(total_berat) as total FROM stok_gudang WHERE status = 'Tersedia'";
$total_stok_result = $conn->query($total_stok_query);
$total_stok = $total_stok_result->fetch_assoc()['total'] ?? 0;

// Hitung total terjual
$total_terjual_query = "SELECT SUM(total_berat) as total FROM stok_gudang WHERE status = 'Terjual'";
$total_terjual_result = $conn->query($total_terjual_query);
$total_terjual = $total_terjual_result->fetch_assoc()['total'] ?? 0;
?>

<!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>Stok Gudang</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="./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';
      ?>

      <div class="flex flex-col flex-1 w-full">
        <header class="z-10 py-4 bg-white shadow-md dark:bg-gray-800">
          <div
            class="container flex items-center justify-between h-full px-6 mx-auto text-purple-600 dark:text-purple-300"
          >
            <!-- Mobile hamburger -->
            <button
              class="p-1 mr-5 -ml-1 rounded-md md:hidden focus:outline-none focus:shadow-outline-purple"
              @click="toggleSideMenu"
              aria-label="Menu"
            >
              <svg
                class="w-6 h-6"
                aria-hidden="true"
                fill="currentColor"
                viewBox="0 0 20 20"
              >
                <path
                  fill-rule="evenodd"
                  d="M3 5a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 10a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 15a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1z"
                  clip-rule="evenodd"
                ></path>
              </svg>
            </button>
            <!-- Search input -->
            <div class="flex justify-center flex-1 lg:mr-32">
              <div
                class="relative w-full max-w-xl mr-6 focus-within:text-purple-500"
              >
                <div class="absolute inset-y-0 flex items-center pl-2">
                  <svg
                    class="w-4 h-4"
                    aria-hidden="true"
                    fill="currentColor"
                    viewBox="0 0 20 20"
                  >
                    <path
                      fill-rule="evenodd"
                      d="M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z"
                      clip-rule="evenodd"
                    ></path>
                  </svg>
                </div>
                <input
                  class="w-full pl-8 pr-2 text-sm text-gray-700 placeholder-gray-600 bg-gray-100 border-0 rounded-md dark:placeholder-gray-500 dark:focus:shadow-outline-gray dark:focus:placeholder-gray-600 dark:bg-gray-700 dark:text-gray-200 focus:placeholder-gray-500 focus:bg-white focus:border-purple-300 focus:outline-none focus:shadow-outline-purple form-input"
                  type="text"
                  placeholder="Search..."
                  aria-label="Search"
                />
              </div>
            </div>
            <ul class="flex items-center flex-shrink-0 space-x-6">
              <!-- Theme toggler -->
              <li class="flex">
                <button
                  class="rounded-md focus:outline-none focus:shadow-outline-purple"
                  @click="toggleTheme"
                  aria-label="Toggle color mode"
                >
                  <template x-if="!dark">
                    <svg
                      class="w-5 h-5"
                      aria-hidden="true"
                      fill="currentColor"
                      viewBox="0 0 20 20"
                    >
                      <path
                        d="M17.293 13.293A8 8 0 016.707 2.707a8.001 8.001 0 1010.586 10.586z"
                      ></path>
                    </svg>
                  </template>
                  <template x-if="dark">
                    <svg
                      class="w-5 h-5"
                      aria-hidden="true"
                      fill="currentColor"
                      viewBox="0 0 20 20"
                    >
                      <path
                        fill-rule="evenodd"
                        d="M10 2a1 1 0 011 1v1a1 1 0 11-2 0V3a1 1 0 011-1zm4 8a4 4 0 11-8 0 4 4 0 018 0zm-.464 4.95l.707.707a1 1 0 001.414-1.414l-.707-.707a1 1 0 00-1.414 1.414zm2.12-10.607a1 1 0 010 1.414l-.706.707a1 1 0 11-1.414-1.414l.707-.707a1 1 0 011.414 0zM17 11a1 1 0 100-2h-1a1 1 0 100 2h1zm-7 4a1 1 0 011 1v1a1 1 0 11-2 0v-1a1 1 0 011-1zM5.05 6.464A1 1 0 106.465 5.05l-.708-.707a1 1 0 00-1.414 1.414l.707.707zm1.414 8.486l-.707.707a1 1 0 01-1.414-1.414l.707-.707a1 1 0 011.414 1.414zM4 11a1 1 0 100-2H3a1 1 0 000 2h1z"
                        clip-rule="evenodd"
                      ></path>
                    </svg>
                  </template>
                </button>
              </li>
              <!-- Profile menu -->
              <li class="relative">
                <button
                  class="align-middle rounded-full focus:shadow-outline-purple focus:outline-none"
                  @click="toggleProfileMenu"
                  @keydown.escape="closeProfileMenu"
                  aria-label="Account"
                  aria-haspopup="true"
                >
                  <img
                    class="object-cover w-8 h-8 rounded-full"
                    src="https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=100&q=80"
                    alt=""
                    aria-hidden="true"
                  />
                </button>
                <template x-if="isProfileMenuOpen">
                  <ul
                    x-transition:leave="transition ease-in duration-150"
                    x-transition:leave-start="opacity-100"
                    x-transition:leave-end="opacity-0"
                    @click.away="closeProfileMenu"
                    @keydown.escape="closeProfileMenu"
                    class="absolute right-0 w-56 p-2 mt-2 space-y-2 text-gray-600 bg-white border border-gray-100 rounded-md shadow-md dark:border-gray-700 dark:text-gray-300 dark:bg-gray-700"
                    aria-label="submenu"
                  >
                    <li class="flex">
                      <a
                        class="inline-flex items-center w-full px-2 py-1 text-sm font-semibold transition-colors duration-150 rounded-md hover:bg-gray-100 hover:text-gray-800 dark:hover:bg-gray-800 dark:hover:text-gray-200"
                        href="#"
                      >
                        <svg
                          class="w-4 h-4 mr-3"
                          aria-hidden="true"
                          fill="none"
                          stroke-linecap="round"
                          stroke-linejoin="round"
                          stroke-width="2"
                          viewBox="0 0 24 24"
                          stroke="currentColor"
                        >
                          <path
                            d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"
                          ></path>
                        </svg>
                        Profile
                      </a>
                    </li>
                    <li class="flex">
                      <a
                        class="inline-flex items-center w-full px-2 py-1 text-sm font-semibold transition-colors duration-150 rounded-md hover:bg-gray-100 hover:text-gray-800 dark:hover:bg-gray-800 dark:hover:text-gray-200"
                        href="#"
                      >
                        <svg
                          class="w-4 h-4 mr-3"
                          aria-hidden="true"
                          fill="none"
                          stroke-linecap="round"
                          stroke-linejoin="round"
                          stroke-width="2"
                          viewBox="0 0 24 24"
                          stroke="currentColor"
                        >
                          <path
                            d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"
                          ></path>
                          <path d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                        </svg>
                        Settings
                      </a>
                    </li>
                    <li class="flex">
                      <a
                        class="inline-flex items-center w-full px-2 py-1 text-sm font-semibold transition-colors duration-150 rounded-md hover:bg-gray-100 hover:text-gray-800 dark:hover:bg-gray-800 dark:hover:text-gray-200"
                        href="pages/logout.php"
                      >
                        <svg
                          class="w-4 h-4 mr-3"
                          aria-hidden="true"
                          fill="none"
                          stroke-linecap="round"
                          stroke-linejoin="round"
                          stroke-width="2"
                          viewBox="0 0 24 24"
                          stroke="currentColor"
                        >
                          <path
                            d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"
                          ></path>
                        </svg>
                        Log out
                      </a>
                    </li>
                  </ul>
                </template>
              </li>
            </ul>
          </div>
        </header>
        <main class="h-full 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"
            >
              Stok Gudang
            </h2>

            <!-- Cards -->
            <div class="grid gap-6 mb-8 md:grid-cols-2 xl:grid-cols-4">
              <!-- Total Stok -->
              <div class="min-w-0 p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
                <div class="flex items-center">
                  <div class="p-3 mr-4 text-orange-500 bg-orange-100 rounded-full dark:text-orange-100 dark:bg-orange-500">
                    <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                      <path d="M13 6a3 3 0 11-6 0 3 3 0 016 0zM18 8a2 2 0 11-4 0 2 2 0 014 0zM14 15a4 4 0 00-8 0v3h8v-3zM6 8a2 2 0 11-4 0 2 2 0 014 0zM16 18v-3a5.972 5.972 0 00-.75-2.906A3.005 3.005 0 0119 15v3h-3zM4.75 12.094A5.973 5.973 0 004 15v3H1v-3a3 3 0 013.75-2.906z"></path>
                    </svg>
                  </div>
                  <div>
                    <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">
                      Total Stok Tersedia
                    </p>
                    <p class="text-lg font-semibold text-gray-700 dark:text-gray-200">
                      <?= number_format($total_stok, 2) ?> kg
                    </p>
                  </div>
                </div>
              </div>

              <!-- Total Terjual -->
              <div class="min-w-0 p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
                <div class="flex items-center">
                  <div class="p-3 mr-4 text-green-500 bg-green-100 rounded-full dark:text-green-100 dark:bg-green-500">
                    <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                      <path fill-rule="evenodd" d="M4 4a2 2 0 00-2 2v4a2 2 0 002 2V6h10a2 2 0 00-2-2H4zm2 6a2 2 0 012-2h8a2 2 0 012 2v4a2 2 0 01-2 2H8a2 2 0 01-2-2v-4zm6 4a2 2 0 100-4 2 2 0 000 4z" clip-rule="evenodd"></path>
                    </svg>
                  </div>
                  <div>
                    <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">
                      Total Terjual
                    </p>
                    <p class="text-lg font-semibold text-gray-700 dark:text-gray-200">
                      <?= number_format($total_terjual, 2) ?> kg
                    </p>
                  </div>
                </div>
              </div>

              <!-- Jumlah Item -->
              <div class="min-w-0 p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
                <div class="flex items-center">
                  <div class="p-3 mr-4 text-blue-500 bg-blue-100 rounded-full dark:text-blue-100 dark:bg-blue-500">
                    <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                      <path d="M3 4a1 1 0 011-1h12a1 1 0 011 1v2a1 1 0 01-1 1H4a1 1 0 01-1-1V4zM3 10a1 1 0 011-1h6a1 1 0 011 1v6a1 1 0 01-1 1H4a1 1 0 01-1-1v-6zM14 9a1 1 0 00-1 1v6a1 1 0 001 1h2a1 1 0 001-1v-6a1 1 0 00-1-1h-2z"></path>
                    </svg>
                  </div>
                  <div>
                    <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">
                      Jumlah Item
                    </p>
                    <p class="text-lg font-semibold text-gray-700 dark:text-gray-200">
                      <?= $stok_result->num_rows ?>
                    </p>
                  </div>
                </div>
              </div>

              <!-- Status -->
              <div class="min-w-0 p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
                <div class="flex items-center">
                  <div class="p-3 mr-4 text-purple-500 bg-purple-100 rounded-full dark:text-purple-100 dark:bg-purple-500">
                    <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                      <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd"></path>
                    </svg>
                  </div>
                  <div>
                    <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">
                      Status
                    </p>
                    <p class="text-lg font-semibold text-gray-700 dark:text-gray-200">
                      Aktif
                    </p>
                  </div>
                </div>
              </div>
            </div>

            <!-- Table -->
            <div class="w-full overflow-hidden rounded-lg shadow-xs">
              <div class="w-full overflow-x-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">Kode</th>
                      <th class="px-4 py-3">Kelas Mutu</th>
                      <th class="px-4 py-3">Mutu</th>
                      <th class="px-4 py-3">Grade</th>
                      <th class="px-4 py-3">Berat Paket</th>
                      <th class="px-4 py-3">Jenis Kemasan</th>
                      <th class="px-4 py-3">Jumlah</th>
                      <th class="px-4 py-3">Total Berat</th>
                      <th class="px-4 py-3">Status</th>
                      <th class="px-4 py-3">Tanggal Masuk</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 while ($row = $stok_result->fetch_assoc()): ?>
                    <tr class="text-gray-700 dark:text-gray-300">
                      <td class="px-4 py-3 text-sm">
                        <?= htmlspecialchars($row['kode_pengepakan']) ?>
                      </td>
                      <td class="px-4 py-3 text-sm">
                        <?= htmlspecialchars($row['kelas_mutu']) ?>
                      </td>
                      <td class="px-4 py-3 text-sm">
                        <?= htmlspecialchars($row['mutu']) ?>
                      </td>
                      <td class="px-4 py-3 text-sm">
                        <span class="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['grade']) ?>
                        </span>
                      </td>
                      <td class="px-4 py-3 text-sm">
                        <?= number_format($row['berat_paket'], 2) ?> kg
                      </td>
                      <td class="px-4 py-3 text-sm">
                        <?= htmlspecialchars($row['jenis_kemasan']) ?>
                      </td>
                      <td class="px-4 py-3 text-sm">
                        <?= $row['jumlah_kemasan'] ?>
                      </td>
                      <td class="px-4 py-3 text-sm">
                        <strong><?= number_format($row['total_berat'], 2) ?> kg</strong>
                      </td>
                      <td class="px-4 py-3 text-sm">
                        <?php if ($row['status'] == 'Tersedia'): ?>
                          <span class="px-2 py-1 font-semibold leading-tight text-green-700 bg-green-100 rounded-full dark:bg-green-700 dark:text-green-100">
                            Tersedia
                          </span>
                        <?php elseif ($row['status'] == 'Terjual'): ?>
                          <span class="px-2 py-1 font-semibold leading-tight text-red-700 bg-red-100 rounded-full dark:bg-red-700 dark:text-red-100">
                            Terjual
                          </span>
                        <?php else: ?>
                          <span class="px-2 py-1 font-semibold leading-tight text-gray-700 bg-gray-100 rounded-full dark:bg-gray-700 dark:text-gray-100">
                            Habis
                          </span>
                        <?php endif; ?>
                      </td>
                      <td class="px-4 py-3 text-sm">
                        <?= date('d/m/Y H:i', strtotime($row['tanggal_masuk'])) ?>
                      </td>
                      <td class="px-4 py-3 text-sm">
                        <?php if ($row['status'] == 'Tersedia'): ?>
                          <a href="data_penjualan.php?action=jual&id_stok=<?= $row['id_stok'] ?>" 
                             class="px-3 py-1 text-sm font-medium leading-tight text-white bg-purple-600 rounded-full hover:bg-purple-700 focus:outline-none focus:shadow-outline">
                            Jual
                          </a>
                        <?php else: ?>
                          <span class="px-3 py-1 text-sm font-medium leading-tight text-gray-500 bg-gray-200 rounded-full">
                            -
                          </span>
                        <?php endif; ?>
                      </td>
                    </tr>
                    <?php endwhile; ?>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </main>
      </div>
    </div>
  </body>
</html>
