<?php 

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



// summon admin

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

// -------------------------------------USER SECTION--------------------------------------------------------------------
// select user by admin

function select_laporan()
{
	global $koneksi;
	$kasir_nama = mysqli_real_escape_string($koneksi, $_SESSION['namakaskit']);
	return mysqli_query($koneksi, "SELECT * FROM laporan_penjualan WHERE kasir='$kasir_nama' ORDER BY id DESC");
}


// 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 = (int)$_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) {
		echo "username  '%".$username."%' sudah ada";
	}else 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);
      			$result = mysqli_query($koneksi, "INSERT INTO tb_user SET username='$username', password='$password', nama='$nama', level='$level', foto='$nama_file_baru'");
      			
    }



	
	}else if($foto==""){
		return mysqli_query($koneksi, "INSERT INTO tb_user SET username='$username', password='$password', nama='$nama', level='$level'");
	}
}

// delete user

function delete_user()
{
	global $koneksi;
	$id = (int)$_POST['id'];
	$cekimg = mysqli_query($koneksi, "SELECT * FROM tb_user WHERE id='$id'");
	$row = mysqli_fetch_array($cekimg);

	// hapus gambar
	$foto = $row['foto'];
	unlink("img/$foto");
	return mysqli_query($koneksi, "DELETE FROM tb_user WHERE id='$id'");
}

// update user
function update_user()
{
	
	global $koneksi;
	$id = (int)$_POST['id'];
	$username = mysqli_real_escape_string($koneksi, $_POST['username']);
	$password = md5($_POST['password']);
	$nama = mysqli_real_escape_string($koneksi, $_POST['nama']);
	
	$foto = $_FILES['foto']['name'];

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

	$hapus_foto = $row['foto'];
	
	

	// update

	if(isset($_POST['ubahfoto']))
	{
		if ($row['foto']=="") 
		{
				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, '../admin/img/'.$nama_file_baru);
		      			$result =  mysqli_query($koneksi, "UPDATE tb_user SET username='$username', password='$password', nama='$nama', foto='$nama_file_baru' WHERE id='$id'");
		      			
		      			
		    }



			}
		}else if ($row['foto']!="") {
			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, '../admin/img/'.$nama_file_baru);
		      			$result =  mysqli_query($koneksi, "UPDATE tb_user SET username='$username', password='$password', nama='$nama', foto='$nama_file_baru' WHERE id='$id'");
		      			if ($result) {
		      				unlink("../admin/img/$hapus_foto");
		      			}

		      			
		    }



			}
		}	
	}

	if (empty($_POST['foto'])) {
		return  mysqli_query($koneksi, "UPDATE tb_user SET username='$username', password='$password', nama='$nama' WHERE id='$id'");
	}

}

// ---------------------------------------------------TRANSAKSI SECTION----------------------------------------------------------
function insert_transaksi()
{
	global $koneksi;
	$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']);
	$total = (int)$_POST['harga'];

	$tanggal = mysqli_real_escape_string($koneksi, $_POST['tanggal']);
	$jam = mysqli_real_escape_string($koneksi, $_POST['jam']);
	$kasir = mysqli_real_escape_string($koneksi, $_POST['kasir']);

	//validasi

	$kasir_id = (int)$_SESSION['idkaskit'];

	$select  = mysqli_query($koneksi, "SELECT * FROM transaksi_temp WHERE kdbarang = '$kdbarang' AND kasir_id='$kasir_id'");
	$row = mysqli_fetch_row($select);

	if ($row) {
		$query1 = mysqli_query($koneksi, "UPDATE transaksi_temp SET jumlah_beli = jumlah_beli + 1, total = total + '$total' WHERE kdbarang = '$kdbarang' AND kasir_id='$kasir_id'");
	}else{
		$query1 =  mysqli_query($koneksi, "INSERT INTO transaksi_temp SET kdbarang='$kdbarang', nm_barang='$nm_barang', kategori='$kategori', jumlah_beli=1, total='$total', kasir_id='$kasir_id'");
	}

	

}

function proses_checkout($total_bayar, $jumlah_bayar, $kembalian, $diskon)
{
    global $koneksi;
    $kasir_id = (int)$_SESSION['idkaskit'];
    $kasir_nama = mysqli_real_escape_string($koneksi, $_SESSION['namakaskit']);
    $tanggal = date("Y-m-d");
    $jam = date("H:i:s");
    
    // Generate invoice number
    $q_inv = mysqli_query($koneksi, "SELECT MAX(id) as max_id FROM laporan_penjualan");
    $r_inv = mysqli_fetch_array($q_inv);
    $next_id = ($r_inv['max_id'] ? $r_inv['max_id'] : 0) + 1;
    $no_inv = "INV/" . date('Ymd') . "/" . sprintf("%04s", $next_id);
    
    // Get all cart items
    $cart = mysqli_query($koneksi, "SELECT * FROM transaksi_temp WHERE kasir_id='$kasir_id'");
    
    while ($item = mysqli_fetch_array($cart)) {
        $kdbarang = mysqli_real_escape_string($koneksi, $item['kdbarang']);
        $nm_barang = mysqli_real_escape_string($koneksi, $item['nm_barang']);
        $kategori = mysqli_real_escape_string($koneksi, $item['kategori']);
        $jumlah_beli = (int)$item['jumlah_beli'];
        $subtotal = (int)$item['total'];
        
        // Get current stock
        $q_stok = mysqli_query($koneksi, "SELECT stok FROM tb_barang WHERE kdbarang='$kdbarang'");
        $r_stok = mysqli_fetch_array($q_stok);
        $stok_sekarang = $r_stok ? (int)$r_stok['stok'] : 0;
        $stok_baru = max(0, $stok_sekarang - $jumlah_beli);
        
        // Decrement stock
        mysqli_query($koneksi, "UPDATE tb_barang SET stok='$stok_baru' WHERE kdbarang='$kdbarang'");
        
        // Insert into laporan_penjualan (NOW at checkout time!)
        $no_inv_esc = mysqli_real_escape_string($koneksi, $no_inv);
        mysqli_query($koneksi, "INSERT INTO laporan_penjualan SET no_inv='$no_inv_esc', kdbarang='$kdbarang', nm_barang='$nm_barang', kategori='$kategori', jumlah_beli='$jumlah_beli', total='$subtotal', tanggal='$tanggal', jam='$jam', kasir='$kasir_nama'");
        
        // Log activity
        $log_msg = mysqli_real_escape_string($koneksi, "Penjualan: $nm_barang x$jumlah_beli (Rp " . number_format($subtotal, 0, ',', '.') . ")");
        mysqli_query($koneksi, "INSERT INTO activity_log SET user_id='$kasir_id', action='transaksi', detail='$log_msg', tanggal='$tanggal', jam='$jam'");
    }
    
    // Record the payment with discount
    $total_bayar_int = (int)$total_bayar;
    $jumlah_bayar_int = (int)$jumlah_bayar;
    $kembalian_int = (int)$kembalian;
    $diskon_int = (int)$diskon;
    
    $log_payment = mysqli_real_escape_string($koneksi, "Pembayaran: Total Rp " . number_format($total_bayar_int, 0, ',', '.') . ", Bayar Rp " . number_format($jumlah_bayar_int, 0, ',', '.') . ", Diskon Rp " . number_format($diskon_int, 0, ',', '.') . ", Kembali Rp " . number_format($kembalian_int, 0, ',', '.') . " (No. $no_inv)");
    mysqli_query($koneksi, "INSERT INTO activity_log SET user_id='$kasir_id', action='pembayaran', detail='$log_payment', tanggal='$tanggal', jam='$jam'");
    
    // Clear cart
    mysqli_query($koneksi, "DELETE FROM transaksi_temp WHERE kasir_id='$kasir_id'");
    
    return $no_inv;
}
// url
function url()
{
	return "../vendors/";
}

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

 ?>

