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

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

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

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

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

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


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



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

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

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

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

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

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

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

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

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

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


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


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

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







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

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

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

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

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

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

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

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


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

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

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

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


    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;
    $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'
    ];


    // --------------------------
    // Generate invoice number
    // --------------------------

    $year   = date("Y");
    $month  = date("m");
    $prefix = "INV{$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)
        $numPart = preg_replace('/^' . preg_quote($prefix, '/') . '/', '', $invoiceNo);
    
        if (is_numeric($numPart)) {
            $lastNumber = intval($numPart) + 1;
        }
    }
    
    // ✅ Final invoice number
    $invoice_no = $prefix . str_pad($lastNumber, 6, "0", STR_PAD_LEFT);
    
    // 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, customer_id, package_id, package_name, price, qty_set, qty_total, discount, shipping_fee, grand_total, payment_method, shipping_method, ship_name, ship_address, ship_postcode, ship_city, ship_state, ship_phone, ship_email) 
        VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
    $stmt->bind_param(
        "siisdiiddssssssssss",
        $invoice_no,
        $customer['id'],
        $package['id'],
        $package['name'],
        $package['price'],
        $package['qty_set'],
        $package['qty'],
        $package['discount'],
        $package['shipping'],
        $grand_total,
        $paymentMethod,
        $package['shipping_method'],
        $customer['name'],
        $customer['address'],
        $customer['postcode'],
        $customer['city'],
        $customer['state'],
        $customer['phone'],
        $customer['email']
    );
    $stmt->execute();
    
    
    // --------------------------
    // Display invoice template
    // --------------------------
    ?>
    <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;">
        <!-- 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   }   ?>
        <!-- Invoice Header -->
        
        <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:center; 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>
            <img src='<?= $filename ?>' alt='QR Code' style="width:80px; height:80px;">
        </div>
        
        <!-- Invoice Details -->
        <div>
            <div style="margin-bottom:5px;">
                <span  class="text-right"style="font-size:10px; display:inline-block; width:60px;">No:</span>
                <span style="font-size:12px;"><?= $invoice_no ?></span>
            </div>
            <div style="margin-bottom:5px;">
                <span class="text-right" style="font-size:10px; display:inline-block; width:60px;">Date:</span>
                <span style="font-size:12px;"><?= date("d/m/Y") ?></span>
            </div>
            <div>
                <span class="text-right" style="font-size:10px; display:inline-block; width:60px;">Payment:</span>
                <span style="font-size:12px;"><?= htmlspecialchars($paymentMethod) ?></span>
            </div>
        </div>
    </div>

</div>

        
        </div>



        <!-- Items Table -->
        <table width="100%" border="1" cellspacing="0" cellpadding="8" style="margin-top:20px; border-collapse:collapse;">
            <tr style="background:#f0f0f0;">
                <th>Item</th>
                <th>Price (RM)</th>
                <th>Qty</th>
                <th>Discount (RM)</th>
                <th>Shipping (RM)</th>
                <th>Total (RM)</th>
            </tr>
            <tr>
                <td><?= htmlspecialchars($package['name']) ?></td>
                <td style="text-align:right;"><?= number_format($package['price'],2) ?></td>
                <td style="text-align:center;"><?= $package['qty'] ?></td>
                <td style="text-align:right;"><?= number_format($package['discount'],2) ?></td>
                <td style="text-align:right;"><?= number_format($package['shipping'],2) ?></td>
                <td style="text-align:right;"><?= number_format($grand_total,2) ?></td>
            </tr>
        </table>

        <!-- Progress Status -->
        <div style="margin-top:20px;">
            <strong>Invoice Status:</strong> Draft<br>
            <strong>Payment Status:</strong> Pending<br>
            <strong>Shipping Status:</strong> Pending
        </div>

        <!-- Pay Button -->
        <div style="margin-top:30px; text-align:right;">
            <?php if (strtolower($paymentMethod) == "fpx"): ?>
                <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="window.print()" style="background:#007bff; color:#fff; padding:10px 20px; border:none; border-radius:5px;">PRINT</button>
            <?php endif; ?>
        </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];
    }



?>