<?php
require 'koneksi.php';
$id_gudang = $_REQUEST['id_gudang'] ?? null;
$id_tahun  = $_REQUEST['tahun'] ?? null;

if (!$id_gudang || !$id_tahun) {
    echo "<script>alert('Pilih gudang dan tahun terlebih dahulu.'); window.location.href='gudang_tahun.php';</script>";
    exit();
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <title>Input Stock Opname</title>
  <script src="https://unpkg.com/@zxing/library@latest"></script>
  <style>
    video {
      border: 1px solid #ccc;
      margin-top: 10px;
    }
  </style>
</head>
<body>

<h2>Input Stock Opname</h2>

<form id="opnameForm">
  <label>Barcode:</label>
  <input type="text" id="barcode_input" name="barcode" required autofocus>
  <button type="button" onclick="cekBarcode()">Cek Barcode</button>

  <!-- Fitur tambahan scan -->
  <div style="margin-top: 10px;">
    <button type="button" onclick="startCameraScan()">📷 Scan Kamera</button>
    <input type="file" accept="image/*" onchange="scanBarcodeFromImage(event)">
  </div>
  <video id="video" width="300" height="200" style="display:none;"></video>

  <div id="barang-info" style="display:none; margin-top:10px;">
    <input type="hidden" name="id_barang" id="id_barang">

    <p>Nama: <span id="nama_barang"></span></p>
    <p>Part Number: <span id="part_number"></span></p>
    <p>Satuan: <span id="satuan"></span></p>

    <label>Kondisi:</label><br>
    <input type="radio" id="bagus" name="kondisi" value="Bagus" required>
    <label for="bagus">Bagus</label><br>

    <input type="radio" id="rusak" name="kondisi" value="Rusak" required>
    <label for="rusak">Rusak</label><br><br>

    <label>Stok:</label>
    <input type="number" id="stok" name="stok" required><br><br>

    <button type="button" onclick="simpanData()">Simpan</button>
  </div>

  <input type="hidden" name="part_number" id="hidden_part_number">
  <input type="hidden" name="satuan" id="hidden_satuan">
  <input type="hidden" name="id_gudang" value="<?= $id_gudang ?>">
  <input type="hidden" name="tahun" value="<?= $id_tahun ?>">
</form>

<script>
function cekBarcode() {
  const barcode = document.getElementById('barcode_input').value.trim();
  if (!barcode) {
    alert("Barcode belum diisi");
    return;
  }

  fetch('/soralika/check_barang.php?barcode=' + encodeURIComponent(barcode))
    .then(res => res.json())
    .then(data => {
      if (data.error) {
        alert(data.error);
        document.getElementById('barang-info').style.display = 'none';
        return;
      }

      document.getElementById('id_barang').value = data.id_barang;
      document.getElementById('nama_barang').innerText = data.nama_barang;
      document.getElementById('part_number').innerText = data.part_number;
      document.getElementById('satuan').innerText = data.satuan;
      document.getElementById('hidden_part_number').value = data.part_number;
      document.getElementById('hidden_satuan').value = data.satuan;
      document.getElementById('barang-info').style.display = 'block';

      const kondisiRadios = document.querySelectorAll('input[name="kondisi"]');
      kondisiRadios.forEach(r => r.checked = false);
      document.getElementById('stok').value = '';
    })
    .catch(err => {
      console.error(err);
      alert("Gagal mengambil data barang.");
    });
}

function simpanData() {
  const kondisiChecked = document.querySelector('input[name="kondisi"]:checked');
  const stok = document.getElementById('stok').value.trim();

  if (!kondisiChecked || !stok) {
    alert("Field belum lengkap!");
    return;
  }

  const formData = new FormData(document.getElementById('opnameForm'));

  fetch('/soralika/proses_opname.php', {
    method: 'POST',
    body: formData
  })
  .then(res => res.json())
  .then(response => {
    if (response.success) {
      window.location.href = response.redirect;
    } else {
      alert(response.message);
    }
  })
  .catch(err => {
    console.error(err);
    alert("Gagal menyimpan data!");
  });
}

// === SCAN KAMERA ===
const codeReader = new ZXing.BrowserMultiFormatReader();

function startCameraScan() {
  const video = document.getElementById('video');
  video.style.display = 'block';

  codeReader
    .listVideoInputDevices()
    .then(videoInputDevices => {
      return codeReader.decodeFromVideoDevice(videoInputDevices[0].deviceId, 'video', (result, err) => {
        if (result) {
          document.getElementById('barcode_input').value = result.text;
          codeReader.reset();
          video.style.display = 'none';
          cekBarcode();
        }
      });
    })
    .catch(err => {
      console.error(err);
      alert('Gagal mengakses kamera.');
    });
}

// === SCAN GAMBAR ===
function scanBarcodeFromImage(event) {
  const file = event.target.files[0];
  if (!file) return;

  const reader = new FileReader();
  reader.onload = () => {
    const img = new Image();
    img.src = reader.result;

    img.onload = () => {
      codeReader.decodeFromImage(img)
        .then(result => {
          document.getElementById('barcode_input').value = result.text;
          cekBarcode();
        })
        .catch(err => {
          console.error(err);
          alert('Gagal membaca barcode dari gambar.');
        });
    };
  };
  reader.readAsDataURL(file);
}
</script>

</body>
</html>
