<?php
session_start();

if (isset($_SESSION['flash_message'])) {
    if ( ($_SESSION['flash_message']) == 'Registration successful!' )   {
            unset($_SESSION['flash_message']);
            header("Location: registration.php?status=success");
            exit;
    }   else    {
            unset($_SESSION['flash_message']);
            header("Location: registration.php?status=fail");
            exit;
    }  
}

$key = md5(date("Y-m-d").":".$_SERVER['REMOTE_ADDR']);
if (isset($_SESSION['aW1iZXN0cmEuY29tLm15']) <> $key) {
    header("location:".$_SERVER['REQUEST_SCHEME']."://".$_SERVER['SERVER_NAME']); // cara baru !
} else {
    include "_header.php";
    include "_navtop.php";
    include "_navside.php";
    include "_functions.php";
    require "conn.php";	


    // -----------------------------------
    // pendaftaran ahli biasa
    // -----------------------------------
    if (isset($_POST['h'])) {





    $nama       = mysqli_real_escape_string($con, $_POST['a']);
    $telefon    = mysqli_real_escape_string($con, $_POST['b']);
    $email      = mysqli_real_escape_string($con, $_POST['c']);
    $mykad      = mysqli_real_escape_string($con, $_POST['d']);
    $usrnm      = mysqli_real_escape_string($con, $_POST['e']);
    $package    = (int)($_POST['i'] ?? 0); // force integer
    $pins       = $_POST['g'] ?? []; // array of pins

    $pswd   = randomPass();
    $penaja = $_SESSION['aidi'];
    date_default_timezone_set("Asia/Kuala_Lumpur");
    $tarikh = date("Y-m-d H:i:s");

    // Validate all PINs
    foreach ($pins as $pin) {
        $pin = mysqli_real_escape_string($con, $pin);

        if (chkPin($pin) == 0) {
            noTis("danger", "Error", "Wrong PIN: $pin");
            goto kaki;
        }

        if (reKod("status", "bestpin", "no", $pin) == 1) {
            noTis("danger", "Error", "PIN $pin has expired.");
            goto kaki;
        }
    }
        
        $sql    = "SELECT * FROM packages WHERE id = $package";
        $result = mysqli_query($con, $sql);
        while ($p = mysqli_fetch_assoc($result)) {
            $directSponsor  = number_format($p['direct_sponsor'], 2);
            $pakejName      = $p['name'];
            $commLevel      = $p['commission_level'];
        }

?>
        <div id="page-wrapper" >
            <div id="page-inner">
                <div class="row">
                    <div class="col-md-12">
                     <h2>Registration</h2>                          
                    </div>
                </div>
<?

            if (chkUsr($usrnm) == 1) {
                $_SESSION['flash_message'] = "Registration fail !";
                noTis("danger", "Error", "Username already exists.");
            } else {
                
                $spl            = mysqli_fetch_array(mysqli_query($con, "SELECT * FROM setting"));
                $multipleAcc    = (int)$spl['multiple_acc'];
                $mykadCount     = chkAny("kp", $mykad); // jumlah akaun dengan MyKad ini
                
                if ($multipleAcc == 0 || $mykadCount < $multipleAcc) {

                    require "conn2.php";
                    include "_register.php";
                    include "_sms_registration.php";
                    include "_phpmailer.php";
                    

                    //mysqli_query($con, "UPDATE bestpin SET dateactive='".$tarikh."', status=1 WHERE no='".$pin."'");
                    // ✅ Update all used PINs to status=1
                    foreach ($pins as $pin) {
                        mysqli_query($con, "UPDATE bestpin SET dateactive = '$tarikh', status = 1 WHERE no = '$pin'");
                    }
                    
                        
                    // -----------------------------------
                    // bonus unilevel dinamik
                    // -----------------------------------
                    $r = mysqli_fetch_assoc(mysqli_query($con, "SELECT * FROM komisen WHERE id=1"));

                    $maxLevel = 0;
                    $bonusLevels = [];
                    foreach($r as $key => $value) {
                        if(strpos($key, 'lvl') === 0) {
                            $lvlNum = intval(substr($key, 3));
                            $bonusLevels[$lvlNum] = $value;
                            if($lvlNum > $maxLevel) $maxLevel = $lvlNum;
                        }
                    }

                    $penajaNow = $penaja;
                    $senaraiPenaja = [];
                    $jumlahBonus = 0;

                    for($level=1; $level <= $maxLevel; $level++) {
                        if(!$penajaNow) break;


                        if(bolehDapatBonus($con, $penajaNow, $level)) {
                            $bonus = $bonusLevels[$level] ?? 0;
                        
                            // dapatkan username penaja sekarang
                            $penajaUsername = '';
                            $res = mysqli_query($con, "SELECT * FROM ahli WHERE id = $penajaNow LIMIT 1");
                            if($res && mysqli_num_rows($res) > 0) {
                                $rowU = mysqli_fetch_assoc($res);
                                $penajaUsername = $rowU['username'];
                                $phone = $rowU['telefon'];
                            }
                        
                            // hanya insert kalau bukan admin
                            if($penajaUsername != 'admin') {
                                mysqli_query($con, "INSERT INTO cwallet (tarikh, keterangan, rujukan, masuk, userid)
                                    VALUES (
                                        '".$tarikh."', 
                                        'Bonus Level ".$level." : RM ".$bonus." for ".$penajaUsername."', 
                                        '".$usrnm."', 
                                        ".$bonus.", 
                                        ".$penajaNow."
                                    )");
                        
                                $jumlahBonus += $bonus;
                                $senaraiPenaja[] = $penajaNow;
                                include "_sms_bonus_level.php";
                            }
                        }


                        $penajaNow = getFieldValue("penaja", "ahli", "id", $penajaNow);
                    }

                    if(count($senaraiPenaja) > 0) {
                        $senaraiStr = implode(",", $senaraiPenaja);
                        $sql = "SELECT GROUP_CONCAT(username) FROM ahli WHERE id IN ($senaraiStr)";
                        $row = mysqli_fetch_array(mysqli_query($con, $sql));

                        $output = logSub($tarikh, 2, $usrnm." account registration. Bonus for ".$row[0], $jumlahBonus);
                        if (!$output) {
                            echo mysqli_error($con);
                        }
                    }


                } else {
                    $_SESSION['flash_message'] = "Registration fail !";
                    noTis("danger", "Error", " That MyKad number is already registered or has reached the maximum account limit ($multipleAcc). Please use a different MyKad or contact support.");
                }
            } 					
        		
    }    

    // -----------------------------------
    // pendaftaran merchant
    // -----------------------------------
    if (isset($_POST['reg_merchant'])) {

        $nama       = mysqli_real_escape_string($con, $_POST['a']);
        $telefon    = mysqli_real_escape_string($con, $_POST['b']);
        $email      = mysqli_real_escape_string($con, $_POST['c']);
        $roc        = mysqli_real_escape_string($con, $_POST['d']);
        $usrnm      = mysqli_real_escape_string($con, $_POST['e']);
        $pin        = mysqli_real_escape_string($con, $_POST['g']);

        $pswd = randomPass();
        $penaja = $_SESSION['aidi'];

        date_default_timezone_set("Asia/Kuala_Lumpur");
        $tarikh = date("Y-m-d H:i:s");
?>
        <div id="page-wrapper" >
            <div id="page-inner">
                <div class="row">
                    <div class="col-md-12">
                     <h2>Registration</h2>                          
                    </div>
                </div>
<?
        if (chkUsrMerchant($usrnm) == 1) {
            noTis("danger", "Error", "Username already exists.");
        } else {
            if (chkAnyRoc("roc", $roc) == 0) {

                require "conn2.php";
                include "_register_merchant.php";
                include "_phpmailer.php";

            } else {
                noTis("danger", "Error", "Your account already exists.");
            }
        } 					
    }   
	
kaki:
?>			 
            </div>
         <!-- /. PAGE WRAPPER  -->
        </div>
<?
    include "_footer.php";
}
?>
