<?php
session_start();

$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";    
?>
        <div id="page-wrapper" >
            <div id="page-inner">
                <div class="row">
                    <div class="col-md-12">
                     <h2>Registration</h2>                          
                    </div>
                </div>
            <hr />
<?
// Ambil PIN dari GET (jika ada)
$pin = mysqli_real_escape_string($con, $_GET['pin'] ?? '');

// PIN value dari komisen
$rowPv = mysqli_fetch_array(mysqli_query($con, "SELECT nilaipin FROM komisen"));
$pv = $rowPv['nilaipin'] ?? 0;

// Kira berapa banyak PIN available untuk user login
$userId = (int)($_SESSION['aidi'] ?? 0);
$sql_pin = "SELECT no FROM bestpin WHERE userid = $userId AND status = 0 ORDER BY datesold ASC";
$res_pin = mysqli_query($con, $sql_pin);

// Simpan semua PIN available user dalam array
$availablePins = [];
while ($row = mysqli_fetch_assoc($res_pin)) {
    $availablePins[] = $row['no'];
}
$totalPin = count($availablePins);

// Jumlah nilai kredit PIN
$totalCredit = $totalPin * $pv;

    	
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['package'])) {

?>
                <div class="row" >

                    <div class="col-md-12 col-sm-12 col-xs-12">

                    <div class="panel panel-default">
                        <div class="panel-heading">
                           New Registration
                        </div>
                        <div class="panel-body">
                            <div class="table-responsive">
                                <form method="post" action="">
                                <label >Choose Package</label>
                                <div style="display:flex; gap:15px; flex-wrap:wrap;">
<?php
                                        // Ambil senarai packages
                                        $sql = "SELECT * FROM packages ORDER BY price ASC";
                                        $result = mysqli_query($con, $sql);
                                        
                                        while ($p = mysqli_fetch_assoc($result)) {
                                            $pinNeeded = ceil($p['price'] / $pv);  // berapa pin diperlukan untuk pakej ini
                                            $enough    = ($totalCredit >= $p['price'] && $totalPin >= $pinNeeded);
                                            $disabled  = $enough ? "" : "disabled";
                                            $dimStyle  = $enough ? "" : "opacity:0.5; pointer-events:none;";
                                        
                                            // Ambil PIN yang diperlukan untuk pakej ini
                                            $usePins = array_slice($availablePins, 0, $pinNeeded);
                                            ?>
                                            <button type="submit" name="package" value="<?= $p['id'] ?>" class="col-md-4 " 
                                                   style="flex:1; cursor:pointer; background:#87B6C9; border:2px solid #eee; border-radius:10px; padding:15px; text-align:center; <?= $dimStyle ?>">
                                        
                                                <!-- Package Name -->
                                                <div style="font-weight:bold; font-size:16px; margin-bottom:8px; color:#333;">
                                                    <?= htmlspecialchars($p['name']) ?>
                                                </div>
                                        
                                                <!-- Logo -->
                                                <div style="color:#555;">
                                                    <img src="assets2/ico/tls2u.png" height="55" width="auto" alt="TLS2U.COM">
                                                </div>
                                        
                                                <!-- Quantity -->
                                                <div style="font-weight:bold; color:#FFF; font-size:10px;">
                                                    ( <?= $p['qty_set'] ?> PAX )
                                                </div>
                                        
                                                <!-- Price -->
                                                <div style="font-weight:bold; color:#FFF; font-size:20px;">
                                                    <span class="small">RM</span> <?= number_format($p['price'], 2) ?>
                                                </div>
                                        
                                                <!-- PIN Info -->
                                                <div style="margin-top:8px; font-weight:100; font-size:10px; color:#fff;"><span class="badge" style="padding:5px; background-color:white;"> <i class="fas fa-key text-danger"></i></span> 
                                                    Required: <span style="color:red; font-weight:300; font-size:14px;"><?= $pinNeeded ?></span>  | 
                                                    Available: <span style="color:red; font-weight:300; font-size:14px;"><?= $totalPin ?></span>   
                                                </div>
                                        
                                                <?php if ($enough): ?>
                                                    <div style="margin-top:5px; font-weight:100; font-size:11px; color:#fff; text-align:center;">
                                                        <?php 
                                                        foreach ($usePins as $up) {
                                                            // echo "• $up ";
                                                            // hidden input untuk hantar ke POST
                                                            echo '<input type="hidden" name="pins[]" value="'.$up.'">';
                                                        }
                                                        ?>
                                                    </div>
                                                <?php else: ?>
                                                    <div style="color:red; font-size:12px; margin-top:8px;">
                                                        Not enough PIN
                                                    </div>
                                                <?php endif; ?>
                                            </button>
                                            <?php
                                        }
?>
                                </div>
                                </form>
                                <label style="padding-top: 30px;">Available PIN</label>
                                <table class="table table-striped table-bordered table-hover">
                                    <thead>
                                        <tr>
                                            <th>#</th>
                                            <th>No</th>
                                            <th>Date / Time Generated</th>
                                            <th>Status</th>
                                        </tr>
                                    </thead>
                                    <tbody>
<?php
                                        $sql = "SELECT no, datesold FROM bestpin WHERE userid = ".$_SESSION['aidi']." AND status = 0";
                                        $result = mysqli_query($con, $sql);
                                        $c = 1;
                                        while ($row = mysqli_fetch_array($result)) {
?>
                                            <tr>
                                                <td><?= $c++ ?></td>
                                                <td><?= $row[0] ?></td>
                                                <td><?= $row[1] ?></td>
                                                <td><span class="btn btn-success btn-xs">Active</span></td>
                                            </tr>
                                        <? } ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                    </div>
                </div>
<?
} else {

    $packageId = $_POST['package'];

    // Ambil package info
    $sql = "SELECT * FROM packages WHERE id = $packageId";
    $p = mysqli_fetch_assoc(mysqli_query($con, $sql));
    $pinNeeded = ceil($p['price'] / $pv);
    
    // Ambil PIN yang betul-betul digunakan
    $pinsUsed = array_slice($availablePins, 0, $pinNeeded);
    
    // Semak setiap PIN
    $invalidPin = false;
    foreach ($pinsUsed as $pinCheck) {
        if (chkPin($pinCheck) != 1) {
            $invalidPin = true;
            break;
        }
    }
    
    if ($invalidPin) {
        echo '<div class="alert alert-danger">';
        echo 'Error! Wrong PIN.';
        echo '</div>';
        goto kaki;
    }

?>
<script type="text/javascript">
    function ValidateUsername() {
        var username = document.getElementById("txtUsername").value;
        var lblError = document.getElementById("lblError");
        lblError.innerHTML = "";
        var expr = /^[a-zA-Z0-9_]*$/;
        if (!expr.test(username)) {
            lblError.innerHTML = "Only Alphabets, Numbers, Underscore allowed in Username.";
            event.preventDefault(); // tambahan
        }
    }
</script>

<?php
            // Check Number Sponsor - Limit Sponsor (Limitkan Sponsor) 
            
            $s_limit_sql = mysqli_fetch_array(mysqli_query($con, "SELECT sponsor_limit FROM setting"));
            $s_limit = $s_limit_sql['sponsor_limit'];
            
            $s_num_sql = mysqli_num_rows(mysqli_query($con, "SELECT id FROM ahli WHERE penaja = '".$_SESSION['aidi']."'"));
            $s_num = $s_num_sql;

            if ($s_limit == 0) {
                $dis = "";
            }
            else    {
                if ($s_num >= $s_limit) {
                    $dis = "disabled";
                    noTis("danger", "Notice ", " Your account reach a maximum sponsor limit."); 
                }   
                else {
                    $dis = "";
                } 
            }
            
            
            
            
            
           

?>
			<div class="row">
                <div class="col-md-12">
                    <!-- Form Elements -->
                    <div class="panel panel-default">
                        <div class="panel-heading">
                            Register New Member 	
                        </div>
                        <div class="panel-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <form role="form" method="post" action="register.php" onsubmit="return ValidateUsername();">
                                        <div class="form-group">
                                            <label class="form-label"><strong>Package</strong></label>
                                            <div style="display:flex; gap:15px; flex-wrap:wrap;">
                            
                                            <?php

                                            $sql = "SELECT * FROM packages WHERE id = $packageId";
                                            $result = mysqli_query($con, $sql);
                            
                                            while ($p = mysqli_fetch_assoc($result)) {
                                                ?>
                                                <label type="submit" name="package" class="col-md-4" 
                                                       style="flex:1; border:2px solid #eee; border-radius:10px; background:#87B6C9; padding:15px; text-align:center;">
                                            
                                                    <!-- Package Name -->
                                                    <div style="font-weight:bold; font-size:16px; margin-bottom:8px; color:#333;">
                                                        <input type="number" name="i" value="<?= $p['id'] ?>" required>
                                                        <?= htmlspecialchars($p['name']) ?>
                                                    </div>
                                            
                                                    <!-- Logo -->
                                                    <div style="color:#555;">
                                                        <img src="assets2/ico/tls2u.png" height="55" width="auto" alt="TLS2U.COM">
                                                    </div>
                                            
                                                    <!-- Quantity -->
                                                    <div style="font-weight:bold; color:#FFF; font-size:10px;">
                                                        ( <?= $p['qty_set'] ?> PAX )
                                                    </div>
                                            
                                                    <!-- Price -->
                                                    <div style="font-weight:bold; color:#FFF; font-size:20px;">
                                                        <span class="small">RM</span> <?= number_format($p['price'], 2) ?>
                                                    </div>
                                            
                                                    <div style="margin-top:5px; font-weight:100; font-size:11px; color:#fff; text-align:center;">
                                                        <?php 
                                                            foreach ($pinsUsed as $pin) {
                                                                echo "• $pin ";   // paparkan PIN pada button/form
                                                                echo '<input type="hidden" name="g[]" value="'.$pin.'">'; // hantar setiap PIN sebagai array
                                                            }
                                                        ?>
                                                    </div>
                                            </label>
<?php
                                            }
?>
                            
                                            </div>
                                        </div>
                                        
                                        <div class="form-group">
                                            <label>Name</label>
                                            <input class="form-control" name="a" placeholder="Full Name" required <?= $dis; ?>/>
                                        </div>
                                        <div class="form-group">
                                            <label>Phone</label>
                                            <input class="form-control" name="b" placeholder="your mobile phone no." required <?= $dis; ?>/>
                                        </div>
                                        <div class="form-group">
                                            <label>Email</label>
                                            <input class="form-control" type="email" name="c" placeholder="valid email only" required <?= $dis; ?>/>
                                        </div>
                                        <div class="form-group">
                                            <label>MyKad</label>
                                            <input class="form-control" name="d" placeholder="your MyKad no." required <?= $dis; ?>/>
                                        </div>
                                        <div class="form-group">
                                            <label>Username</label>
                                            <input class="form-control" name="e" id="txtUsername" required <?= $dis; ?>/>
                                            <span id="lblError" style="color: red"></span>
                                        </div>
                            <!--            <div class="form-group">
                                            <label>PIN</label>
                                            <?php //foreach($pinsUsed as $p): ?>
                                                        <input class="form-control" type="text" name="g[]" value="<?= htmlspecialchars($p) ?>" readonly />
                                            <?php // endforeach; ?>
                                       </div>
                            --> 
                                        <button type="submit" id="btnValidate" name="h" class="btn btn-primary" <?= $dis; ?>>Register</button>

                                    </form>

                                </div>
                            </div>
                        </div>
                    </div>
                     <!-- End Form Elements -->
                </div>

			</div>
			
			
<?
	}	
?>

             <!-- /. PAGE INNER  -->
<? kaki: ?>			 
            </div>
         <!-- /. PAGE WRAPPER  -->
        </div>
<?
    include "_footer.php";
}
?>
