<?php
session_start();
include ('../config/conn.php');
include ('../config/function.php');

if(isset($_POST['tambah'])){
    $id = $_POST['idbarang'];
    $nama_barang = $_POST['nama_barang'];
    $merek = $_POST['merek_id'];
    $tipe = $_POST['tipe'];
    $sn = $_POST['sn'];
    $stok = 0;
    $satuan = $_POST['satuan_id'];

    $insert = mysqli_query($con,"INSERT INTO barang (idbarang, nama_barang, merek_id, tipe, sn, stok, satuan_id) VALUES ('$id','$nama_barang','$merek','$tipe','$sn','$stok','$satuan')") or die (mysqli_error($con));
    if($insert){
        $success = 'Berhasil menambahkan data barang';
    }else{
        $error = 'Gagal menambahkan data barang';
    }
    $_SESSION['success'] = $success;
    $_SESSION['error'] = $error;
    header('Location:../dashboard.php?barang');
}

if(isset($_POST['ubah'])){
    $id = $_POST['idbarang'];
    $nama_barang = $_POST['nama_barang'];
    $merek = $_POST['merek_id'];
    $tipe = $_POST['tipe'];
    $sn = $_POST['sn'];
    $stok = 0;
    $satuan = $_POST['satuan_id'];

    $update = mysqli_query($con,"UPDATE barang SET nama_barang='$nama_barang', merek_id='$merek', tipe='$tipe', sn='$sn', stok='$stok', satuan_id='$satuan' WHERE idbarang='$id'") or die (mysqli_error($con));
    
    // var_dump($update);die;
    if($update){
        $success = 'Berhasil mengubah data barang';
    }else{
        $error = 'Gagal mengubah data barang';
    }
    $_SESSION['success'] = $success;
    $_SESSION['error'] = $error;
    header('Location:../dashboard.php?barang');
}

if(decrypt($_GET['act'])=='delete' && isset($_GET['id'])!=""){
    // echo $_GET['act'];die;
    $id = decrypt($_GET['id']);
    $delete = mysqli_query($con, "DELETE FROM barang WHERE idbarang='$id'")or die(mysqli_error($con));
    if ($delete) {
        $success = "Data barang berhasil dihapus";
    }else{
        $error = "Data barang gagal dihapus";
    }
    $_SESSION['success'] = $success;
    $_SESSION['error'] = $error;
    header('Location:../dashboard.php?barang');
}
?>