<!--
=========================================================
* Paper Dashboard 2 - v2.0.1
=========================================================

* Product Page: https://www.creative-tim.com/product/paper-dashboard-2
* Copyright 2020 Creative Tim (https://www.creative-tim.com)

Coded by www.creative-tim.com

 =========================================================

* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
-->
<?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="en">

<head>
  <meta charset="utf-8" />
  <link rel="apple-touch-icon" sizes="76x76" href="../assets/img/apple-icon.png">
  <link rel="icon" type="image/png" href="../assets/img/favicon.png">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
  <title>
    STOCK OPNAME RALIKA (beta)
  </title>
  <script src="https://unpkg.com/@zxing/library@latest"></script>
  <style>
    video {
      border: 1px solid #ccc;
      margin-top: 10px;
    }
  </style>
  <meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0, shrink-to-fit=no' name='viewport' />
  <!--     Fonts and icons     -->
  <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700,200" rel="stylesheet" />
  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css" rel="stylesheet">
  <!-- CSS Files -->
  <link href="../assets/css/bootstrap.min.css" rel="stylesheet" />
  <link href="../assets/css/paper-dashboard.css?v=2.0.1" rel="stylesheet" />
  <!-- CSS Just for demo purpose, don't include it in your project -->
  <link href="../assets/demo/demo.css" rel="stylesheet" />
</head>

<body class="">
  <div class="wrapper ">
    <div class="sidebar" data-color="white" data-active-color="danger">
      <div class="logo">
        <a href="https://www.creative-tim.com" class="simple-text logo-mini">
          <div class="logo-image-small">
            <img src="../assets/img/logo-small.png">
          </div>
          <!-- <p>CT</p> -->
        </a>
        <a href="https://www.creative-tim.com" class="simple-text logo-normal">
          Creative Tim
          <!-- <div class="logo-image-big">
            <img src="../assets/img/logo-big.png">
          </div> -->
        </a>
      </div>
      <div class="sidebar-wrapper">
        <ul class="nav">
          <li class="active ">
            <a href="./dashboard.php">
              <i class="nc-icon nc-bank"></i>
              <p>Dashboard</p>
            </a>
          </li>
          <li>
            <a href="./gudang_tahun.php">
              <i class="nc-icon nc-diamond"></i>
              <p>Tambah Data</p>
            </a>
          </li>
          <li>
            <a href="./map.html">
              <i class="nc-icon nc-pin-3"></i>
              <p>Maps</p>
            </a>
          </li>
          <li>
            <a href="./notifications.html">
              <i class="nc-icon nc-bell-55"></i>
              <p>Notifications</p>
            </a>
          </li>
          <li>
            <a href="./user.html">
              <i class="nc-icon nc-single-02"></i>
              <p>User Profile</p>
            </a>
          </li>
          <li>
            <a href="./tables.html">
              <i class="nc-icon nc-tile-56"></i>
              <p>Table List</p>
            </a>
          </li>
          <li>
            <a href="./typography.html">
              <i class="nc-icon nc-caps-small"></i>
              <p>Typography</p>
            </a>
          </li>
          <li class="active-pro">
            <a href="./upgrade.html">
              <i class="nc-icon nc-spaceship"></i>
              <p>Upgrade to PRO</p>
            </a>
          </li>
        </ul>
      </div>
    </div>
    <div class="main-panel">
      <!-- Navbar -->
      <nav class="navbar navbar-expand-lg navbar-absolute fixed-top navbar-transparent">
        <div class="container-fluid">
          <div class="navbar-wrapper">
            <div class="navbar-toggle">
              <button type="button" class="navbar-toggler">
                <span class="navbar-toggler-bar bar1"></span>
                <span class="navbar-toggler-bar bar2"></span>
                <span class="navbar-toggler-bar bar3"></span>
              </button>
            </div>
            <a class="navbar-brand" href="javascript:;">Stock Opname Ralika</a>
          </div>
          <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navigation" aria-controls="navigation-index" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-bar navbar-kebab"></span>
            <span class="navbar-toggler-bar navbar-kebab"></span>
            <span class="navbar-toggler-bar navbar-kebab"></span>
          </button>
          <div class="collapse navbar-collapse justify-content-end" id="navigation">
            <form>
              <div class="input-group no-border">
                <input type="text" value="" class="form-control" placeholder="Search...">
                <div class="input-group-append">
                  <div class="input-group-text">
                    <i class="nc-icon nc-zoom-split"></i>
                  </div>
                </div>
              </div>
            </form>
            <ul class="navbar-nav">
              <li class="nav-item btn-rotate dropdown">
                <a class="nav-link dropdown-toggle" href="http://example.com" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                  <i class="nc-icon nc-bell-55"></i>
                  <p>
                    <span class="d-lg-none d-md-block">Some Actions</span>
                  </p>
                </a>
                <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdownMenuLink">
                  <a class="dropdown-item" href="#">Action</a>
                  <a class="dropdown-item" href="#">Another action</a>
                  <a class="dropdown-item" href="#">Something else here</a>
                </div>
              </li>
              <li class="nav-item">
                <a class="nav-link btn-rotate" href="javascript:;">
                  <i class="nc-icon nc-settings-gear-65"></i>
                  <p>
                    <span class="d-lg-none d-md-block">Account</span>
                  </p>
                </a>
              </li>
            </ul>
          </div>
        </div>
      </nav>
      <!-- End Navbar -->
      <div class="content">
        <div class="row">
          <div class="col-md-12">
            <div class="card demo-icons">
              <div class="card-header">
                <h5 class="card-title">Input Gudang dan Tahun</h5>
                <form id="opnameForm">
                <div class="row">
                  <div class="col-md-6 pr-1">
                    <div class="form-group">
                      <label>Input Kode Barkode</label>
                      <input type="text" id="barcode_input" class="form-control" name="barcode" required autofocus >
                      <button type="button" class="btn btn-primary btn-round" onclick="cekBarcode()">Cek Barcode</button>
                    </div>

                    <div style="margin-top: 20px;">
                      <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 class="row">
                    <div class="update ml-auto mr-auto">
                      <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 ?>">
                    </div>
                </form>
              </div>
            </div>
          </div>
        </div>
      </div>
      <footer class="footer footer-black  footer-white ">
        <div class="container-fluid">
          <div class="row">
            <nav class="footer-nav">
              <ul>
                <li><a href="https://www.creative-tim.com" target="_blank">Creative Tim</a></li>
                <li><a href="https://www.creative-tim.com/blog" target="_blank">Blog</a></li>
                <li><a href="https://www.creative-tim.com/license" target="_blank">Licenses</a></li>
              </ul>
            </nav>
            <div class="credits ml-auto">
              <span class="copyright">
                © <script>
                  document.write(new Date().getFullYear())
                </script>, made with <i class="fa fa-heart heart"></i> by Creative Tim
              </span>
            </div>
          </div>
        </div>
      </footer>
    </div>
  </div>
  <!--   Core JS Files   -->
  <script src="../assets/js/core/jquery.min.js"></script>
  <script src="../assets/js/core/popper.min.js"></script>
  <script src="../assets/js/core/bootstrap.min.js"></script>
  <script src="../assets/js/plugins/perfect-scrollbar.jquery.min.js"></script>
  <!--  Google Maps Plugin    -->
  <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY_HERE"></script>
  <!-- Chart JS -->
  <script src="../assets/js/plugins/chartjs.min.js"></script>
  <!--  Notifications Plugin    -->
  <script src="../assets/js/plugins/bootstrap-notify.js"></script>
  <!-- Control Center for Now Ui Dashboard: parallax effects, scripts for the example pages etc -->
  <script src="../assets/js/paper-dashboard.min.js?v=2.0.1" type="text/javascript"></script><!-- Paper Dashboard DEMO methods, don't include it in your project! -->
  <script src="../assets/demo/demo.js"></script>
  <script>
    function SelectText(element) {
      var doc = document,
        text = element,
        range, selection;
      if (doc.body.createTextRange) {
        range = document.body.createTextRange();
        range.moveToElementText(text);
        range.select();
      } else if (window.getSelection) {
        selection = window.getSelection();
        range = document.createRange();
        range.selectNodeContents(text);
        selection.removeAllRanges();
        selection.addRange(range);
      }
    }
    window.onload = function() {
      var iconsWrapper = document.getElementById('icons-wrapper'),
        listItems = iconsWrapper.getElementsByTagName('li');
      for (var i = 0; i < listItems.length; i++) {
        listItems[i].onclick = function fun(event) {
          var selectedTagName = event.target.tagName.toLowerCase();
          if (selectedTagName == 'p' || selectedTagName == 'em') {
            SelectText(event.target);
          } else if (selectedTagName == 'input') {
            event.target.setSelectionRange(0, event.target.value.length);
          }
        }

        var beforeContentChar = window.getComputedStyle(listItems[i].getElementsByTagName('i')[0], '::before').getPropertyValue('content').replace(/'/g, "").replace(/"/g, ""),
          beforeContent = beforeContentChar.charCodeAt(0).toString(16);
        var beforeContentElement = document.createElement("em");
        beforeContentElement.textContent = "\\" + beforeContent;
        listItems[i].appendChild(beforeContentElement);

        //create input element to copy/paste chart
        var charCharac = document.createElement('input');
        charCharac.setAttribute('type', 'text');
        charCharac.setAttribute('maxlength', '1');
        charCharac.setAttribute('readonly', 'true');
        charCharac.setAttribute('value', beforeContentChar);
        listItems[i].appendChild(charCharac);
      }
    }
    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>
