<?php 

// koneksi
require_once __DIR__ . '/../../koneksi.php';



// summon admin

function summon_admin()
{
	global $koneksi;
	$id = $_SESSION['idkaskit'];
	return mysqli_query($koneksi, "SELECT * FROM tb_user WHERE id ='$id'");
}

// -------------------------------------USER SECTION--------------------------------------------------------------------
// select user by admin
function select_user()
{
	global $koneksi;
	if ((isset($_GET['go']) || isset($_POST['go'])) && !empty($_GET['cari'] ?? $_POST['cari'] ?? '')) {
		$cari = mysqli_real_escape_string($koneksi, $_GET['cari'] ?? $_POST['cari']);
		return mysqli_query($koneksi, "SELECT * FROM tb_user WHERE nama LIKE '%$cari%' OR username LIKE '%$cari%'");
	}else{
		return mysqli_query($koneksi, "SELECT * FROM tb_user");
	}
	
}

function select_user_2()
{
	global $koneksi;
	$query =  mysqli_query($koneksi, "SELECT count(id) AS jadmin FROM tb_user ORDER BY id DESC");
	$key = mysqli_fetch_array($query);
	echo $key['jadmin'];
}


// Insert user

function insert_user()
{
	global $koneksi;
	$username = mysqli_real_escape_string($koneksi, $_POST['username']);
	$password = md5($_POST['password']);
	$nama = mysqli_real_escape_string($koneksi, $_POST['nama']);
	$level = mysqli_real_escape_string($koneksi, $_POST['level']);
	$foto = $_FILES['foto']['name'];

	// cek username
	$cek = mysqli_query($koneksi, "SELECT * FROM tb_user WHERE username ='$username'");
	$row = mysqli_fetch_row($cek);

	if ($row) {
		header("location: index.php?m=admin&s=title&msg=gagal");
		exit;
	}

	if ($foto != "") {
		$allowed_ext = array('png','jpg');
		$x = explode(".", $foto);
		$ekstensi = strtolower(end($x));
		$file_tmp = $_FILES['foto']['tmp_name'];
		$angka_acak = rand(1,999);
		$nama_file_baru = $angka_acak.'-'.$foto;
		if (in_array($ekstensi, $allowed_ext) === true) {
			move_uploaded_file($file_tmp, 'img/'.$nama_file_baru);
			$query = mysqli_query($koneksi, "INSERT INTO tb_user SET username='$username', password='$password', nama='$nama', level='$level', foto='$nama_file_baru'");
		} else {
			header("location: index.php?m=admin&s=title&msg=gagal");
			exit;
		}
	} else {
		$query = mysqli_query($koneksi, "INSERT INTO tb_user SET username='$username', password='$password', nama='$nama', level='$level', foto=''");
	}

	if ($query) {
		header("location: index.php?m=admin&s=title&msg=tambah_sukses");
	} else {
		header("location: index.php?m=admin&s=title&msg=gagal");
	}
	exit;
}

// delete user

function delete_user()
{
	global $koneksi;
	$id = (int)$_POST['id'];

	// Prevent deleting admin users
	$existing = mysqli_fetch_array(mysqli_query($koneksi, "SELECT * FROM tb_user WHERE id='$id'"));
	if ($existing && $existing['level'] == 'admin') {
		header("location: index.php?m=admin&s=title&msg=gagal");
		exit;
	}

	$cekimg = mysqli_query($koneksi, "SELECT * FROM tb_user WHERE id='$id'");
	$row = mysqli_fetch_array($cekimg);

	if ($row && !empty($row['foto'])) {
		$foto = $row['foto'];
		if (file_exists("img/$foto")) {
			unlink("img/$foto");
		}
	}

	$query = mysqli_query($koneksi, "DELETE FROM tb_user WHERE id='$id'");
	if ($query) {
		header("location: index.php?m=admin&s=title&msg=hapus_sukses");
		exit;
	} else {
		header("location: index.php?m=admin&s=title&msg=gagal");
		exit;
	}
}

// update user
function update_user()
{
	global $koneksi;
	$id = (int)$_POST['id'];

	$existing = mysqli_fetch_array(mysqli_query($koneksi, "SELECT * FROM tb_user WHERE id='$id'"));
	$foto_data = $existing['foto'];
	$is_admin = ($existing['level'] == 'admin');

	if (!$is_admin) {
		$username = mysqli_real_escape_string($koneksi, $_POST['username']);
		$nama = mysqli_real_escape_string($koneksi, $_POST['nama']);
		$level = mysqli_real_escape_string($koneksi, $_POST['level']);
		if (!empty($_POST['password'])) {
	$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
			$password_sql = ", password='$password'";
		} else {
			$password_sql = "";
		}
		$field_sql = "username='$username', nama='$nama', level='$level' $password_sql,";
	} else {
		$field_sql = "";
	}

	if (isset($_POST['hapusfoto']) && $foto_data != '') {
		@unlink("img/$foto_data");
		$foto_data = '';
	}

	$foto_name = $_FILES['foto']['name'];
	if ($foto_name != '') {
		$allowed_ext = array('png','jpg');
		$x = explode(".", $foto_name);
		$ekstensi = strtolower(end($x));
		$file_tmp = $_FILES['foto']['tmp_name'];
		$angka_acak = rand(1,999);
		$nama_file_baru = $angka_acak.'-'.$foto_name;
		if (in_array($ekstensi, $allowed_ext) === true) {
			move_uploaded_file($file_tmp, 'img/'.$nama_file_baru);
			if ($foto_data != '') {
				@unlink("img/$foto_data");
			}
			$foto_data = $nama_file_baru;
		}
	}

	$query = mysqli_query($koneksi, "UPDATE tb_user SET $field_sql foto='$foto_data' WHERE id='$id'");
	if ($query) {
		header("location: index.php?m=admin&s=detail&id=$id&msg=edit_sukses");
		exit;
	} else {
		header("location: index.php?m=admin&s=detail&id=$id&msg=gagal");
		exit;
	}
}

// ---------------------------------------------------RAK SECTION---------------------------------\\

function insert_rak()
{
	global $koneksi;
	$kdrak = mysqli_real_escape_string($koneksi, $_POST['kdrak']);
	$namarak = mysqli_real_escape_string($koneksi, $_POST['namarak']);
	$query = mysqli_query($koneksi, "INSERT INTO tb_rak SET kdrak='$kdrak', namarak='$namarak'");
	if ($query) {
		header("location: index.php?m=rak&s=title&msg=tambah_sukses");
	} else {
		header("location: index.php?m=rak&s=title&msg=gagal");
	}
	exit;
}

function delete_rak()
{
	global $koneksi;
	$id = (int)$_POST['id'];
	$query = mysqli_query($koneksi, "DELETE FROM tb_rak WHERE id='$id'");
	if ($query) {
		header("location: index.php?m=rak&s=title&msg=hapus_sukses");
	} else {
		header("location: index.php?m=rak&s=title&msg=gagal");
	}
	exit;
}

function update_rak()
{
	global $koneksi;
	$id = (int)$_POST['id'];
	$kdrak = mysqli_real_escape_string($koneksi, $_POST['kdrak']);
	$namarak = mysqli_real_escape_string($koneksi, $_POST['namarak']);
	$query = mysqli_query($koneksi, "UPDATE tb_rak SET kdrak='$kdrak', namarak='$namarak' WHERE id='$id'");
	if ($query) {
		header("location: index.php?m=rak&s=title&msg=edit_sukses");
	} else {
		header("location: index.php?m=rak&s=title&msg=gagal");
	}
	exit;
}


// ----------------------------------------------SUPPLIER SECTION---------------------------------------------------------------\\

function insert_supplier()
{
	global $koneksi;
	$kdspl = mysqli_real_escape_string($koneksi, $_POST['kdspl']);
	$namaspl = mysqli_real_escape_string($koneksi, $_POST['namaspl']);
	$alamatspl = mysqli_real_escape_string($koneksi, $_POST['alamatspl']);
	$kontakspl = mysqli_real_escape_string($koneksi, $_POST['kontakspl']);
	$query = mysqli_query($koneksi, "INSERT INTO tb_supplier SET kdspl='$kdspl', namaspl='$namaspl', alamatspl='$alamatspl', kontakspl='$kontakspl'");
	if ($query) {
		header("location: index.php?m=supplier&s=title&msg=tambah_sukses");
	} else {
		header("location: index.php?m=supplier&s=title&msg=gagal");
	}
	exit;
}

function hapus_supplier()
{
	global $koneksi;
	$id = (int)$_POST['id'];
	$query = mysqli_query($koneksi, "DELETE FROM tb_supplier WHERE id='$id'");
	if ($query) {
		header("location: index.php?m=supplier&s=title&msg=hapus_sukses");
	} else {
		header("location: index.php?m=supplier&s=title&msg=gagal");
	}
	exit;
}

function update_supplier()
{
	global $koneksi;
	$id = (int)$_POST['id'];
	$kdspl = mysqli_real_escape_string($koneksi, $_POST['kdspl']);
	$namaspl = mysqli_real_escape_string($koneksi, $_POST['namaspl']);
	$alamatspl = mysqli_real_escape_string($koneksi, $_POST['alamatspl']);
	$kontakspl = mysqli_real_escape_string($koneksi, $_POST['kontakspl']);
	$query = mysqli_query($koneksi, "UPDATE tb_supplier SET kdspl='$kdspl', namaspl='$namaspl', alamatspl='$alamatspl', kontakspl='$kontakspl' WHERE id='$id'");
	if ($query) {
		header("location: index.php?m=supplier&s=title&msg=edit_sukses");
	} else {
		header("location: index.php?m=supplier&s=title&msg=gagal");
	}
	exit;
}

// ------------------------------------------------------------BARANG SECTION----------------------------------------------------\\

function insert_barang()
{
	global $koneksi;
	$kdbarang = mysqli_real_escape_string($koneksi, $_POST['kdbarang']);
	$nm_barang = mysqli_real_escape_string($koneksi, $_POST['nm_barang']);
	$kategori = (int)$_POST['kategori'];
	$stok = (int)$_POST['stok'];

	$harga_beli = (int)$_POST['harga_beli'];
	$harga_jual = (int)$_POST['harga_jual'];
	$satuan = mysqli_real_escape_string($koneksi, $_POST['satuan'] ?? '');

	$query = mysqli_query($koneksi, "INSERT INTO tb_barang SET kdbarang='$kdbarang', nm_barang='$nm_barang', kategori='$kategori', stok='$stok', harga_beli='$harga_beli', harga_jual='$harga_jual', satuan='$satuan'");
	
	if($query){
		header("location: index.php?m=barang&s=title&msg=tambah_sukses");
		exit;
	} else {
		header("location: index.php?m=barang&s=title&msg=gagal");
		exit;
	}
}

function delete_barang()
{
	global $koneksi;
	$id = (int)$_POST['id'];
	$query = mysqli_query($koneksi, "DELETE FROM tb_barang WHERE id='$id'");
	if($query){
		header("location: index.php?m=barang&s=title&msg=hapus_sukses");
		exit;
	} else {
		header("location: index.php?m=barang&s=title&msg=gagal");
		exit;
	}
}

function update_barang()
{
	global $koneksi;
	$id = (int)$_POST['id'];
	$kdbarang = mysqli_real_escape_string($koneksi, $_POST['kdbarang']);
	$nm_barang = mysqli_real_escape_string($koneksi, $_POST['nm_barang']);
	$kategori = (int)$_POST['kategori'];
	$stok = (int)$_POST['stok'];

	$harga_beli = (int)$_POST['harga_beli'];
	$harga_jual = (int)$_POST['harga_jual'];
	$satuan = mysqli_real_escape_string($koneksi, $_POST['satuan'] ?? '');
	
	$query = mysqli_query($koneksi, "UPDATE tb_barang SET kdbarang='$kdbarang', nm_barang='$nm_barang', kategori='$kategori', stok='$stok', harga_beli='$harga_beli', harga_jual='$harga_jual', satuan='$satuan' WHERE id='$id'");
	
	if($query){
		header("location: index.php?m=barang&s=title&msg=edit_sukses");
		exit;
	} else {
		header("location: index.php?m=barang&s=title&msg=gagal");
		exit;
	}
}

function select_barang()
{
	global $koneksi;
	$query = mysqli_query($koneksi, "SELECT count(id) AS jbarang FROM tb_barang");
	$row = mysqli_fetch_array($query);
	echo $row['jbarang'];
}

// ------------------------------------------------KATEGORI SECTION---------------------------------------------------------------\\\

function insert_kategori()
{
	global $koneksi;
	$kategori = mysqli_real_escape_string($koneksi, $_POST['kategori']);
	$query = mysqli_query($koneksi, "INSERT INTO tb_kat SET kategori='$kategori'");
	if ($query) {
		header("location: index.php?m=kategori&s=title&msg=tambah_sukses");
	} else {
		header("location: index.php?m=kategori&s=title&msg=gagal");
	}
	exit;
}

function hapus_kategori()
{
	global $koneksi;
	$id = (int)$_POST['id'];
	$query = mysqli_query($koneksi, "DELETE FROM tb_kat WHERE id='$id'");
	if ($query) {
		header("location: index.php?m=kategori&s=title&msg=hapus_sukses");
	} else {
		header("location: index.php?m=kategori&s=title&msg=gagal");
	}
	exit;
}

function update_kategori()
{
	global $koneksi;
	$id = (int)$_POST['id'];
	$kategori = mysqli_real_escape_string($koneksi, $_POST['kategori']);
	$query = mysqli_query($koneksi, "UPDATE tb_kat SET kategori='$kategori' WHERE id='$id'");
	if ($query) {
		header("location: index.php?m=kategori&s=title&msg=edit_sukses");
	} else {
		header("location: index.php?m=kategori&s=title&msg=gagal");
	}
	exit;
}


// ---------------------------------------------------BARANG MASUK SECTION----------------------------------------------------------\\

function barang_masuk()
{
	global $koneksi;
	$noinv = mysqli_real_escape_string($koneksi, $_POST['noinv']);
	$tanggal = mysqli_real_escape_string($koneksi, $_POST['tanggal']);
	$jam = mysqli_real_escape_string($koneksi, $_POST['jam']);
	$kdbarang = mysqli_real_escape_string($koneksi, $_POST['kdbarang']);
	$nm_barang = mysqli_real_escape_string($koneksi, $_POST['nm_barang']);
	$kategori = mysqli_real_escape_string($koneksi, $_POST['kategori']);

	$stok = (int)$_POST['stok'];
	$jml_masuk = (int)$_POST['jml_masuk'];
	$admin = mysqli_real_escape_string($koneksi, $_POST['admin']);

	// Tambah Stok Tabel Barang
	$tambah_stok = $jml_masuk + $stok;
	$query = mysqli_query($koneksi, "UPDATE tb_barang SET stok='$tambah_stok' WHERE kdbarang='$kdbarang'");
	$query_insert = mysqli_query($koneksi, "INSERT INTO tb_barang_masuk SET noinv='$noinv', tanggal='$tanggal', jam='$jam', kdbarang='$kdbarang', nm_barang='$nm_barang', kategori='$kategori', stok='$stok', jml_masuk='$jml_masuk', admin='$admin'");

	if ($query_insert) {
		header("location: index.php?m=barangmasuk&s=title&msg=tambah_sukses");
	} else {
		header("location: index.php?m=barangmasuk&s=title&msg=gagal");
	}
	exit;
}

// -----------------------------------------CALL TRANSACTION-------------------------------------------------------------------------\\
function jumlah_saldo()
{
	global $koneksi;
	$jumlah = mysqli_query($koneksi, "SELECT sum(total) as jtotal from laporan_penjualan");
	$row = mysqli_fetch_array($jumlah);
	$total = $row['jtotal'] ? $row['jtotal'] : 0;
	echo rupiah($total);
}
function jumlah_terjual()
{
	global $koneksi;
	$jumlah = mysqli_query($koneksi, "SELECT sum(jumlah_beli) as jbeli from laporan_penjualan");
	$row = mysqli_fetch_array($jumlah);
	$jbeli = $row['jbeli'] ? $row['jbeli'] : 0;
	echo $jbeli;
}

// ---------------------------------------------lOGISTIK SECTON-----------------------------------------------------------------\\
function delete_pro_masuk()
{
	global $koneksi;
	$id = (int)$_POST['id'];
	$q = mysqli_query($koneksi, "SELECT kdbarang, jml_masuk FROM tb_barang_masuk WHERE id='$id'");
	$r = mysqli_fetch_array($q);
	if ($r) {
		mysqli_query($koneksi, "UPDATE tb_barang SET stok = stok - " . (int)$r['jml_masuk'] . " WHERE kdbarang='" . mysqli_real_escape_string($koneksi, $r['kdbarang']) . "'");
	}
	$query = mysqli_query($koneksi, "DELETE FROM tb_barang_masuk WHERE id='$id'");
	if ($query) {
		header("location: index.php?m=barangmasuk&s=title&msg=hapus_sukses");
	} else {
		header("location: index.php?m=barangmasuk&s=title&msg=gagal");
	}
	exit;
}

// ---------------------------------------------DASHBOARD SECTION-----------------------------------------------------------------\\

function penjualan_terkini()
{
	global $koneksi;
	return mysqli_query($koneksi, "SELECT * FROM laporan_penjualan ORDER BY id DESC LIMIT 5");
}

function barang_terpopuler()
{
	global $koneksi;
	return mysqli_query($koneksi, "SELECT nm_barang, SUM(jumlah_beli) AS total_qty, SUM(total) AS total_omzet FROM laporan_penjualan GROUP BY nm_barang ORDER BY total_qty DESC LIMIT 5");
}

function total_barang_terjual()
{
	global $koneksi;
	$q = mysqli_query($koneksi, "SELECT SUM(jumlah_beli) AS jml FROM laporan_penjualan");
	$r = mysqli_fetch_array($q);
	return (int)($r['jml'] ?? 0);
}

// url
function url()
{
	return "../vendors/";
}

function rupiah($angka){
	$hasil = "Rp. ". number_format($angka, 0, ',', '.');
	return $hasil;
}

 ?>

