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

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

// Endpoint suggestion (typeahead) sederhana untuk stok
if (isset($_GET['suggest']) && intval($_GET['suggest']) === 1) {
    header('Content-Type: application/json');
    $q = isset($_GET['q']) ? trim($_GET['q']) : '';
    $suggestions = [];
    if ($q !== '') {
        $safe = '%' . $conn->real_escape_string($q) . '%';
        $sql = "
            SELECT DISTINCT CONCAT(kode_pengepakan, ' | ', kelas_mutu, ' ', mutu, ' (', grade, ')') AS label
            FROM stok_gudang
            WHERE kode_pengepakan LIKE '$safe'
               OR kelas_mutu LIKE '$safe'
               OR mutu LIKE '$safe'
               OR grade LIKE '$safe'
               OR jenis_kemasan LIKE '$safe'
            ORDER BY tanggal_masuk DESC
            LIMIT 10
        ";
        $res = $conn->query($sql);
        while ($row = $res && $row = $res->fetch_assoc()) {
            if (!empty($row['label'])) { $suggestions[] = $row['label']; }
        }
    }
    echo json_encode($suggestions);
    exit;
}

// 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(
				"issssdsid",
				$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']);
}

// Filters & pagination
$q = isset($_GET['q']) ? trim($_GET['q']) : '';
$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : '';
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : '';
$page = max(1, intval($_GET['page'] ?? 1));
$per_page = max(5, intval($_GET['per_page'] ?? 10));
$offset = ($page - 1) * $per_page;

$whereParts = [];
if ($q !== '') {
    $safeQ = '%' . $conn->real_escape_string($q) . '%';
    $whereParts[] = "(
        LOWER(sg.kode_pengepakan) LIKE LOWER('$safeQ') OR 
        LOWER(sg.kelas_mutu) LIKE LOWER('$safeQ') OR 
        LOWER(sg.mutu) LIKE LOWER('$safeQ') OR 
        LOWER(sg.grade) LIKE LOWER('$safeQ') OR 
        LOWER(sg.jenis_kemasan) LIKE LOWER('$safeQ')
    )";
}
if ($start_date !== '' && $end_date !== '') {
    $startEsc = $conn->real_escape_string($start_date);
    $endEsc = $conn->real_escape_string($end_date);
    $whereParts[] = "(DATE(sg.tanggal_masuk) BETWEEN '$startEsc' AND '$endEsc')";
} elseif ($start_date !== '') {
    $startEsc = $conn->real_escape_string($start_date);
    $whereParts[] = "(DATE(sg.tanggal_masuk) >= '$startEsc')";
} elseif ($end_date !== '') {
    $endEsc = $conn->real_escape_string($end_date);
    $whereParts[] = "(DATE(sg.tanggal_masuk) <= '$endEsc')";
}
$whereSql = count($whereParts) ? ('WHERE ' . implode(' AND ', $whereParts)) : '';

// Count for pagination
$count_sql = "SELECT COUNT(*) AS cnt FROM stok_gudang sg $whereSql";
$count_res = $conn->query($count_sql);
$total_rows = $count_res ? intval(($count_res->fetch_assoc()['cnt'] ?? 0)) : 0;
$total_pages = max(1, (int)ceil($total_rows / $per_page));

// Ambil data stok gudang dengan filter & pagination
$stok_query = "
\tSELECT sg.*, p.tanggal_input as tanggal_pengepakan
\tFROM stok_gudang sg
\tLEFT JOIN pengepakan p ON sg.id_pengepakan = p.id_pengepakan
\t$whereSql
\tORDER BY sg.kode_pengepakan ASC, sg.tanggal_masuk DESC
\tLIMIT $per_page OFFSET $offset
";
$stok_result = $conn->query($stok_query);

// Hitung total stok tersedia (kg) dari berat_paket
$total_stok_query = "SELECT SUM(berat_paket) 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 (kg) dari tabel penjualan
$total_terjual_query = "SELECT SUM(quantity_kg) as total FROM penjualan";
$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';
      ?>

<?php include 'header.php'; ?>

        <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 ? $stok_result->num_rows : 0 ?>
                    </p>
                  </div>
                </div>
              </div>
            </div>

            <!-- Filter -->
            <div class="mb-6 grid gap-6 md:grid-cols-2 md:gap-8">
              <!-- Search only -->
              <form method="GET" action="stok_gudang.php" class="flex items-center gap-4 p-4 bg-white dark:bg-gray-800 rounded-md shadow" onsubmit="this.querySelector('[name=page]').value=1;">
                <input type="hidden" name="page" value="<?= (int)$page ?>" />
                <input type="text" name="q" value="<?= htmlspecialchars($q) ?>" placeholder="Cari kode/mutu/grade/kemasan..."
                       class="flex-1 min-w-[220px] px-3 py-2 text-sm border border-gray-300 rounded-md dark:bg-gray-700 dark:border-gray-600 dark:text-gray-200" />
                <button type="submit" class="px-3 py-2 text-sm text-white bg-blue-600 rounded-md">Cari</button>
              </form>

              <!-- Date filter only -->
              <form method="GET" action="stok_gudang.php" class="flex items-center gap-4 p-4 bg-white dark:bg-gray-800 rounded-md shadow">
                <input type="date" name="start_date" value="<?= htmlspecialchars($start_date) ?>"
                       class="px-3 py-2 text-sm border border-gray-300 rounded-md dark:bg-gray-700 dark:border-gray-600 dark:text-gray-200" />
                <span class="text-sm text-gray-500 dark:text-gray-400">s/d</span>
                <input type="date" name="end_date" value="<?= htmlspecialchars($end_date) ?>"
                       class="px-3 py-2 text-sm border border-gray-300 rounded-md dark:bg-gray-700 dark:border-gray-600 dark:text-gray-200" />
                <button type="submit" class="ml-auto px-3 py-2 text-sm text-white bg-purple-600 rounded-md">Filter Tanggal</button>
                <a href="stok_gudang.php" class="px-3 py-2 text-sm bg-gray-100 rounded-md dark:bg-gray-700 dark:text-gray-200">Reset</a>
              </form>
            </div>

            <!-- Table detail stok -->
            <div class="w-full overflow-hidden rounded-lg shadow-xs">
              <div class="w-full overflow-x-auto">
                <table class="w-full whitespace-no-wrap">
                  <tbody class="bg-white divide-y dark:divide-gray-700 dark:bg-gray-800">
                    <?php if ($stok_result && $stok_result->num_rows > 0): ?>
                      <?php 
                        $currentKode = null; 
                        $no = 1;
                        while ($row = $stok_result->fetch_assoc()): 
                          if ($currentKode !== $row['kode_pengepakan']) {
                            $currentKode = $row['kode_pengepakan'];
                      ?>
                        <tr class="bg-gray-100 dark:bg-gray-900">
                          <td colspan="11" class="px-4 py-2 text-sm font-semibold text-gray-800 dark:text-gray-200">
                            Kode: <?= htmlspecialchars($currentKode) ?> | Tanggal: <?= isset($row['tanggal_pengepakan']) ? date('d/m/Y', strtotime($row['tanggal_pengepakan'])) : '-' ?>
                          </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</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 Kemasan</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>
                      <?php } ?>
                        <tr class="text-gray-700 dark:text-gray-300">
                          <td class="px-4 py-3 text-sm"><?php echo $no++; ?></td>
                          <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((float)($row['berat_paket'] ?? 0), 2) ?> kg</td>
                          <td class="px-4 py-3 text-sm"><?= htmlspecialchars($row['jenis_kemasan'] ?? '') ?></td>
                          <td class="px-4 py-3 text-sm"><?= (int)($row['jumlah_kemasan'] ?? 0) ?></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"><?= isset($row['tanggal_masuk']) ? 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=<?= (int)$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; ?>
                    <?php else: ?>
                      <tr>
                        <td colspan="11" class="px-4 py-6 text-center text-sm text-gray-500 dark:text-gray-400">Belum ada data stok gudang.</td>
                      </tr>
                    <?php endif; ?>
                  </tbody>
                </table>
              </div>
            </div>

            <!-- Pagination -->
            <div class="flex items-center justify-between mt-4">
              <div class="text-sm text-gray-600 dark:text-gray-400">Halaman <?= $page ?> dari <?= $total_pages ?> (<?= $total_rows ?> data)</div>
              <div class="flex gap-2">
                <?php if ($page > 1): ?>
                  <a class="px-3 py-1 rounded bg-gray-200 dark:bg-gray-700 dark:text-gray-200" href="?<?= http_build_query(array_merge($_GET, ['page' => $page-1])) ?>">Prev</a>
                <?php endif; ?>
                <?php if ($page < $total_pages): ?>
                  <a class="px-3 py-1 rounded bg-gray-200 dark:bg-gray-700 dark:text-gray-200" href="?<?= http_build_query(array_merge($_GET, ['page' => $page+1])) ?>">Next</a>
                <?php endif; ?>
              </div>
            </div>
          </div>
        </main>
      </div>
    </div>
  <script>
    (function(){
      const input = document.getElementById('sgSearch');
      const box = document.getElementById('sgSuggest');
      if (!input || !box) return;
      let t;
      function hide(){ box.classList.add('hidden'); }
      function show(){ box.classList.remove('hidden'); }
      function render(items){
        if (!items || !items.length){ hide(); box.innerHTML=''; return; }
        box.innerHTML = items.map(it=>`<div class=\"px-3 py-2 text-sm cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-600\">${it}</div>`).join('');
        Array.from(box.children).forEach(el=>{
          el.addEventListener('click', ()=>{ input.value = el.textContent; input.form.submit(); });
        });
        show();
      }
      input.addEventListener('input', ()=>{
        clearTimeout(t);
        const q = input.value.trim();
        if (!q){ hide(); return; }
        t = setTimeout(()=>{
          fetch(`stok_gudang.php?suggest=1&q=${encodeURIComponent(q)}`)
            .then(r=>r.json())
            .then(render)
            .catch(()=>hide());
        }, 200);
      });
      document.addEventListener('click', (e)=>{ if (!box.contains(e.target) && e.target!==input) hide(); });
    })();
  </script>
  </body>
</html>
