<?
if (count(get_included_files()) ==1) die("<h4>You don't have right permission to access this file directly.</h4>");

// check baki
function sumWall($col, $table) {
  global $con;
  $res = mysqli_fetch_array(mysqli_query($con, "SELECT SUM(".$col.") FROM ".$table." WHERE userid = '".$_SESSION['aidi']."'"));
  return $res[0];
}

// check baki
function MsumWall($col, $table) {
  global $con;
  $res = mysqli_fetch_array(mysqli_query($con, "SELECT SUM(".$col.") FROM ".$table." WHERE merchant_id = '".$_SESSION['aidi']."'"));
  return $res[0];
}

// check baki dari ID
function jumLah($col, $table, $id) {
  global $con;
  $res = mysqli_fetch_array(mysqli_query($con, "SELECT SUM(".$col.") FROM ".$table." WHERE userid = '".$id."'"));
  return $res[0];
}

/*
$cwallet = sumWall("masuk", "cwallet") - sumWall("keluar", "cwallet");
$rwallet = sumWall("masuk", "rwallet") - sumWall("keluar", "rwallet");
$gwallet = sumWall("masuk", "gwallet") - sumWall("keluar", "gwallet");
$mwallet = sumWall("masuk", "mwallet") - sumWall("keluar", "mwallet");
*/

function reKod($col1, $table, $col2, $input) {
  global $con;
  $hasil = mysqli_fetch_array(mysqli_query($con, "SELECT ".$col1." FROM ".$table." WHERE ".$col2." = '".$input."'"));
  return $hasil[0];
}


function telUser($input) {
    global $con;
    $sql = "SELECT telefon, username, sms FROM ahli WHERE id = '".mysqli_real_escape_string($con, $input)."' LIMIT 1";
    $r = mysqli_fetch_array(mysqli_query($con, $sql));
    if ($r) {
        return $r['telefon'] . "|" . $r['username'] . "|" . $r['sms'];
    }
    return null;
}



function chkPenaja($p) {
  global $con;
  return mysqli_num_rows(mysqli_query($con, "SELECT id FROM ahli WHERE kp = '".$p."'"));
}

function chkPin($n) {
  global $con;
  return mysqli_num_rows(mysqli_query($con, "SELECT id FROM bestpin WHERE no = '".$n."'"));
}

function chkRid($d) {
  global $con;
  return mysqli_num_rows(mysqli_query($con, "SELECT * FROM bestpin WHERE id = '".$d."'"));
}

function chkUsr($x) {
  global $con;
  return mysqli_num_rows(mysqli_query($con, "SELECT id FROM ahli WHERE username = '".$x."'"));
}

function chkAny($field, $input) {
  global $con;
  return mysqli_num_rows(mysqli_query($con, "SELECT id FROM ahli WHERE ".$field." = '".$input."'"));
}

function chkUsrMerchant($x) {
  global $con;
  return mysqli_num_rows(mysqli_query($con, "SELECT id FROM merchant WHERE username = '".$x."'"));
}

function chkAnyRoc($field, $input) {
  global $con;
  return mysqli_num_rows(mysqli_query($con, "SELECT id FROM merchant WHERE ".$field." = '".$input."'"));
}

function chkSMS() {
    global $con;
    $row = mysqli_fetch_array(mysqli_query($con, "SELECT sms_balance FROM setting"));
    return $row['sms_balance'];
}

/*
function strCom($data) {
  str_replace(array('register', 'company'), array('daftar', 'company'), array('malaysia', 'company'), array('registration', 'company'), $data);
}
*/
function logSub($tarikh, $jenis, $keterangan, $amaun) {
  global $con;
  mysqli_query($con, "INSERT INTO `log` (tarikh, jenis, keterangan, amaun) 
  VALUES ('".$tarikh."', '".$jenis."', '".$keterangan."', '".$amaun."')");  
}

function mysqli_result($result,$row,$field=0) {
    if ($result===false) return false;
    if ($row>=mysqli_num_rows($result)) return false;
    if (is_string($field) && !(strpos($field,".")===false)) {
        $t_field=explode(".",$field);
        $field=-1;
        $t_fields=mysqli_fetch_fields($result);
        for ($id=0;$id<mysqli_num_fields($result);$id++) {
            if ($t_fields[$id]->table==$t_field[0] && $t_fields[$id]->name==$t_field[1]) {
                $field=$id;
                break;
            }
        }
        if ($field==-1) return false;
    }
    mysqli_data_seek($result,$row);
    $line=mysqli_fetch_array($result);
    return isset($line[$field])?$line[$field]:false;
}


function randomPass() {
  $len = 5;
  $base = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
  $max = strlen($base)-1;
  $activatecode = '';
  mt_srand((double)microtime()*1000000);
  while (strlen($activatecode)<$len+1)
  //$activatecode .= $base{mt_rand(0,$max)};
  $activatecode .= $base[mt_rand(0,$max)];
  return $activatecode;
}


function randomPin() {
  $len = 9;
  $base = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
  $max = strlen($base)-1;
  $activatecode = '';
  mt_srand((double)microtime()*1000000);
  while (strlen($activatecode)<$len+1)
  //$activatecode .= $base{mt_rand(0,$max)};
  $activatecode .= $base[mt_rand(0,$max)];
  return $activatecode;
}

function noTis($jenis, $bold, $pengumuman) {
  echo "<div>";
  echo "  <div class=\"alert alert-".$jenis."\">\n";
  echo "    <strong>".$bold."!</strong> ".$pengumuman."\n";
  echo "  </div>\n";
  echo "</div>";
}







/* ===============================
   CRUD FUNCTIONS FOR PACKAGES
   =============================== */

// CREATE
function addPackage($name, $price, $qty_set, $direct_sponsor, $commission_level, $items = null) {
    global $con;
    $stmt = $con->prepare("INSERT INTO packages (name, price, qty_set, direct_sponsor, commission_level, items) VALUES (?,?,?,?,?,?)");
    $stmt->bind_param("sdiids", $name, $price, $qty_set, $direct_sponsor, $commission_level, $items);
    $stmt->execute();
    $stmt->close();
}

// READ all
function getPackages() {
    global $con;
    $result = $con->query("SELECT * FROM packages ORDER BY price ASC");
    $packages = [];
    while($row = $result->fetch_assoc()) {
        $packages[] = $row;
    }
    return $packages;
}

// READ single
function getPackageById($id) {
    global $con;
    $stmt = $con->prepare("SELECT * FROM packages WHERE id=?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();
    $data = $result->fetch_assoc();
    $stmt->close();
    return $data;
}

// UPDATE
function updatePackage($id, $name, $price, $qty_set, $direct_sponsor, $commission_level, $items = null) {
    global $con;
    $stmt = $con->prepare("UPDATE packages SET name=?, price=?, qty_set=?, direct_sponsor=?, commission_level=?, items=? WHERE id=?");
    $stmt->bind_param("sdiidsi", $name, $price, $qty_set, $direct_sponsor, $commission_level, $items, $id);
    $stmt->execute();
    $stmt->close();
}

// DELETE
function deletePackage($id) {
    global $con;
    $stmt = $con->prepare("DELETE FROM packages WHERE id=?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $stmt->close();
}

/* ===============================
   DISPLAY FUNCTION
   =============================== */
function displayPackagesRadio($selected = null) {
    $packages = getPackages();
    echo '<div class="form-group">
            <label class="form-label"><strong>Select Package</strong></label>
            <div style="display:flex; gap:15px; flex-wrap:wrap;">';
    
    foreach ($packages as $p) {
        $checked = ($selected == $p['id']) ? "checked" : "";
        echo '<label style="flex:1; cursor:pointer; border:2px solid #eee; border-radius:10px; padding:15px; text-align:center;">
                <input type="radio" name="package" value="'.$p['id'].'" '.$checked.' required>
                <div style="color:#555;"><img src="assets2/ico/tls2u.png" height="55px" width="auto" alt="TLS2U.COM"></div>
                <div style="font-weight:bold;">x '.$p['qty_set'].'pcs</div>
                <div style="color:#555;">RM '.number_format($p['price'], 2).'</div>
              </label>';
    }

    echo '  </div>
          </div>';
}


    // ------------------------------
    // fungsi helper baru
    // ------------------------------
    function getFieldValue($col1, $table, $col2, $input) {
        global $con;
        $sql = "SELECT $col1 FROM $table WHERE $col2 = '".mysqli_real_escape_string($con, $input)."' LIMIT 1";
        $q = mysqli_query($con, $sql);
        if($q && mysqli_num_rows($q) > 0) {
            $row = mysqli_fetch_array($q);
            return $row[0];
        }
        return null;
    }

    function bolehDapatBonus($con, $userid, $level) {
        $q = mysqli_query($con, "SELECT pakej FROM ahli WHERE id='$userid'");
        if(!$q || mysqli_num_rows($q)==0) return false;
        $row = mysqli_fetch_assoc($q);
        $pakej = $row['pakej'];

        $p = mysqli_query($con, "SELECT commission_level FROM packages WHERE name='$pakej'");
        if(!$p || mysqli_num_rows($p)==0) return false;
        $pkg = mysqli_fetch_assoc($p);

        return ($level <= $pkg['commission_level']);
    }



?>