<!--
=========================================================
* 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';

// Ambil semua nama_gudang unik
$gudang_result = $conn->query("SELECT DISTINCT nama_gudang FROM gudang_tahun ORDER BY nama_gudang ASC");

// Tangkap nama_gudang dan tahun dari GET
$nama_gudang = $_GET['nama_gudang'] ?? null;
$tahun       = $_GET['tahun'] ?? null;

// Ambil tahun berdasarkan nama_gudang jika sudah dipilih
$tahun_result = [];
if ($nama_gudang) {
    $stmt_tahun = $conn->prepare("SELECT DISTINCT tahun FROM gudang_tahun WHERE nama_gudang = ? ORDER BY tahun DESC");
    $stmt_tahun->bind_param("s", $nama_gudang);
    $stmt_tahun->execute();
    $tahun_result = $stmt_tahun->get_result();
}

// Ambil data hasil_opname
$data_opname = [];
$id_gudang_sekarang = null;
if ($nama_gudang && $tahun) {
    $stmt = $conn->prepare("
        SELECT ho.*, b.nama_barang, gt.nama_gudang, gt.id_gudang
        FROM hasil_opname ho
        JOIN barang b ON ho.id_barang = b.id_barang
        JOIN gudang_tahun gt ON ho.id_gudang = gt.id_gudang AND ho.tahun = gt.tahun
        WHERE gt.nama_gudang = ? AND gt.tahun = ?
    ");
    $stmt->bind_param("ss", $nama_gudang, $tahun);
    $stmt->execute();
    $result = $stmt->get_result();

    while ($row = $result->fetch_assoc()) {
        $id_barang = $row['id_barang'];
        $id_gudang_sekarang = $row['id_gudang'];
        $tahun_sekarang = $tahun;
        $tahun_lalu = (string)((int)$tahun - 1);

        // --- SOLUSI FIX ---
        // 1. Ambil id_gudang tahun sebelumnya
        $stmt_gudang_lalu = $conn->prepare("
            SELECT id_gudang FROM gudang_tahun
            WHERE nama_gudang = ? AND tahun = ?
            LIMIT 1
        ");
        $stmt_gudang_lalu->bind_param("ss", $nama_gudang, $tahun_lalu);
        $stmt_gudang_lalu->execute();
        $res_gudang_lalu = $stmt_gudang_lalu->get_result();
        $id_gudang_lalu = $res_gudang_lalu->fetch_assoc()['id_gudang'] ?? null;
        $stmt_gudang_lalu->close();

        $prev_stock_akhir = 0;
        if ($id_gudang_lalu) {
            // 2. Ambil stock_akhir dari hasil_opname tahun sebelumnya
            $stmt_prev = $conn->prepare("
                SELECT stock_akhir
                FROM hasil_opname
                WHERE id_barang = ? AND id_gudang = ? AND tahun = ?
                ORDER BY id_opname DESC
                LIMIT 1
            ");
            $stmt_prev->bind_param("sss", $id_barang, $id_gudang_lalu, $tahun_lalu);
            $stmt_prev->execute();
            $prev_result = $stmt_prev->get_result();
            $prev_stock_akhir = $prev_result->fetch_assoc()['stock_akhir'] ?? 0;
            $stmt_prev->close();
        }

        $row['stock_akhir_lalu'] = $prev_stock_akhir;
        $data_opname[] = $row;
    }
    $stmt->close();
}
?>

<!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>
  <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>
        </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="card">
          <div class="card-body">
            <form id="filterForm" method="GET" action="dashboard.php" class="d-flex justify-content-between align-items-center flex-wrap">
              <div class="filters-wrap">
                <!-- Chip 1: Pilih Gudang -->
                <div class="filter-chip">
                  <label for="gudang_id" class="mb-0">Pilih Gudang</label>
                  <select name="nama_gudang" onchange="this.form.submit()" required>
                    <option value="">Pilih Gudang</option>
                    <?php while ($row = $gudang_result->fetch_assoc()): ?>
                        <option value="<?= htmlspecialchars($row['nama_gudang']) ?>" <?= ($nama_gudang == $row['nama_gudang']) ? 'selected' : '' ?>>
                            <?= htmlspecialchars($row['nama_gudang']) ?>
                        </option>
                    <?php endwhile; ?>
                  </select>
                </div>

                <!-- Chip 2: Pilih Tahun -->
                <div class="filter-chip">
                  <label for="tahun" class="mb-0">Pilih Tahun</label>
                  <select name="tahun" required>
                    <option value="">Pilih Tahun</option>
                    <?php if ($tahun_result): ?>
                        <?php while ($row = $tahun_result->fetch_assoc()): ?>
                            <option value="<?= $row['tahun'] ?>" <?= ($tahun == $row['tahun']) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($row['tahun']) ?>
                            </option>
                        <?php endwhile; ?>
                    <?php endif; ?>
                </select>
                </div>
              </div>

              <div class="filters-actions mt-2 mt-md-0">
                <button type="submit" class="btn btn-success btn-primary btn-round">Cari</button>
              </div>
            </form>
          </div>
        </div>

        <!-- ===== Modal Tambah Data (UI Only) ===== -->
        <!-- ===== Modal Tambah Data ===== -->
        <div class="modal fade" id="modalTambah" tabindex="-1" role="dialog" aria-labelledby="modalTambahLabel" aria-hidden="true">
          <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">

              <div class="modal-header">
                <h5 class="modal-title" id="modalTambahLabel">Tambah Data</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">×</span>
                </button>
              </div>

              <form id="formTambah" method="POST" action="proses_tambah.php">
                <div class="modal-body">
                  <!-- === INPUT GUDANG DENGAN DATALIST === -->
                  <div class="form-group">
                    <?php
                      $conn = new mysqli("localhost", "root", "", "soralika");
                      $gudangResult = $conn->query("SELECT nama_gudang FROM gudang ORDER BY nama_gudang ASC");
                    ?>
                    <label for="nama_gudang">Gudang</label>
                    <input list="gudangList" name="nama_gudang" id="nama_gudang" class="form-control" placeholder="Ketik atau pilih gudang..." required>
                    <datalist id="gudangList">
                      <?php while($row = $gudangResult->fetch_assoc()): ?>
                        <option value="<?= htmlspecialchars($row['nama_gudang']) ?>"></option>
                      <?php endwhile; ?>
                    </datalist>
                  </div>

                  <!-- === TAHUN DINAMIS === -->
                  <div class="form-group">
                    <label for="tahun">Tahun</label>
                    <select name="tahun" id="tahun" class="form-control" required>
                      <option value="">-- Pilih Tahun --</option>
                      <?php
                        $tahunSekarang = date('Y');
                        for ($th = $tahunSekarang; $th >= 2020; $th--) {
                            echo "<option value=\"$th\">$th</option>";
                        }
                      ?>
                    </select>
                  </div>

                </div>
                <div class="modal-footer">
                  <button type="button" class="btn btn-outline-secondary" data-dismiss="modal">Batal</button>
                  <button type="submit" class="btn btn-success">Simpan</button>
                </div>
              </form>

            </div>
          </div>
        </div>

        <div class="row">
          <div class="col-md-12">
            <div class="card ">
              <div class="card-header ">
                <h5 class="card-title">tes</h5>
                <p class="card-category">24 Hours performance</p>
              </div>
              <div class="card-body ">
              <?php if ($nama_gudang && $tahun): ?>
                  <?php if (count($data_opname) > 0): ?>
                      <h3>Hasil Opname Gudang <?= htmlspecialchars($nama_gudang) ?> - Tahun <?= htmlspecialchars($tahun) ?></h3>

                      <form method="GET" action="export_opname_excel.php" target="_blank">
                          <input type="hidden" name="id_gudang" value="<?= htmlspecialchars($id_gudang_sekarang) ?>">
                          <input type="hidden" name="nama_gudang" value="<?= htmlspecialchars($nama_gudang) ?>">
                          <input type="hidden" name="tahun" value="<?= htmlspecialchars($tahun) ?>">
                          <button type="submit">📥 Download Excel</button>
                      </form>
              </div>
              <div class="card-body ">
                <div class="table-responsive">
                  <table class="table">
                    <thead class=" text-primary">
                        <th class="text-center">No.</th>
                        <th class="text-center">Nama Barang</th>
                        <th class="text-center">Part Number</th>
                        <th class="text-center">Stock Awal</th>
                        <th class="text-center">Kondisi Bagus</th>
                        <th class="text-center">Kondisi Rusak</th>
                        <th class="text-center">Stock Akhir</th>
                        <th class="text-center">Satuan</th>
                        <th class="text-center">Barcode</th>
                      </thead>
                  <tbody>
                  <?php $no = 1; foreach ($data_opname as $row): ?>
                    <tr>
                        <td class="text-center"><?= $no++ ?></td>
                        <td><?= htmlspecialchars($row['nama_barang']) ?></td>
                        <td class="text-center"><?= htmlspecialchars($row['part_number']) ?></td>
                        <td class="text-center"><?= htmlspecialchars($row['stock_akhir_lalu']) ?></td>
                        <td class="text-center"><?= number_format($row['kondisi_bagus'] ?? 0) ?></td>
                        <td class="text-center"><?= number_format($row['kondisi_rusak'] ?? 0) ?></td>
                        <td class="text-center"><?= htmlspecialchars($row['stock_akhir']) ?></td>
                        <td class="text-center"><?= htmlspecialchars($row['satuan']) ?></td>
                        <td class="text-center"><?= htmlspecialchars($row['barcode']) ?></td>
                    </tr>
                    <?php endforeach; ?>
                  </tbody>
                </table>
              <?php else: ?>
                  <p><em>Tidak ada data opname untuk gudang dan tahun yang dipilih.</em></p>
              <?php endif; ?>
          <?php endif; ?>
              </div>
              <div class="card-footer ">
                <hr>
                <div class="stats">
                  <i class="fa fa-history"></i> Updated 3 minutes ago
                </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>
    $(document).ready(function() {
      // Javascript method's body can be found in assets/assets-for-demo/js/demo.js
      demo.initChartsPages();
    });
  </script>
  <script>
  document.getElementById('modalTambah').addEventListener('show.bs.modal', function () {
    var g = document.getElementById('gudang_id').value;
    var t = document.getElementById('tahun').value;
    if (g) document.getElementById('tambah_gudang').value = g;
    if (t) document.getElementById('tambah_tahun').value = t;
  });
</script>
</body>

</html>
