<?php 
$koneksi = new mysqli("localhost", "bpjw9637_inventori", "inventori123", "bpjw9637_inventori");

// Periksa koneksi
if ($koneksi->connect_error) {
    die("Koneksi gagal: " . $koneksi->connect_error);
}

// Query untuk mengambil kode barang terakhir dari database
$no = mysqli_query($koneksi, "SELECT kode_barang FROM gudang ORDER BY kode_barang DESC LIMIT 1");
$kdbarang = mysqli_fetch_array($no);
$kode = isset($kdbarang['kode_barang']) ? $kdbarang['kode_barang'] : '';

// Mengecek apakah kode barang terakhir ada dan bukan null
$urut = $kode ? substr($kode, 8, 3) : '000';
$tambah = (int)$urut + 1;

$bulan = date("m");
$tahun = date("y");

// Menentukan format kode barang baru
if (strlen($tambah) == 1) {
    $format = "BAR-" . $bulan . $tahun . "00" . $tambah;
} elseif (strlen($tambah) == 2) {
    $format = "BAR-" . $bulan . $tahun . "0" . $tambah;
} else {
    $format = "BAR-" . $bulan . $tahun . $tambah;
}

$jumlah = 0;
?>

<div class="container-fluid">
    <!-- DataTales Example -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary">Tambah Stok</h6>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <div class="body">
                    <form method="POST" enctype="multipart/form-data">
                        <label for="">Kode Barang</label>
                        <div class="form-group">
                            <div class="form-line">
                                <input type="text" name="kode_barang" class="form-control" id="kode_barang" value="<?php echo $format; ?>" readonly />
                            </div>
                        </div>

                        <label for="">Nama Barang</label>
                        <div class="form-group">
                            <div class="form-line">
                                <input type="text" name="nama_barang" class="form-control" required />
                            </div>
                        </div>

                        <label for="">Jenis Barang</label>
                        <div class="form-group">
                            <div class="form-line">
                                <select name="jenis_barang" class="form-control" required>
                                    <option value="">-- Pilih Jenis Barang --</option>
                                    <?php
                                    $sql = $koneksi->query("SELECT * FROM jenis_barang ORDER BY id");
                                    while ($data = $sql->fetch_assoc()) {
                                        echo "<option value='" . $data['id'] . "." . $data['jenis_barang'] . "'>" . $data['jenis_barang'] . "</option>";
                                    }
                                    ?>
                                </select>
                            </div>
                        </div>

                        <label for="">Foto</label>
                        <div class="form-group">
                            <div class="form-line">
                                <input type="file" name="foto" class="form-control" />
                            </div>
                        </div>

                        <label for="">Jumlah</label>
                        <div class="form-group">
                            <div class="form-line">
                                <input type="text" name="jumlah" class="form-control" id="jumlah" value="<?php echo $jumlah; ?>" readonly />
                            </div>
                        </div>

                        <label for="">Satuan Barang</label>
                        <div class="form-group">
                            <div class="form-line">
                                <select name="satuan" class="form-control" required>
                                    <option value="">-- Pilih Satuan Barang --</option>
                                    <?php
                                    $sql = $koneksi->query("SELECT * FROM satuan ORDER BY id");
                                    while ($data = $sql->fetch_assoc()) {
                                        echo "<option value='" . $data['id'] . "." . $data['satuan'] . "'>" . $data['satuan'] . "</option>";
                                    }
                                    ?>
                                </select>
                            </div>
                        </div>

                        <input type="submit" name="simpan" value="Simpan" class="btn btn-primary">
                    </form>

                    <?php
                    if (isset($_POST['simpan'])) {
                        // Sanitasi input
                        $kode_barang = $koneksi->real_escape_string($_POST['kode_barang']);
                        $nama_barang = $koneksi->real_escape_string($_POST['nama_barang']);
                        
                        $jenis_barang_input = $koneksi->real_escape_string($_POST['jenis_barang']);
                        $jenis_pieces = explode(".", $jenis_barang_input);
                        $id_jenis = isset($jenis_pieces[0]) ? $jenis_pieces[0] : '';
                        $jenis_barang = isset($jenis_pieces[1]) ? $jenis_pieces[1] : '';
                        
                        $jumlah = isset($_POST['jumlah']) ? (int)$_POST['jumlah'] : 0;
                        
                        $satuan_input = $koneksi->real_escape_string($_POST['satuan']);
                        $satuan_pieces = explode(".", $satuan_input);
                        $id_satuan = isset($satuan_pieces[0]) ? $satuan_pieces[0] : '';
                        $satuan = isset($satuan_pieces[1]) ? $satuan_pieces[1] : '';

                        // Menghandle upload foto
                        if (isset($_FILES['foto']) && $_FILES['foto']['error'] == 0) {
                            $foto = $koneksi->real_escape_string($_FILES['foto']['name']);
                            $lokasi = $_FILES['foto']['tmp_name'];
                            $target_dir = "img/";
                            $target_file = $target_dir . basename($foto);

                            // Pastikan direktori tujuan ada
                            if (!is_dir($target_dir)) {
                                mkdir($target_dir, 0755, true);
                            }

                            // Validasi tipe file (opsional)
                            $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
                            $extensions_arr = array("jpg", "jpeg", "png", "gif");

                            if (in_array($imageFileType, $extensions_arr)) {
                                // Upload file
                                if (move_uploaded_file($lokasi, $target_file)) {
                                    // File berhasil diupload, simpan data ke database
                                    $sql_insert = "INSERT INTO gudang (kode_barang, nama_barang, jenis_barang, foto, jumlah, satuan) VALUES ('$kode_barang', '$nama_barang', '$jenis_barang', '$foto', '$jumlah', '$satuan')";
                                    $sql = $koneksi->query($sql_insert);

                                    if ($sql) {
                                        echo '<script type="text/javascript">
                                                alert("Data Berhasil Disimpan");
                                                window.location.href="?page=gudang";
                                              </script>';
                                    } else {
                                        echo '<script type="text/javascript">
                                                alert("Data Gagal Disimpan: ' . $koneksi->error . '");
                                              </script>';
                                    }
                                } else {
                                    echo '<script type="text/javascript">
                                            alert("Gagal mengupload foto.");
                                          </script>';
                                }
                            } else {
                                echo '<script type="text/javascript">
                                        alert("Ekstensi file tidak diperbolehkan. Hanya JPG, JPEG, PNG, dan GIF yang diperbolehkan.");
                                      </script>';
                            }
                        } else {
                            echo '<script type="text/javascript">
                                    alert("Gagal mengupload foto atau tidak ada file yang diupload.");
                                  </script>';
                        }
                    }

                    // Tutup koneksi
                    $koneksi->close();
                    ?>
                </div>
            </div>
        </div>
    </div>
</div>
