<?php
require "conn.php";

// check baki
function baki($id) {
  global $con;
  $m = mysqli_fetch_array(mysqli_query($con, "SELECT SUM(masuk) FROM cwallet WHERE userid = '".$id."'"));
  $masuk = $m[0];
  $k = mysqli_fetch_array(mysqli_query($con, "SELECT SUM(keluar) FROM cwallet WHERE userid = '".$id."'"));
  $keluar = $k[0];
  return $masuk - $keluar;
}

// fix bug date pada server
date_default_timezone_set("Asia/Kuala_Lumpur");
$tarikh = date("Y-m-d H:i:s");

$sql = "SELECT nama, username, id FROM ahli WHERE id NOT IN (1,2,3,4,5)";
$result = mysqli_query($con,$sql);
$j = 1;

while ($row = mysqli_fetch_array($result)) {

  // no, username, nama, bank, noakaun, amaun
  $id = $row[2];
  $bal = baki($id);

  if ($bal >= 10) {

    $amaun = floor(baki($id) / 10) * 10;

    mysqli_query($con, "INSERT INTO cwallet (tarikh, keterangan, rujukan, keluar, userid)
    VALUES ('".$tarikh."', 'Auto Withdrawal', 'admin', ".$amaun.", ".$id.")");

    mysqli_query($con, "INSERT INTO withdraw (userid, amaun, tarikh)
    VALUES ('".$id."', ".$amaun.", '".$tarikh."')");
  }

  unset ($id, $bal, $amaun);
}
