<?php
include "koneksi.php";

// ====== PROSES SIMPAN PRODUK BARU ======
if (isset($_POST['tambah'])) {
    $kode_barang   = trim($_POST['kode_barang']);
    $nama_produk   = trim($_POST['nama_produk']);
    $stok          = (int) $_POST['stok'];
    $harga_beli    = (float) $_POST['harga_beli'];
    $harga_eceran  = (float) $_POST['harga_eceran'];
    $kategori      = trim($_POST['kategori']);

    // === CEK DUPLIKAT ===
    $cek = $conn->prepare("SELECT id FROM tabel_produk WHERE kode_barang = ? OR nama_produk = ? LIMIT 1");
    $cek->bind_param("ss", $kode_barang, $nama_produk);
    $cek->execute();
    $hasil = $cek->get_result();

    if ($hasil->num_rows > 0) {
        echo "<script>alert('Kode barang atau nama produk sudah ada!'); history.back();</script>";
        exit;
    }

    // === SIMPAN DATA BARU ===
    $stmt = $conn->prepare("INSERT INTO tabel_produk 
        (kode_barang, nama_produk, stok, harga_beli, harga_eceran, kategori) 
        VALUES (?,?,?,?,?,?)");
    $stmt->bind_param("ssidds", 
        $kode_barang,
        $nama_produk,
        $stok,
        $harga_beli,
        $harga_eceran,
        $kategori
    );

    if ($stmt->execute()) {
        echo "<script>alert('Produk berhasil ditambahkan!'); location.href='index.php?page=produk';</script>";
    } else {
        echo "Gagal tambah produk: " . $stmt->error;
    }
}
?>

<div class="container mt-4">
    <h3>Tambah Produk Baru</h3>
    <form method="post">
        <div class="mb-3">
            <label>Kode Barang</label>
            <input type="text" name="kode_barang" class="form-control" required>
        </div>
        <div class="mb-3">
            <label>Nama Produk</label>
            <input type="text" name="nama_produk" class="form-control" required>
        </div>
        <div class="mb-3">
            <label>Stok</label>
            <input type="number" name="stok" class="form-control" required>
        </div>
        <div class="mb-3">
            <label>Harga Beli</label>
            <input type="number" step="0.01" name="harga_beli" class="form-control" required>
        </div>
        <div class="mb-3">
            <label>Harga Eceran</label>
            <input type="number" step="0.01" name="harga_eceran" class="form-control" required>
        </div>
        <div class="mb-3">
            <label>Kategori</label>
            <input type="text" name="kategori" class="form-control" required>
        </div>
        <button type="submit" name="tambah" class="btn btn-success">Simpan</button>
        <a href="index.php?page=produk" class="btn btn-secondary">Kembali</a>
    </form>
</div>
