<?
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 randomPass($len = 5) {
    $base = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
    $max = strlen($base) - 1;
    $activatecode = '';

    while (strlen($activatecode) < $len) {
        $activatecode .= $base[random_int(0, $max)]; // cryptographically secure
    }
    return $activatecode;
}

function registration($paymentMethod) {
    global $con;

    // --------------------------
    // Use Malaysia time
    // --------------------------
    date_default_timezone_set('Asia/Kuala_Lumpur');

    // --------------------------
    // Sanitize and collect input
    // --------------------------
    $nama       = mysqli_real_escape_string($con, $_POST['nama']);
    $kp         = mysqli_real_escape_string($con, $_POST['kp']);
    $alamat     = mysqli_real_escape_string($con, $_POST['alamat']);
    $poskod     = mysqli_real_escape_string($con, $_POST['poskod']);
    $bandar     = mysqli_real_escape_string($con, $_POST['bandar']);
    $negeri     = mysqli_real_escape_string($con, $_POST['negeri']);
    $negara     = "Malaysia"; // default since not in form
    $telefon    = mysqli_real_escape_string($con, $_POST['telefon']);
    $email      = mysqli_real_escape_string($con, $_POST['email']);
    $username   = mysqli_real_escape_string($con, $_POST['username']);
    
    $bank       = mysqli_real_escape_string($con, $_POST['bank']);
    $naakaun    = mysqli_real_escape_string($con, $_POST['naakaun']);
    $noakaun    = mysqli_real_escape_string($con, $_POST['noakaun']);
    $bnama      = mysqli_real_escape_string($con, $_POST['bnama']);
    $bkp        = mysqli_real_escape_string($con, $_POST['bkp']);
    $brelation  = mysqli_real_escape_string($con, $_POST['brelation']);
    
    $pakej      = mysqli_real_escape_string($con, $_POST['package_name'] ?? '');

    // --------------------------
    // Auto values
    // --------------------------
    $penaja         = $_SESSION['aidi']; // sponsor from session
    $ref_id         = strtoupper(substr(md5(uniqid(rand(), true)), 0, 8));
    $plainPassword  = randomPass();
    $status         = 'inactive';
    $tarikh         = date("Y-m-d H:i:s");

    // --------------------------
    // Handle profile photo upload
    // --------------------------
    $profilePath = null;
    if (!empty($_FILES['profile_photo']['name'])) {
        $targetDir = "uploads/profile/";
        if (!file_exists($targetDir)) mkdir($targetDir, 0777, true);

        $ext = pathinfo($_FILES['profile_photo']['name'], PATHINFO_EXTENSION);
        $filename = $username . "." . strtolower($ext);
        $targetFile = $targetDir . $filename;

        if (move_uploaded_file($_FILES['profile_photo']['tmp_name'], $targetFile)) {
            $profilePath = $targetFile;
        }
    }



    if (chkUsr($username) == 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", $kp); // jumlah akaun dengan MyKad ini
                
                if ($multipleAcc == 0 || $mykadCount < $multipleAcc) {

                    // --------------------------
                    // Insert member record
                    // --------------------------
                    $stmt = $con->prepare("INSERT INTO ahli 
                        (ref_id, nama, kp, alamat, bandar, poskod, negeri, negara, telefon, email, tarikh, penaja, username, password, status, bank, naakaun, noakaun, bnama, bkp, brelation, pakej, photo)
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                
                    $stmt->bind_param(
                        "sssssssssssssssssssssss",
                        $ref_id,
                        $nama,
                        $kp,
                        $alamat,
                        $bandar,
                        $poskod,
                        $negeri,
                        $negara,
                        $telefon,
                        $email,
                        $tarikh,
                        $penaja,
                        $username,
                        $plainPassword,
                        $status,
                        $bank,
                        $naakaun,
                        $noakaun,
                        $bnama,
                        $bkp,
                        $brelation,
                        $pakej,
                        $profilePath
                    );
                
                    // --------------------------
                    // Execute and confirm
                    // --------------------------
                    if ($stmt->execute()) {
                
                        // ✅ Get last inserted member ID
                        $lastMemberId   = mysqli_insert_id($con);
                        $usrnm          = $username;
                        $pswd           = $plainPassword;
                        
                        include "_sms_registration.php";
                        include "_phpmailer.php";
                         $_SESSION['flash_message'] = "Registration successful!";
                         
                        echo "<div class='alert alert-success text-center'>
                                <strong>Registration successful!</strong><br>
                                <b>Status:</b> $status<br>
                                <span style='color:red;'>You will receive <u>Registration Notice</u> via Email and SMS. Please check!</span>
                              </div>";
                
                        // ✅ Pass last inserted member ID to invoice generator
                        generateInvoiceRegistration($paymentMethod, $lastMemberId);
                
                    } else {
                        echo "<div class='alert alert-danger'>Error: " . htmlspecialchars($stmt->error) . "</div>";
                    }
                
                    $stmt->close();                    

                } 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.");
                }
            } 

}


function processPaidOrder($invoice_no) {
    global $con;
    date_default_timezone_set("Asia/Kuala_Lumpur");

    $logFile = __DIR__ . "/debug_log.txt";
    $now = date("Y-m-d H:i:s");
    error_log("\n=== processPaidOrder() START for Invoice: $invoice_no at $now ===\n", 3, $logFile);

    // ----------------------------
    // Get invoice info
    // ----------------------------
    $inv = mysqli_fetch_assoc(mysqli_query($con, "SELECT * FROM invoice WHERE invoice_no='$invoice_no'"));
    if (!$inv) {
        error_log("[ERROR] Invoice not found: $invoice_no\n", 3, $logFile);
        return;
    }

    error_log("[INFO] invoice_type={$inv['invoice_type']}, payment_status={$inv['payment_status']}\n", 3, $logFile);

    if ($inv['payment_status'] == 'Paid' && $inv['invoice_type'] == 'REGISTRATION') {

        $customer_id = $inv['customer_id'];
        $username    = getFieldValues("username", "ahli", "id", $customer_id);
        $tarikh      = date("Y-m-d H:i:s");

        error_log("[INFO] Invoice qualifies for registration activation. customer_id=$customer_id username=$username\n", 3, $logFile);

        // ----------------------------
        // Activate ahli
        // ----------------------------
        mysqli_query($con, "UPDATE ahli SET status='active' WHERE username='$username'");
        $affected = mysqli_affected_rows($con);
        error_log("[OK] Updated ahli.status for username=$username (affected rows=$affected)\n", 3, $logFile);

        // ----------------------------
        // Load MLM Setting
        // ----------------------------
        $setting = mysqli_fetch_assoc(mysqli_query($con, "SELECT * FROM setting LIMIT 1"));
        $width       = (int)($setting['width'] ?? 0);
        $levelLimit  = (int)($setting['level_limit'] ?? 0);
        $mlmType     = ($width > 0) ? 'MATRIX' : 'UNILEVEL';
        error_log("[MODE] MLM Type detected: $mlmType | width=$width | levelLimit=$levelLimit\n", 3, $logFile);

        // ----------------------------
        // Get ahli info
        // ----------------------------
        $resAhli = mysqli_query($con, "SELECT * FROM ahli WHERE username = '$username' LIMIT 1");
        if ($resAhli && mysqli_num_rows($resAhli) > 0) {
            $ahli = mysqli_fetch_assoc($resAhli);
            $penaja     = $ahli['penaja'];
            $upline_id  = $ahli['upline_id'] ?? $penaja;


// -------------------- Assign Correct Upline After Payment --------------------
if ($mlmType == 'MATRIX' && $width > 0) {

    // Start with sponsor as base placement
    $currentUpline = $penaja;

    // Count direct children of sponsor
    $directCount = mysqli_num_rows(mysqli_query($con, "SELECT id FROM ahli WHERE upline_id='$currentUpline'"));

    if ($directCount < $width) {
        // ✅ Sponsor has free slot → place here
        mysqli_query($con, "UPDATE ahli SET upline_id='$currentUpline' WHERE id='$customer_id'");
    } else {
        // ❗ Sponsor full → search next available placement (BFS downward)
        $newUpline = findNextAvailablePlacement($currentUpline, $width, $levelLimit, $con);
        mysqli_query($con, "UPDATE ahli SET upline_id='$newUpline' WHERE id='$customer_id'");
    }

} else if ($mlmType == 'UNILEVEL') {

    // ✅ Always place directly under sponsor
    mysqli_query($con, "UPDATE ahli SET upline_id='$penaja' WHERE id='$customer_id'");
}


//            // Adjust placement logic based on MLM type
//            if ($mlmType == 'MATRIX' && $width > 0) {
//                $childCount = mysqli_num_rows(mysqli_query($con, "SELECT id FROM ahli WHERE upline_id='$upline_id'"));
//                if ($childCount >= $width) {
//                    $newUpline = findNextAvailablePlacement($upline_id, $width);
//                    mysqli_query($con, "UPDATE ahli SET upline_id='$newUpline' WHERE id='$customer_id'");
//                    $upline_id = $newUpline;
//                    error_log("[INFO] Matrix full. Auto-reassigned upline_id to $upline_id\n", 3, $logFile);
//                }
//            } elseif ($mlmType == 'UNILEVEL' && $width == 0) {
//                // Ensure upline = penaja
//                if ($upline_id == 0 || $upline_id != $penaja) {
//                    mysqli_query($con, "UPDATE ahli SET upline_id='$penaja' WHERE id='$customer_id'");
//                    $upline_id = $penaja;
//                    error_log("[INFO] Unilevel mode: set upline_id = penaja ($penaja)\n", 3, $logFile);
//                }
//            }

            // ----------------------------
            // Sponsor Bonus (Direct)
            // ----------------------------
            $sponsor = mysqli_fetch_assoc(mysqli_query($con, "SELECT * FROM ahli WHERE id='$penaja' LIMIT 1"));
            $penajaUsername = $sponsor['username'] ?? '';
            $penajaEmail    = $sponsor['email'];
            $penajaNama     = $sponsor['nama'];

            if ($penajaUsername != 'admin') {
                $pakejName = $ahli['pakej'];
                $pkg = mysqli_fetch_assoc(mysqli_query($con, "SELECT * FROM packages WHERE name='$pakejName'"));
                $directSponsor = $pkg['direct_sponsor'];
                $usrnm = $ahli['username'];

                $info = telUser($penaja);
                list($tel, $uname, $sms) = explode("|", $info);

                mysqli_query($con, "
                    INSERT INTO cwallet (tarikh, keterangan, rujukan, masuk, userid)
                    VALUES ('$tarikh', 'Bonus Sponsor: RM$directSponsor [$pakejName] for $uname', '$usrnm', '$directSponsor', '$penaja')
                ");
                error_log("[OK] Direct sponsor bonus RM$directSponsor inserted for $uname\n", 3, $logFile);
                include "_sms_bonus_sponsor.php";
                include "_phpmailer_bonus_sponsor.php";
            }

            // ----------------------------
            // Bonus Unilevel / Matrix (Dynamic)
            // ----------------------------
            $r = mysqli_fetch_assoc(mysqli_query($con, "SELECT * FROM komisen WHERE id=1"));
            $maxLevel = $levelLimit;
            $bonusLevels = [];
            foreach ($r as $key => $value) {
                if (strpos($key, 'lvl') === 0) {
                    $lvlNum = intval(substr($key, 3));
                    $bonusLevels[$lvlNum] = $value;
                }
            }

            $penajaNow = $upline_id;
            $senaraiPenaja = [];
            $jumlahBonus = 0;
            
            $info = telUser($penajaNow);
            list($tel, $uname, $sms) = explode("|", $info);
                
            for ($level = 1; $level <= $maxLevel; $level++) {
                if (!$penajaNow) break;

                if (bolehDapatBonuss($con, $penajaNow, $level)) {
                    $bonus = $bonusLevels[$level] ?? 0;

                    $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'];
                        $uplineEmail    = $rowU['email'];
                        $uplineNama     = $rowU['nama'];
                    }

                    if ($penajaUsername != 'admin') {
                        mysqli_query($con, "
                            INSERT INTO cwallet (tarikh, keterangan, rujukan, masuk, userid)
                            VALUES ('$tarikh', 'Bonus Level $level : RM $bonus for $penajaUsername', '$username', $bonus, $penajaNow)
                        ");
                        $jumlahBonus += $bonus;
                        $senaraiPenaja[] = $penajaNow;
                        
                        error_log("[OK] Level $level bonus RM$bonus inserted for $penajaUsername\n", 3, $logFile);
                        include "_sms_bonus_level.php";
                        include "_phpmailer_bonus_level.php";
                    }
                }

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

            if (count($senaraiPenaja) > 0) {
                $senaraiStr = implode(",", $senaraiPenaja);
                $row = mysqli_fetch_array(mysqli_query($con, "SELECT GROUP_CONCAT(username) FROM ahli WHERE id IN ($senaraiStr)"));
                logSub($tarikh, 2, "$username account registration. Bonus for ".$row[0], $jumlahBonus);
            }
        }
    }

    error_log("[DONE] processPaidOrder() completed for invoice_no=$invoice_no\n", 3, $logFile);
}





function getFieldValues($field, $table, $whereField, $value) {
    global $con;
    $res = mysqli_query($con, "SELECT $field FROM $table WHERE $whereField='$value' LIMIT 1");
    if ($res && mysqli_num_rows($res) > 0) {
        $row = mysqli_fetch_assoc($res);
        return $row[$field];
    }
    return null;
}


function bolehDapatBonuss($con, $user_id, $level) {
    // Basic eligibility logic (can customize)
    $status = getFieldValues("status", "ahli", "id", $user_id);
    return ($status == 'active');
}


//function findNextAvailablePlacement($upline_id, $width) {
//    global $con;
//    // BFS search for next available upline
//    $queue = [$upline_id];
//    while (!empty($queue)) {
//        $current = array_shift($queue);
//        $childCount = mysqli_num_rows(mysqli_query($con, "SELECT id FROM ahli WHERE upline_id='$current'"));
//        if ($childCount < $width) {
//            return $current;
//        }
//        $res = mysqli_query($con, "SELECT id FROM ahli WHERE upline_id='$current'");
//        while ($row = mysqli_fetch_assoc($res)) {
//            $queue[] = $row['id'];
//        }
//    }
//    return $upline_id; // fallback
//}

// -------------------- Function to find available placement --------------------
function findNextAvailablePlacement($startId, $width, $levelLimit, $con) {
    $queue = [ ['id' => $startId, 'level' => 0] ];

    while (!empty($queue)) {
        $current = array_shift($queue);
        $parentId = $current['id'];
        $currentLevel = $current['level'];

        // Stop searching deeper if reach level limit
        if ($currentLevel >= $levelLimit) continue;

        $childQuery = mysqli_query($con, "SELECT id FROM ahli WHERE upline_id='$parentId'");
        $childCount = mysqli_num_rows($childQuery);

        // ✅ Found slot under this parent
        if ($childCount < $width) return $parentId;

        // Otherwise, push children to queue to continue BFS search
        while ($child = mysqli_fetch_assoc($childQuery)) {
            $queue[] = ['id' => $child['id'], 'level' => $currentLevel + 1];
        }
    }

    // If no slot found, default back to sponsor
    return $startId;
}
























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']);
    }


   function generateInvoiceRegistration($paymentMethod,$lastMemberId) {
        global $con; // use your mysqli connection
    
        // --------------------------
        // Build customer data
        // --------------------------
        $customer = [
            'username' => $_POST['username'] ?? '',
            'id'       => $lastMemberId,
            'name'     => $_POST['nama'] ?? '',
            'address'  => $_POST['ship_address'] ?? '',
            'postcode' => $_POST['ship_postcode'] ?? '',
            'city'     => $_POST['ship_city'] ?? '',
            'state'    => $_POST['ship_state'] ?? '',
            'phone'    => $_POST['ship_phone'] ?? '',
            'email'    => $_POST['ship_email'] ?? ''
        ];
    
        // --------------------------
        // Build package data
        // --------------------------
        $price        = isset($_POST['nilai_value']) ? (float) str_replace(',', '', $_POST['nilai_value']) : 0;
        $qty_set      = isset($_POST['qty_set']) ? (int) $_POST['qty_set'] : 1;
        $qty_total    = isset($_POST['qty_total']) ? (int) $_POST['qty_total'] : $qty_set;
        $discount     = isset($_POST['discount']) ? (float) $_POST['discount'] : 0;
        $tax          = isset($_POST['tax']) ? (float) $_POST['tax'] : 0;
        $shipping_fee = isset($_POST['shipping_fee']) ? (float) $_POST['shipping_fee'] : (float) ($_POST['shipping'] ?? 0);
        $grand_total  = isset($_POST['grand_total'])
            ? (float) $_POST['grand_total']
            : (($price * $qty_total) - $discount + $shipping_fee);
    
        $package = [
            'id'              => $_POST['package_id'] ?? 0,
            'name'            => $_POST['package_name'] ?? 'Selected Package',
            'price'           => $price,
            'qty_set'         => $qty_set,
            'qty'             => $qty_total,
            'discount'        => $discount,
            'shipping'        => $shipping_fee,
            'shipping_method' => $_POST['shipping_method'] ?? 'selfcollect'
        ];

    // --------------------------
    // Get package items (JSON)
    // --------------------------
    if (!empty($package['id'])) {
        $sqlPkg = "SELECT items FROM packages WHERE id = " . intval($package['id']);
        $resPkg = mysqli_query($con, $sqlPkg);
        if ($resPkg && $rowPkg = mysqli_fetch_assoc($resPkg)) {
            $itemsData = json_decode($rowPkg['items'], true);
            $package['items'] = is_array($itemsData) ? $itemsData : [];
        } else {
            $package['items'] = [];
        }
    } else {
        $package['items'] = [];
    }

    // 1️⃣ Prepare the package_desc JSON
    $package_desc = json_encode($package['items'] ?? [], JSON_UNESCAPED_UNICODE);
    
    $invoice_type = "REGISTRATION";

    // --------------------------
    // Set timezone to Kuala Lumpur
    // --------------------------
    date_default_timezone_set("Asia/Kuala_Lumpur");
    
    // --------------------------
    // Generate invoice number (YYYYMM{number})
    // Reset setiap bulan baru
    // --------------------------
    $year   = date("Y");
    $month  = date("m");
    $prefix = "{$year}{$month}";
    
    $sql = "SELECT invoice_no 
            FROM invoice 
            WHERE invoice_no LIKE '{$prefix}%'
            ORDER BY id DESC 
            LIMIT 1";
    $res = mysqli_query($con, $sql);
    
    $lastNumber = 1;
    if ($row = mysqli_fetch_assoc($res)) {
        $invoiceNo = $row['invoice_no'];
    
        // ✅ extract only the numeric suffix (after prefix YYYYMM)
        $numPart = preg_replace('/^' . preg_quote($prefix, '/') . '/', '', $invoiceNo);
    
        if (is_numeric($numPart)) {
            $lastNumber = intval($numPart) + 1;
        }
    }
    
    // ✅ Final invoice number (contoh: 2025091, 2025092, ..., 2025101)
    $invoice_no = $prefix . $lastNumber;
    
    // Folder to save QR
    $dir = "temp/img/qrcode/";
    if (!file_exists($dir)) {
        mkdir($dir, 0777, true);
    }
    
    $filename = $dir . $invoice_no . ".png";
    
    // Generate QR (content can be just invoice_no or full payment URL)
    QRcode::png($invoice_no, $filename, QR_ECLEVEL_L, 3);


    // --------------------------
    // Insert invoice
    // --------------------------
    $stmt = $con->prepare("INSERT INTO invoice 
        (invoice_no, invoice_type, customer_id, package_id, package_name, package_desc, price, qty_set, qty_total, discount, shipping_fee, tax, grand_total, payment_method, shipping_method, ship_name, ship_address, ship_postcode, ship_city, ship_state, ship_phone, ship_email) 
        VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");

    $stmt->bind_param(
        "ssiissdiidddssssssssss",
        $invoice_no,
        $invoice_type,
        $customer['id'],
        $package['id'],
        $package['name'],
        $package_desc,
        $package['price'],
        $package['qty_set'],
        $package['qty'],
        $package['discount'],
        $package['shipping'],
        $tax,
        $grand_total,
        $paymentMethod,
        $package['shipping_method'],
        $customer['name'],
        $customer['address'],
        $customer['postcode'],
        $customer['city'],
        $customer['state'],
        $customer['phone'],
        $customer['email']
    );
    $stmt->execute();


    // --------------------------
    // Get inserted invoice status
    // --------------------------
    $sqlStatus = "SELECT invoice_status, payment_status, shipping_status 
                  FROM invoice 
                  WHERE invoice_no = ?";
    $stmtStatus = $con->prepare($sqlStatus);
    $stmtStatus->bind_param("s", $invoice_no);
    $stmtStatus->execute();
    $resStatus = $stmtStatus->get_result();
    $status = $resStatus->fetch_assoc();

    
    // --------------------------
    // Display invoice template
    // --------------------------
    ?>
    <!-- Scrollable container -->
    <div style="overflow-x:auto; -webkit-overflow-scrolling:touch;">
        <div style="width:800px; margin:auto; font-family:Arial, sans-serif; border:1px solid #ccc; padding:20px; box-shadow:0 4px 8px rgba(0,0,0,0.1); border-radius:8px;">
            <!-- Invoice Print Area -->
            <div id="printArea">
                
            <!-- Letterhead -->
    <?php
            $sql1 = "SELECT * FROM ahli WHERE username ='admin' ORDER BY id DESC LIMIT 1";
            $res1 = mysqli_query($con, $sql1);
            if ($rowHeader = mysqli_fetch_assoc($res1)) {
    ?>        
                <div style="display:flex; align-items:center; justify-content:space-between; border-bottom:0px solid #000; padding-bottom:10px; margin-bottom:20px;">
                    <div style="text-align:left;">
                        <h4 style="margin:0;">
                            <?= $rowHeader['nama'] ?>
                            <span class="small">(<?= $rowHeader['kp'] ?>)</span>
                        </h4>
                        <small>
                            <?= $rowHeader['alamat'] ?>,
                            <?= $rowHeader['poskod'] ?>,
                            <?= $rowHeader['bandar'] ?>,
                            <?= $rowHeader['negeri'] ?> <br>
                            <?= $rowHeader['email'] ?> |
                            <?= $rowHeader['telefon'] ?>
                        </small>
                    </div>
                    <img src="assets2/ico/tls2u.png" style="height:100px;">
        
                </div>
    
    <?php   }   ?>
    
            
                <div style="display:flex; justify-content:space-between; align-items:flex-start; margin-bottom:20px;">
                    <!-- Left: Bill To -->
                    <div style="font-size:12px; line-height:1.4;">
                        <span style="font-size:10px;">Bill To:</span>
                        <div style="padding-top:5px;">
                            <strong><?= htmlspecialchars(strtoupper($customer['name'])) ?></strong><br>
                            <?= htmlspecialchars($customer['address']) ?><br>
                            <?= htmlspecialchars($customer['postcode']) ?> <?= htmlspecialchars($customer['city']) ?>,<br>
                            <?= htmlspecialchars($customer['state']) ?><br>
                            <i class="fa-solid fa-phone"></i> <?= htmlspecialchars($customer['phone']) ?><br>
                            <i class="fa-solid fa-envelope"></i> <?= htmlspecialchars($customer['email']) ?>
                        </div>
                    </div>
                
                    <!-- Right: Invoice Info -->
                    <div style="min-width:250px; font-size:12px;">
                    
                        <!-- Title -->
                        <div style="text-align:right; margin-bottom:10px;">
                            <h3 style="margin:0;">INVOICE</h3>
                        </div>
                    
                        <!-- QR + Info Side by Side -->
                        <div style="display:flex; align-items:center; gap:10px;">
                            
                            <!-- QR Code -->
                            <div style="margin-bottom:5px;">
                                <img src='<?= $filename ?>' alt='QR Code' style="width:80px; height:80px;">
                            </div>
                            
                            <!-- Invoice Details -->
                            <div>
                                <div style="margin-bottom:5px; display:flex; justify-content:space-between;">
                                    <span style="font-size:10px; width:60px;">No:</span>
                                    <span style="font-size:13px; text-align:right; min-width:100px;"><?= $invoice_no ?></span>
                                </div>
                                <div style="margin-bottom:5px; display:flex; justify-content:space-between;">
                                    <span style="font-size:10px; display:inline-block; width:60px;">Date:</span>
                                    <span style="font-size:13px; text-align:right; min-width:100px;"><?= date("d/m/Y") ?></span>
                                </div>
                                <div style="margin-bottom:5px; display:flex; justify-content:space-between;">
                                    <span style="font-size:10px; display:inline-block; width:60px;">Payment:</span>
                                    <span style="font-size:13px; text-align:right; min-width:100px;"><?= htmlspecialchars($paymentMethod) ?></span>
                                </div>
                            </div>
                        </div>
                    
                    </div>
                </div>
            
                
                    <table width="100%" cellspacing="0" cellpadding="8" style="margin-top:20px; border-collapse:collapse; font-size:13px; font-family:Arial, sans-serif; ">
                        <thead>
                            <tr style="border-top:2px solid #eaeaea;">
                                <th style="text-align:left; padding:10px 12px; border-bottom:1px solid #e6e6e6;">Item</th>
                                <th style="text-align:center; padding:10px 12px; border-bottom:1px solid #e6e6e6; width:80px;">Qty</th>
                                <th style="text-align:right; padding:10px 12px; border-bottom:1px solid #e6e6e6; width:140px;">Unit Price (RM)</th>
                                <th style="text-align:right; padding:10px 12px; border-bottom:1px solid #e6e6e6; width:160px;">Line Total (RM)</th>
                            </tr>
                        </thead>
                    
                        <tbody>
                            <?php
                            // line total (per item)
                            $lineTotal = ($package['price'] * $package['qty_set']);
                            ?>
                            <tr>
                                <td style="padding:20px 12px; vertical-align:top;">
                                    <strong><?= htmlspecialchars($package['name']) ?></strong>
                                    
                                    <div style="color:#666; font-size:12px; margin-top:6px;">
                                        <?php
                                        if (!empty($package_desc)) {
                                            // Decode JSON string into PHP array
                                            $items = json_decode($package_desc, true);
                                        
                                            if (is_array($items) && count($items) > 0) {
                                                echo '<div style="margin-top:8px; color:#555; font-size:12px;">';
                                                foreach ($items as $item) {
                                                    $pid = intval($item['product_id']);
                                                    $productName = '';
                                                    $resProd = mysqli_query($con, "SELECT product_name FROM products WHERE id = $pid");
                                                    if ($resProd && $rowProd = mysqli_fetch_assoc($resProd)) {
                                                        $productName = $rowProd['product_name'];
                                                    }
                                        
                                                    echo htmlspecialchars($productName) . ' (x' . intval($item['qty']) . ')<br>';
                                                }
                                                echo '</div>';
                                            } else {
                                                echo '<div style="color:#999;">No items found</div>';
                                            }
                                        }
                                        ?>

                                    </div>
                                </td>
                    
                                <td style="text-align:center; padding:10px 12px; border-bottom:1px solid #f3f3f3; vertical-align:middle;">
                                    <?= $package['qty_set'] ?>
                                </td>
                    
                                <td style="text-align:right; padding:10px 12px; border-bottom:1px solid #f3f3f3; vertical-align:middle;">
                                    <?= number_format($package['price'], 2) ?>
                                </td>
                    
                                <td style="text-align:right; padding:10px 12px; border-bottom:1px solid #f3f3f3; vertical-align:middle;">
                                    <?= number_format($lineTotal, 2) ?>
                                </td>
                            </tr>
                        </tbody>
                    
                        <tfoot>
                            <?php
                            // Subtotal: kalau ada lebih dari 1 baris, jumlahkan semua $lineTotal
                            $subtotal = $lineTotal;
                    
                            // Discount: treating as RM (if percentage, adjust logic)
                            $discount = isset($package['discount']) ? (float)$package['discount'] : 0.00;
                    
                            // Shipping fee
                            $shipping = isset($package['shipping']) ? (float)$package['shipping'] : 0.00;
                    
                            // Dapatkan tax setting
                            $taxRow = mysqli_fetch_array(mysqli_query($con, "SELECT * FROM setting LIMIT 1"));
                            $taxRate = isset($taxRow['tax']) ? (float)$taxRow['tax'] : 0;
                            
                            // Grand total calc (recompute to be safe)
                            $grand_total_calc = $subtotal - $discount + $shipping + $tax;
                            ?>
                    
                            <tr>
                                <td colspan="3 small" style="font-size:10px; text-align:right; padding-top:10px; padding-right: 12px; "><er>Subtotal</er></td>
                                <td style="text-align:right; padding-top:10px; padding-right: 12px; "><?= number_format($subtotal, 2) ?></td>
                            </tr>
                    
                            <tr>
                                <td colspan="3 small" style="font-size:10px; text-align:right; padding:0px 12px;"><er>Discount</er></td>
                                <td style="text-align:right; padding:0px 12px;">-<?= number_format($discount, 2) ?></td>
                            </tr>
                    
                            <tr>
                                <td colspan="3 small" style="font-size:10px; text-align:right; padding:0px 12px;"><er>Shipping</er></td>
                                <td style="text-align:right; padding:0px 12px;"><?= number_format($shipping, 2) ?></td>
                            </tr>
                    
                            <tr>
                                <td colspan="3 small" style="font-size:10px; text-align:right; padding-bottom:10px; padding-right: 12px;"><er>Tax (<?= $taxRate ?>%)</er></td>
                                <td style="text-align:right; padding-bottom:10px; padding-right: 12px;"><?= number_format($tax, 2) ?></td>
                            </tr>
                    
                            <tr style="background:#f7f7f7; font-weight:700;">
                                <td colspan="3" style="text-align:right; padding:12px 14px; border-top:2px solid #ddd;">Grand Total (RM)</td>
                                <td style="text-align:right; padding:12px 14px; border-top:2px solid #ddd;"><?= number_format($grand_total_calc, 2) ?></td>
                            </tr>
                        </tfoot>
                    </table>
                    <p style="font-size:12px; text-align:center; margin:5px;">
                        --- Computer Generated ---
                    </p>
<?php    
            // --------------------------
            // Payment Method Handling
            // --------------------------
            $message_notif = '';
            
            if ($paymentMethod === 'transfer') {
                ?>
                <fieldset style="border:1px solid #ccc; padding:10px 15px; margin-bottom:15px; box-shadow:0 4px 8px rgba(0,0,0,0.1); border-radius:8px;">
                    <legend style="padding:0 10px; font-size:12px; border:none; width:auto;">
                        Bank Transfer Information
                    </legend>
                    
                    <!-- Data info at the top -->
                    <div style="text-align:left; margin-bottom:8px;">
                        <span style="font-size:12px;" class="small">Account Name:   </span> <b><?= $rowHeader['naakaun'] ?></b><br>
                        <span style="font-size:12px;" class="small">Bank Name:      </span> <b><?= $rowHeader['bank'] ?></b><br>
                        <span style="font-size:12px;" class="small">Account No:     </span> <b><?= $rowHeader['noakaun'] ?></b>
                    </div>
                
                    <!-- Instruction -->
                    <div style="text-align:left; font-size:12px;">
                        <p style="margin:0 0 5px 0; font-size:12px;">
                             Pay invoice <b class="text-danger"><?= $invoice_no ?></b> via bank transfer (details above), then follow the steps below:
                        </p>
                        <ul style="margin-left:20px; font-size:12px;">
                            <li>Take a screenshot or photo of your payment receipt.</li>
                            <li>Login to the system and upload that payment receipt via the <b>Payment</b> menu.</li>
                            <li>Wait for admin verification. You will be notified once your payment has been confirmed.</li>
                        </ul>
                    </div>
                </fieldset>


                <?php
            } elseif ($paymentMethod === 'cash') {
                ?>
                <fieldset style="border:1px solid #ccc; padding:10px 15px; margin-bottom:15px; box-shadow:0 4px 8px rgba(0,0,0,0.1); border-radius:8px;">
                    <legend style="padding:0 10px; font-size:12px; border:none; width:auto;">
                        Bank Transfer Information
                    </legend>
                    
                    <!-- Instruction -->
                    <div style="text-align:left; margin-bottom:8px; font-size:12px;">
                        <p style="margin:0 0 5px 0; font-size:12px;">
                            Please settle your invoice <b class="text-danger"><?= $invoice_no ?></b> at the counter, and then follow the steps below:
                        </p>
                        <ul style="margin-left:20px; font-size:12px;">
                            <li>Make your payment directly at the counter.</li>
                            <li>Collect your official receipt after payment is completed.</li>
                            <li>A copy of the receipt will also be sent to your registered email address.</li>
                        </ul>
                    </div>
                </fieldset>
                <?php
            
                // Hantar email untuk cash
                $to = $customer['email'];
                $subject = "Cash Payment Required";
                $body = "Please settle your invoice $invoice_no at the counter. Receipt will be given at the counter and via email.";
                $headers = "From: billing@yourcompany.com";
                mail($to, $subject, $body, $headers);
            }
?>               
            </div>
            <!-- End Invoice Print Area -->
    <?php
            // --------------------------
            // Get inserted invoice status
            // --------------------------
            $sqlStatus = "SELECT invoice_status, payment_status, packaging_status, shipping_status 
                          FROM invoice 
                          WHERE invoice_no = ?";
            $stmtStatus = $con->prepare($sqlStatus);
            $stmtStatus->bind_param("s", $invoice_no);
            $stmtStatus->execute();
            $resStatus = $stmtStatus->get_result();
            $status = $resStatus->fetch_assoc();
            ?>
            
            <style>
            .progress-area {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-top:30px;
                gap: 20px;
            }
            
            .progress-tracker {
                display: flex;
                justify-content: space-between;
                flex: 1;
                margin: 0;
                padding: 0;
                list-style: none;
            }
            .progress-tracker li {
                flex: 1;
                text-align: center;
                position: relative;
                font-size: 13px;
                color: #999;
            }
            .progress-tracker li::before {
                content: "";
                width: 20px;
                height: 20px;
                background: #ccc;
                border-radius: 50%;
                display: block;
                margin: 0 auto 8px;
            }
            .progress-tracker li::after {
                content: "";
                position: absolute;
                top: 10px;
                left: 50%;
                width: 100%;
                height: 4px;
                background: #ccc;
                z-index: -1;
            }
            .progress-tracker li:last-child::after {
                display: none;
            }
            .progress-tracker li.active {
                color: #4CAF50;
                font-weight: bold;
            }
            .progress-tracker li.active::before {
                background: #4CAF50;
            }
            .progress-tracker li.paid::before {
                background: #2196F3; /* biru untuk Paid */
            }
            .progress-tracker li.packaged::before {
                background: #9C27B0; /* ungu untuk Packaging */
            }
            .progress-tracker li.shipped::before {
                background: #FF9800; /* oren untuk Shipped */
            }
            .progress-tracker li.delivered::before {
                background: #4CAF50; /* hijau untuk Delivered */
            }
            
            .progress-button button,
            .progress-button a {
                white-space: nowrap;
            }
            
            /* Responsive: biar horizontal scroll bila screen kecil */
            @media(max-width:768px){
                .progress-area {
                    overflow-x: auto;
                    -webkit-overflow-scrolling: touch;
                }
                .progress-tracker {
                    flex-wrap: nowrap;
                    min-width: 600px; /* boleh adjust ikut bilangan step */
                }
                .progress-tracker li {
                    flex: 0 0 auto;
                    min-width: 100px; /* bagi spacing setiap step */
                }
            }
            
            @media print {
                body * {
                    visibility: hidden;
                }
                #printArea, #printArea * {
                    visibility: visible;
                }
                #printArea {
                    position: absolute;
                    left: 0;
                    top: 0;
                    width: 100%;
                    height: auto;
                }
                @page {
                    size: A4;
                    margin: 10mm;
                }
            }
    </style>

            <div class="progress-area">
                <ul class="small progress-tracker">
                    <li style="font-size:10px;" class="small <?= ($status['invoice_status']=='Issued') ? 'active' : '' ?>">
                        Invoice Issued
                    </li>
                    <li style="font-size:10px;" class="small <?= ($status['payment_status']=='Paid') ? 'active paid' : '' ?>">
                        Payment
                    </li>
                    <li style="font-size:10px;" class="small <?= ($status['packaging_status']=='Packed') ? 'active packaged' : '' ?>">
                        Packaging
                    </li>
                    <li style="font-size:10px;" class="small <?= ($status['shipping_status']=='Shipped') ? 'active shipped' : '' ?>">
                        Shipping
                    </li>
                    <li style="font-size:10px;" class="small <?= ($status['shipping_status']=='Delivered') ? 'active delivered' : '' ?>">
                        Delivered
                    </li>
                </ul>
            
                <!-- Pay / Print Button -->
                <div class="progress-button">
                    <?php if (strtolower($paymentMethod) == "fpx"): ?>
                        <!-- Print Button -->
                            <button onclick="printInvoice()" style="background:#007bff; color:#fff; padding:10px 20px; border:none; border-radius:5px;">
                                PRINT
                            </button>
                            <a href="pay_fpx.php?invoice=<?= urlencode($invoice_no) ?>" 
                               style="background:#28a745; color:#fff; padding:10px 20px; text-decoration:none; border-radius:5px;">PAY NOW</a>
                        <?php else: ?>
                            <button onclick="printInvoice()" style="background:#007bff; color:#fff; padding:10px 20px; border:none; border-radius:5px;">
                                PRINT
                            </button>
                    <?php endif; ?>
                </div>
            </div>
            <script>
            function printInvoice() {
                window.print();
            }
            </script>
    
        </div>
    </div>
    <?php
}



    function generateInvoice($paymentMethod) {
        global $con; // use your mysqli connection
    
        // --------------------------
        // Build customer data
        // --------------------------
        $customer = [
            'id'       => $_SESSION['aidi'] ?? 0,
            'name'     => $_SESSION['namapenuh'] ?? '',
            'address'  => $_POST['ship_address'] ?? '',
            'postcode' => $_POST['ship_postcode'] ?? '',
            'city'     => $_POST['ship_city'] ?? '',
            'state'    => $_POST['ship_state'] ?? '',
            'phone'    => $_POST['ship_phone'] ?? '',
            'email'    => $_POST['ship_email'] ?? ''
        ];
    
        // --------------------------
        // Build package data
        // --------------------------
        $price        = isset($_POST['nilai_value']) ? (float) str_replace(',', '', $_POST['nilai_value']) : 0;
        $qty_set      = isset($_POST['qty_set']) ? (int) $_POST['qty_set'] : 1;
        $qty_total    = isset($_POST['qty_total']) ? (int) $_POST['qty_total'] : $qty_set;
        $discount     = isset($_POST['discount']) ? (float) $_POST['discount'] : 0;
        $tax          = isset($_POST['tax']) ? (float) $_POST['tax'] : 0;
        $shipping_fee = isset($_POST['shipping_fee']) ? (float) $_POST['shipping_fee'] : (float) ($_POST['shipping'] ?? 0);
        $grand_total  = isset($_POST['grand_total'])
            ? (float) $_POST['grand_total']
            : (($price * $qty_total) - $discount + $shipping_fee);
    
        $package = [
            'id'              => $_POST['package_id'] ?? 0,
            'name'            => $_POST['package_name'] ?? 'Selected Package',
            'price'           => $price,
            'qty_set'         => $qty_set,
            'qty'             => $qty_total,
            'discount'        => $discount,
            'shipping'        => $shipping_fee,
            'shipping_method' => $_POST['shipping_method'] ?? 'selfcollect'
        ];
    
    // --------------------------
    // Get package items (JSON)
    // --------------------------
    if (!empty($package['id'])) {
        $sqlPkg = "SELECT items FROM packages WHERE id = " . intval($package['id']);
        $resPkg = mysqli_query($con, $sqlPkg);
        if ($resPkg && $rowPkg = mysqli_fetch_assoc($resPkg)) {
            $itemsData = json_decode($rowPkg['items'], true);
            $package['items'] = is_array($itemsData) ? $itemsData : [];
        } else {
            $package['items'] = [];
        }
    } else {
        $package['items'] = [];
    }

    // 1️⃣ Prepare the package_desc JSON
    $package_desc = json_encode($package['items'] ?? [], JSON_UNESCAPED_UNICODE);
    $invoice_type = "STOCK";
    
    // --------------------------
    // Set timezone to Kuala Lumpur
    // --------------------------
    date_default_timezone_set("Asia/Kuala_Lumpur");
    
    // --------------------------
    // Generate invoice number (YYYYMM{number})
    // Reset setiap bulan baru
    // --------------------------
    $year   = date("Y");
    $month  = date("m");
    $prefix = "{$year}{$month}";
    
    $sql = "SELECT invoice_no 
            FROM invoice 
            WHERE invoice_no LIKE '{$prefix}%'
            ORDER BY id DESC 
            LIMIT 1";
    $res = mysqli_query($con, $sql);
    
    $lastNumber = 1;
    if ($row = mysqli_fetch_assoc($res)) {
        $invoiceNo = $row['invoice_no'];
    
        // ✅ extract only the numeric suffix (after prefix YYYYMM)
        $numPart = preg_replace('/^' . preg_quote($prefix, '/') . '/', '', $invoiceNo);
    
        if (is_numeric($numPart)) {
            $lastNumber = intval($numPart) + 1;
        }
    }
    
    // ✅ Final invoice number (contoh: 2025091, 2025092, ..., 2025101)
    $invoice_no = $prefix . $lastNumber;
    
    // Folder to save QR
    $dir = "temp/img/qrcode/";
    if (!file_exists($dir)) {
        mkdir($dir, 0777, true);
    }
    
    $filename = $dir . $invoice_no . ".png";
    
    // Generate QR (content can be just invoice_no or full payment URL)
    QRcode::png($invoice_no, $filename, QR_ECLEVEL_L, 3);

    // --------------------------
    // Insert invoice
    // --------------------------
    $stmt = $con->prepare("INSERT INTO invoice 
        (invoice_no, invoice_type, customer_id, package_id, package_name, package_desc, price, qty_set, qty_total, discount, shipping_fee, tax, grand_total, payment_method, shipping_method, ship_name, ship_address, ship_postcode, ship_city, ship_state, ship_phone, ship_email) 
        VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");

    $stmt->bind_param(
        "ssiissdiidddssssssssss",
        $invoice_no,
        $invoice_type,
        $customer['id'],
        $package['id'],
        $package['name'],
        $package_desc,
        $package['price'],
        $package['qty_set'],
        $package['qty'],
        $package['discount'],
        $package['shipping'],
        $tax,
        $grand_total,
        $paymentMethod,
        $package['shipping_method'],
        $customer['name'],
        $customer['address'],
        $customer['postcode'],
        $customer['city'],
        $customer['state'],
        $customer['phone'],
        $customer['email']
    );
    $stmt->execute();


    // --------------------------
    // Get inserted invoice status
    // --------------------------
    $sqlStatus = "SELECT invoice_status, payment_status, shipping_status 
                  FROM invoice 
                  WHERE invoice_no = ?";
    $stmtStatus = $con->prepare($sqlStatus);
    $stmtStatus->bind_param("s", $invoice_no);
    $stmtStatus->execute();
    $resStatus = $stmtStatus->get_result();
    $status = $resStatus->fetch_assoc();

    
    // --------------------------
    // Display invoice template
    // --------------------------
    ?>
    <!-- Scrollable container -->
    <div style="overflow-x:auto; -webkit-overflow-scrolling:touch;">
        <div style="width:800px; margin:auto; font-family:Arial, sans-serif; border:1px solid #ccc; padding:20px; box-shadow:0 4px 8px rgba(0,0,0,0.1); border-radius:8px;">
            <!-- Invoice Print Area -->
            <div id="printArea">
                
            <!-- Letterhead -->
    <?php
            $sql1 = "SELECT * FROM ahli WHERE username ='admin' ORDER BY id DESC LIMIT 1";
            $res1 = mysqli_query($con, $sql1);
            if ($rowHeader = mysqli_fetch_assoc($res1)) {
    ?>        
                <div style="display:flex; align-items:center; justify-content:space-between; border-bottom:0px solid #000; padding-bottom:10px; margin-bottom:20px;">
                    <div style="text-align:left;">
                        <h4 style="margin:0;">
                            <?= $rowHeader['nama'] ?>
                            <span class="small">(<?= $rowHeader['kp'] ?>)</span>
                        </h4>
                        <small>
                            <?= $rowHeader['alamat'] ?>,
                            <?= $rowHeader['poskod'] ?>,
                            <?= $rowHeader['bandar'] ?>,
                            <?= $rowHeader['negeri'] ?> <br>
                            <?= $rowHeader['email'] ?> |
                            <?= $rowHeader['telefon'] ?>
                        </small>
                    </div>
                    <img src="assets2/ico/tls2u.png" style="height:100px;">
        
                </div>
    
    <?php   }   ?>
    
            
                <div style="display:flex; justify-content:space-between; align-items:flex-start; margin-bottom:20px;">
                    <!-- Left: Bill To -->
                    <div style="font-size:12px; line-height:1.4;">
                        <span style="font-size:10px;">Bill To:</span>
                        <div style="padding-top:5px;">
                            <strong><?= htmlspecialchars(strtoupper($customer['name'])) ?></strong><br>
                            <?= htmlspecialchars($customer['address']) ?><br>
                            <?= htmlspecialchars($customer['postcode']) ?> <?= htmlspecialchars($customer['city']) ?>,<br>
                            <?= htmlspecialchars($customer['state']) ?><br>
                            <i class="fa-solid fa-phone"></i> <?= htmlspecialchars($customer['phone']) ?><br>
                            <i class="fa-solid fa-envelope"></i> <?= htmlspecialchars($customer['email']) ?>
                        </div>
                    </div>
                
                    <!-- Right: Invoice Info -->
                    <div style="min-width:250px; font-size:12px;">
                    
                        <!-- Title -->
                        <div style="text-align:right; margin-bottom:10px;">
                            <h3 style="margin:0;">INVOICE</h3>
                        </div>
                    
                        <!-- QR + Info Side by Side -->
                        <div style="display:flex; align-items:center; gap:10px;">
                            
                            <!-- QR Code -->
                            <div style="margin-bottom:5px;">
                                <img src='<?= $filename ?>' alt='QR Code' style="width:80px; height:80px;">
                            </div>
                            
                            <!-- Invoice Details -->
                            <div>
                                <div style="margin-bottom:5px; display:flex; justify-content:space-between;">
                                    <span style="font-size:10px; width:60px;">No:</span>
                                    <span style="font-size:13px; text-align:right; min-width:100px;"><?= $invoice_no ?></span>
                                </div>
                                <div style="margin-bottom:5px; display:flex; justify-content:space-between;">
                                    <span style="font-size:10px; display:inline-block; width:60px;">Date:</span>
                                    <span style="font-size:13px; text-align:right; min-width:100px;"><?= date("d/m/Y") ?></span>
                                </div>
                                <div style="margin-bottom:5px; display:flex; justify-content:space-between;">
                                    <span style="font-size:10px; display:inline-block; width:60px;">Payment:</span>
                                    <span style="font-size:13px; text-align:right; min-width:100px;"><?= htmlspecialchars($paymentMethod) ?></span>
                                </div>
                            </div>
                        </div>
                    
                    </div>
                </div>
            
                
                    <table width="100%" cellspacing="0" cellpadding="8" style="margin-top:20px; border-collapse:collapse; font-size:13px; font-family:Arial, sans-serif; ">
                        <thead>
                            <tr style="border-top:2px solid #eaeaea;">
                                <th style="text-align:left; padding:10px 12px; border-bottom:1px solid #e6e6e6;">Item</th>
                                <th style="text-align:center; padding:10px 12px; border-bottom:1px solid #e6e6e6; width:80px;">Qty</th>
                                <th style="text-align:right; padding:10px 12px; border-bottom:1px solid #e6e6e6; width:140px;">Unit Price (RM)</th>
                                <th style="text-align:right; padding:10px 12px; border-bottom:1px solid #e6e6e6; width:160px;">Line Total (RM)</th>
                            </tr>
                        </thead>
                    
                        <tbody>
                            <?php
                            // line total (per item)
                            $lineTotal = ($package['price'] * $package['qty_set']);
                            ?>
                            <tr>
                                <td style="padding:20px 12px; vertical-align:top;">
                                    <strong><?= htmlspecialchars($package['name']) ?></strong>
                                    
                                    <div style="color:#666; font-size:12px; margin-top:6px;">
<?php
                                        if (!empty($package_desc)) {
                                            // Decode JSON string into PHP array
                                            $items = json_decode($package_desc, true);
                                        
                                            if (is_array($items) && count($items) > 0) {
                                                echo '<div style="margin-top:8px; color:#555; font-size:12px;">';
                                                foreach ($items as $item) {
                                                    $pid = intval($item['product_id']);
                                                    $productName = '';
                                                    $resProd = mysqli_query($con, "SELECT product_name FROM products WHERE id = $pid");
                                                    if ($resProd && $rowProd = mysqli_fetch_assoc($resProd)) {
                                                        $productName = $rowProd['product_name'];
                                                    }
                                        
                                                    echo htmlspecialchars($productName) . ' (x' . intval($item['qty']) . ')<br>';
                                                }
                                                echo '</div>';
                                            } else {
                                                echo '<div style="color:#999;">No items found</div>';
                                            }
                                        }
?>
                                    </div>
                                </td>
                    
                                <td style="text-align:center; padding:10px 12px; border-bottom:1px solid #f3f3f3; vertical-align:middle;">
                                    <?= $package['qty_set'] ?>
                                </td>
                    
                                <td style="text-align:right; padding:10px 12px; border-bottom:1px solid #f3f3f3; vertical-align:middle;">
                                    <?= number_format($package['price'], 2) ?>
                                </td>
                    
                                <td style="text-align:right; padding:10px 12px; border-bottom:1px solid #f3f3f3; vertical-align:middle;">
                                    <?= number_format($lineTotal, 2) ?>
                                </td>
                            </tr>
                        </tbody>
                    
                        <tfoot>
                            <?php
                            // Subtotal: kalau ada lebih dari 1 baris, jumlahkan semua $lineTotal
                            $subtotal = $lineTotal;
                    
                            // Discount: treating as RM (if percentage, adjust logic)
                            $discount = isset($package['discount']) ? (float)$package['discount'] : 0.00;
                    
                            // Shipping fee
                            $shipping = isset($package['shipping']) ? (float)$package['shipping'] : 0.00;
                    
                            // Dapatkan tax setting
                            $taxRow = mysqli_fetch_array(mysqli_query($con, "SELECT * FROM setting LIMIT 1"));
                            $taxRate = isset($taxRow['tax']) ? (float)$taxRow['tax'] : 0;
                            
                            // Grand total calc (recompute to be safe)
                            $grand_total_calc = $subtotal - $discount + $shipping + $tax;
                            ?>
                    
                            <tr>
                                <td colspan="3 small" style="font-size:10px; text-align:right; padding-top:10px; padding-right: 12px; "><er>Subtotal</er></td>
                                <td style="text-align:right; padding-top:10px; padding-right: 12px; "><?= number_format($subtotal, 2) ?></td>
                            </tr>
                    
                            <tr>
                                <td colspan="3 small" style="font-size:10px; text-align:right; padding:0px 12px;"><er>Discount</er></td>
                                <td style="text-align:right; padding:0px 12px;">-<?= number_format($discount, 2) ?></td>
                            </tr>
                    
                            <tr>
                                <td colspan="3 small" style="font-size:10px; text-align:right; padding:0px 12px;"><er>Shipping</er></td>
                                <td style="text-align:right; padding:0px 12px;"><?= number_format($shipping, 2) ?></td>
                            </tr>
                    
                            <tr>
                                <td colspan="3 small" style="font-size:10px; text-align:right; padding-bottom:10px; padding-right: 12px;"><er>Tax (<?= $taxRate ?>%)</er></td>
                                <td style="text-align:right; padding-bottom:10px; padding-right: 12px;"><?= number_format($tax, 2) ?></td>
                            </tr>
                    
                            <tr style="background:#f7f7f7; font-weight:700;">
                                <td colspan="3" style="text-align:right; padding:12px 14px; border-top:2px solid #ddd;">Grand Total (RM)</td>
                                <td style="text-align:right; padding:12px 14px; border-top:2px solid #ddd;"><?= number_format($grand_total_calc, 2) ?></td>
                            </tr>
                        </tfoot>
                    </table>
                    <p style="font-size:12px; text-align:center; margin:5px;">
                        --- Computer Generated ---
                    </p>
<?php    
            // --------------------------
            // Payment Method Handling
            // --------------------------
            $message_notif = '';
            
            if ($paymentMethod === 'transfer') {
                ?>
                <fieldset style="border:1px solid #ccc; padding:10px 15px; margin-bottom:15px; box-shadow:0 4px 8px rgba(0,0,0,0.1); border-radius:8px;">
                    <legend style="padding:0 10px; font-size:12px; border:none; width:auto;">
                        Bank Transfer Information
                    </legend>
                    
                    <!-- Data info at the top -->
                    <div style="text-align:left; margin-bottom:8px;">
                        <span style="font-size:12px;" class="small">Account Name:   </span> <b><?= $rowHeader['naakaun'] ?></b><br>
                        <span style="font-size:12px;" class="small">Bank Name:      </span> <b><?= $rowHeader['bank'] ?></b><br>
                        <span style="font-size:12px;" class="small">Account No:     </span> <b><?= $rowHeader['noakaun'] ?></b>
                    </div>
                
                    <!-- Instruction -->
                    <div style="text-align:left; font-size:12px;">
                        <p style="margin:0 0 5px 0; font-size:12px;">
                             Pay invoice <b class="text-danger"><?= $invoice_no ?></b> via bank transfer (details above), then follow the steps below:
                        </p>
                        <ul style="margin-left:20px; font-size:12px;">
                            <li>Take a screenshot or photo of your payment receipt.</li>
                            <li>Login to the system and upload the receipt via the <b>Order List</b> menu.</li>
                            <li>Wait for admin verification. You will be notified once your payment has been confirmed.</li>
                        </ul>
                    </div>
                </fieldset>


                <?php
            } elseif ($paymentMethod === 'cash') {
                ?>
                <fieldset style="border:1px solid #ccc; padding:10px 15px; margin-bottom:15px; box-shadow:0 4px 8px rgba(0,0,0,0.1); border-radius:8px;">
                    <legend style="padding:0 10px; font-size:12px; border:none; width:auto;">
                        Bank Transfer Information
                    </legend>
                    
                    <!-- Instruction -->
                    <div style="text-align:left; margin-bottom:8px; font-size:12px;">
                        <p style="margin:0 0 5px 0; font-size:12px;">
                            Please settle your invoice <b class="text-danger"><?= $invoice_no ?></b> at the counter, and then follow the steps below:
                        </p>
                        <ul style="margin-left:20px; font-size:12px;">
                            <li>Make your payment directly at the counter.</li>
                            <li>Collect your official receipt after payment is completed.</li>
                            <li>A copy of the receipt will also be sent to your registered email address.</li>
                        </ul>
                    </div>
                </fieldset>
                <?php
            
                // Hantar email untuk cash
                $to = $customer['email'];
                $subject = "Cash Payment Required";
                $body = "Please settle your invoice $invoice_no at the counter. Receipt will be given at the counter and via email.";
                $headers = "From: billing@yourcompany.com";
                mail($to, $subject, $body, $headers);
            }
?>               
            </div>
            <!-- End Invoice Print Area -->
    <?php
            // --------------------------
            // Get inserted invoice status
            // --------------------------
            $sqlStatus = "SELECT invoice_status, payment_status, packaging_status, shipping_status 
                          FROM invoice 
                          WHERE invoice_no = ?";
            $stmtStatus = $con->prepare($sqlStatus);
            $stmtStatus->bind_param("s", $invoice_no);
            $stmtStatus->execute();
            $resStatus = $stmtStatus->get_result();
            $status = $resStatus->fetch_assoc();
            ?>
            
            <style>
            .progress-area {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-top:30px;
                gap: 20px;
            }
            
            .progress-tracker {
                display: flex;
                justify-content: space-between;
                flex: 1;
                margin: 0;
                padding: 0;
                list-style: none;
            }
            .progress-tracker li {
                flex: 1;
                text-align: center;
                position: relative;
                font-size: 13px;
                color: #999;
            }
            .progress-tracker li::before {
                content: "";
                width: 20px;
                height: 20px;
                background: #ccc;
                border-radius: 50%;
                display: block;
                margin: 0 auto 8px;
            }
            .progress-tracker li::after {
                content: "";
                position: absolute;
                top: 10px;
                left: 50%;
                width: 100%;
                height: 4px;
                background: #ccc;
                z-index: -1;
            }
            .progress-tracker li:last-child::after {
                display: none;
            }
            .progress-tracker li.active {
                color: #4CAF50;
                font-weight: bold;
            }
            .progress-tracker li.active::before {
                background: #4CAF50;
            }
            .progress-tracker li.paid::before {
                background: #2196F3; /* biru untuk Paid */
            }
            .progress-tracker li.packaged::before {
                background: #9C27B0; /* ungu untuk Packaging */
            }
            .progress-tracker li.shipped::before {
                background: #FF9800; /* oren untuk Shipped */
            }
            .progress-tracker li.delivered::before {
                background: #4CAF50; /* hijau untuk Delivered */
            }
            
            .progress-button button,
            .progress-button a {
                white-space: nowrap;
            }
            
            /* Responsive: biar horizontal scroll bila screen kecil */
            @media(max-width:768px){
                .progress-area {
                    overflow-x: auto;
                    -webkit-overflow-scrolling: touch;
                }
                .progress-tracker {
                    flex-wrap: nowrap;
                    min-width: 600px; /* boleh adjust ikut bilangan step */
                }
                .progress-tracker li {
                    flex: 0 0 auto;
                    min-width: 100px; /* bagi spacing setiap step */
                }
            }
            
            @media print {
                body * {
                    visibility: hidden;
                }
                #printArea, #printArea * {
                    visibility: visible;
                }
                #printArea {
                    position: absolute;
                    left: 0;
                    top: 0;
                    width: 100%;
                    height: auto;
                }
                @page {
                    size: A4;
                    margin: 10mm;
                }
            }
    </style>

            <div class="progress-area">
                <ul class="small progress-tracker">
                    <li style="font-size:10px;" class="small <?= ($status['invoice_status']=='Issued') ? 'active' : '' ?>">
                        Invoice Issued
                    </li>
                    <li style="font-size:10px;" class="small <?= ($status['payment_status']=='Paid') ? 'active paid' : '' ?>">
                        Payment
                    </li>
                    <li style="font-size:10px;" class="small <?= ($status['packaging_status']=='Packed') ? 'active packaged' : '' ?>">
                        Packaging
                    </li>
                    <li style="font-size:10px;" class="small <?= ($status['shipping_status']=='Shipped') ? 'active shipped' : '' ?>">
                        Shipping
                    </li>
                    <li style="font-size:10px;" class="small <?= ($status['shipping_status']=='Delivered') ? 'active delivered' : '' ?>">
                        Delivered
                    </li>
                </ul>
            
                <!-- Pay / Print Button -->
                <div class="progress-button">
                    <?php if (strtolower($paymentMethod) == "fpx"): ?>
                        <!-- Print Button -->
                            <button onclick="printInvoice()" style="background:#007bff; color:#fff; padding:10px 20px; border:none; border-radius:5px;">
                                PRINT
                            </button>
                            <a href="pay_fpx.php?invoice=<?= urlencode($invoice_no) ?>" 
                               style="background:#28a745; color:#fff; padding:10px 20px; text-decoration:none; border-radius:5px;">PAY NOW</a>
                        <?php else: ?>
                            <button onclick="printInvoice()" style="background:#007bff; color:#fff; padding:10px 20px; border:none; border-radius:5px;">
                                PRINT
                            </button>
                    <?php endif; ?>
                </div>
            </div>
            <script>
            function printInvoice() {
                window.print();
            }
            </script>
    
        </div>
    </div>
    <?php
}







    function generateInvoiceNumber($con) {
        $year  = date("Y");
        $month = date("m");
    
        // Get the last invoice for current year & month
        $sql = "SELECT invoice_no 
                  FROM transactions 
                 WHERE invoice_no LIKE 'INV.$year.$month.%'
                 ORDER BY id DESC LIMIT 1";
        $res = mysqli_query($con, $sql);
        $row = mysqli_fetch_assoc($res);
    
        if ($row && !empty($row['invoice_no'])) {
            $parts = explode(".", $row['invoice_no']);
            $lastNumber = intval(end($parts)) + 1;
        } else {
            $lastNumber = 1;
        }
    
        return "INV.$year.$month." . str_pad($lastNumber, 4, "0", STR_PAD_LEFT);
    }
    
    
    function saveTransaction($con, $paymentMethod) {
        $qty   = (int) $_POST['qty'];
        $nilai = (float) $_POST['nilai_value'];
        $amount = $qty * $nilai;
    
        $invoiceNo = generateInvoiceNumber($con);
    
        $telefon = reKod("telefon", "ahli", "id", $_SESSION['aidi']);
        $telefon = preg_replace('~\D~', '', $telefon);
        if (substr($telefon, 0, 1) == "0") $telefon = "6" . $telefon;
    
        $billname = "WEPAYYOURCOST.COM";
        $billdesc = "Buy $qty PIN via $paymentMethod";
    
        $sql = "INSERT INTO transactions (
                    invoice_no, billName, billDescription, billTo, billEmail, billPhone,
                    billStatus, userName, billcreatedate, billpaymentAmount, userid, billcode
                ) VALUES (
                    '".$invoiceNo."', '".$billname."', '".$billdesc."', 
                    '".mysqli_real_escape_string($con, $_SESSION['namapenuh'])."', 
                    '".mysqli_real_escape_string($con, $_SESSION['email'])."', 
                    '".$telefon."', 
                    'pending', 
                    '".mysqli_real_escape_string($con, $_SESSION['usr'])."', 
                    NOW(), 
                    '".$amount."', 
                    '".$_SESSION['aidi']."', 
                    '".substr(md5(uniqid()),0,8)."'
                )";
    
        mysqli_query($con, $sql);
    
        return [$invoiceNo, $billdesc, $qty, $nilai, $amount];
    }



?>