<?php

session_start();

$path_to_root = "";
include $path_to_root . '../database.php';

$db = new database();

if (isset($_GET['action']) && $_GET['action']!="" && $_GET['action']=='update') {
	$id = $_GET['produk_id'];
	$nama = strip_tags(trim($_POST['nama']));
	$harga = strip_tags(trim($_POST['harga']));
	$deskripsi = strip_tags(trim($_POST['deskripsi']));
	$stok = strip_tags(trim($_POST['stok']));

	$sql_update = "UPDATE `barang` SET `nama` = '".$nama."', `harga` = '".$harga."', `stok` = '".$stok."', `deskripsi` = '".$deskripsi."' WHERE `id_barang` = ".$id;

	$result_update = $db->db_query($sql_update);

	if ($result_update) {
		header("location:index.php?menu=barang");
	} else {
		echo "Tambah Data Gagal!<br/>";
	}
} else {
	// ambil data file
	$namaFile = $_FILES['gambar']['name'];
	$namaSementara = $_FILES['gambar']['tmp_name'];

	// tentukan lokasi file akan dipindahkan
	$dirUpload = "../img-barang/";

	// pindahkan file
	$terupload = move_uploaded_file($namaSementara, $dirUpload.$namaFile);

	$nama = strip_tags(trim($_POST['nama']));
	$harga = strip_tags(trim($_POST['harga']));
	$deskripsi = strip_tags(trim($_POST['deskripsi']));
	$stok = strip_tags(trim($_POST['stok']));

	if ($terupload) {
		$sql = get_sql_tambah_barang($nama, $harga, $deskripsi, $stok, $namaFile);

		$result = $db->db_query($sql);

		if ($result) {
			header("location:index.php?menu=barang");
		} else {
			echo "Tambah Data Gagal!<br/>";
		}
	} else {
	    echo "Upload File Gagal!";
	}
}

function get_sql_tambah_barang($nama, $harga, $deskripsi, $stok, $foto){
	$sql = "INSERT INTO `barang` (`nama`, `harga`, `deskripsi`, `stok`, `foto`) VALUES ('" . $nama ."', '" . $harga . "', '" . $deskripsi . "', '" . $stok . "', '" . $foto . "')";
	return $sql;
}

?>