<?php
//include '../koneksi.php';
//$id_angg    = $_POST['tid'];

function generateKodeUnik($length = 6) {
  $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  $kode = '';
  for ($i = 0; $i < $length; $i++) {
    $kode .= $characters[rand(0, strlen($characters) - 1)];
  }
  return $kode;
}

function cekKodeUnik($conn, $kode) {
  $query = "SELECT * FROM kode_unik WHERE kode = '$kode'";
  $result = mysqli_query($conn, $query);
  if (mysqli_num_rows($result) > 0) {
    return false;
  } else {
    return true;
  }
}

function simpanKodeUnik($conn, $kode) {
  $query = "INSERT INTO kode_unik (kode) VALUES ('$kode')";
  mysqli_query($conn, $query);
}

$conn = mysqli_connect("mitrakoperasi.com", "mitrakop_kopdes_us_01_001_001", "Paktris4464100%", "mitrakop_kopdes_01_001_001");

if (!$conn) {
  die("Koneksi gagal: " . mysqli_connect_error());
}

$kode = generateKodeUnik();
while (!cekKodeUnik($conn, $kode)) {
  $kode = generateKodeUnik();
}
simpanKodeUnik($conn, $kode);
?>