<?php
session_start();

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

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

    $nilaipin = reKod("nilaipin", "komisen", "id", 1);
    
    // PIN value dari komisen
    $rowPv = mysqli_fetch_array(mysqli_query($con, "SELECT nilaipin FROM komisen"));
    $pv = $rowPv['nilaipin'] ?? 0;
    
    // TAX dari setting
    $cukai = mysqli_fetch_array(mysqli_query($con, "SELECT tax FROM setting"));
    $tax = $cukai['tax'] ?? 0;
    
    
    $aidi = $_SESSION['aidi'] ?? 0;

    $userDetail = [
                    'nama' => '',
                    'alamat' => '',
                    'bandar' => '',
                    'poskod' => '',
                    'negeri' => '',
                    'telefon' => '',
                    'email' => ''
                ];

                if ($aidi) {
                    $sql = "SELECT * FROM ahli WHERE id = ?";
                    $stmt = mysqli_prepare($con, $sql);
                    mysqli_stmt_bind_param($stmt, "i", $aidi);
                    mysqli_stmt_execute($stmt);
                    $result = mysqli_stmt_get_result($stmt);
                    if ($row = mysqli_fetch_assoc($result)) {
                        $userDetail = $row;
                    }
                    mysqli_stmt_close($stmt);
                }
?>

        <div id="page-wrapper" >
            <div id="page-inner">
                <div class="row">
                    <div class="col-md-12">
                     <h2>New Registration</h2>
                    </div>
                </div>
            <hr />
<?
if (isset($_POST[md5("fpx" . $_SESSION['aidi'])])) {
    registration("fpx");
} elseif (isset($_POST[md5("transfer" . $_SESSION['aidi'])])) {
    registration("transfer");
} elseif (isset($_POST[md5("cash" . $_SESSION['aidi'])])) {
    registration("cash");
} else {


        // Ambil semua discount utk category Stock
        $discounts = [];
        $sql = "SELECT qty, value FROM discount WHERE name='Stock' ORDER BY qty ASC";
        $result = mysqli_query($con, $sql);
        while ($row = mysqli_fetch_assoc($result)) {
            $discounts[] = $row;
        }
        
        // Ambil shipping ikut negeri
        $shippingCosts = [];
        $sql = "SELECT name, qty, value FROM shipping_cost ORDER BY name, qty ASC";
        $result = mysqli_query($con, $sql);
        while ($row = mysqli_fetch_assoc($result)) {
            $shippingCosts[$row['name']][] = [
                "qty" => (int)$row['qty'],
                "value" => (float)$row['value']
            ];
        }

?>

        <div class="panel panel-default">
          <div class="panel-heading">Select Package</div>
          <div class="panel-body">
            <div style="display:flex; gap:10px; align-items:center; margin-bottom:15px;">
                <div id="step1Indicator" style="flex:1;">
                    <strong>Step 1</strong> — Profile Info
                    <div style="height:6px; background:#eee; border-radius:3px; margin-top:6px;">
                        <div id="bar1" style="width:100%; height:6px; background:#87B6C9; border-radius:3px;"></div>
                    </div>
                </div>
                <div id="step2Indicator" style="flex:1;">
                    <strong>Step 2</strong> — Package & Payment
                    <div style="height:6px; background:#eee; border-radius:3px; margin-top:6px;">
                        <div id="bar2" style="width:0%; height:6px; background:#87B6C9; border-radius:3px;"></div>
                    </div>
                </div>
            </div>

            <!-- Main form — two-step wizard (single form, multi-step) -->
            <form id="regForm" role="form" method="post" enctype="multipart/form-data">
                <!-- Hidden to indicate step being submitted -->
                <input type="hidden" name="step" id="form_step" value="1" />

                <!-- ---------- STEP 1: PROFILE ----------- -->
                <div id="step1_fieldset" style="border:0;">
                    <div class="row" >
                        <div class="col-md-6">
                            <fieldset style="border:1px solid #ccc; padding: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;">Profile Photo</legend>

                                <div style="margin-bottom:8px;">
                                    <?php
                                    $imgUrl = 'assets/img/find_user.png';
                                    ?>
                                    <div style="
                                        display: flex;
                                        justify-content: center;
                                        align-items: center;
                                        width: 50%;
                                        max-width: 220px;
                                        aspect-ratio: 1/1;
                                        margin: 0 auto 15px;
                                        border: 2px solid #ddd;
                                        border-radius: 10px;
                                        overflow: hidden;
                                        background: #f9f9f9;
                                    ">
                                        <img id="previewPhoto" src="<?= htmlspecialchars($imgUrl) ?>" alt="Profile" style="width: 100%; height: 100%; object-fit: cover;">
                                    </div>

                                </div>
                                <div class="form-group">
                                    <label>Upload Photo (JPG/PNG/WEBP)</label>
                                    <input type="file" name="profile_photo" id="profile_photo" accept="image/*" class="form-control" />
                                    <small class="text-muted">Please provide photo as passport size.</small>
                                </div>
                            </fieldset>
                            <fieldset style="border:1px solid #ccc; padding: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;">Login Details</legend>
                                <!-- NEW: Username & bank/beneficiary fields -->
                                <div class="form-group">
                                    <label>Username <small id="username_status" style="margin-left:8px; font-weight:normal;"></small></label>
                                    <input type="text" name="username" id="username" class="form-control" value="" placeholder="Choose a username" autocomplete="off">
                                </div>
                            </fieldset>
                        </div>
                        <div class="col-md-6">
                            <fieldset style="border:1px solid #ccc; padding: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;">Personal Details</legend>

                                <div class="form-group">
                                    <label>Full Name</label>
                                    <input type="text" name="nama" id="nama" class="form-control" required value="">
                                </div>
                                
                                <div class="form-group">
                                    <label>MyKad / Passport</label>
                                    <input type="text" name="kp" id="kp" class="form-control" required value="">
                                </div>

                                <div class="form-group">
                                    <label>Address</label>
                                    <input type="text" name="alamat" id="alamat" class="form-control" required value="">
                                </div>

                                <div class="row">
                                    <div class="col-md-4 form-group">
                                        <label>Postcode</label>
                                        <input type="text" name="poskod" id="poskod" class="form-control" required value="">
                                    </div>
                                    <div class="col-md-4 form-group">
                                        <label>City</label>
                                        <input type="text" name="bandar" id="bandar" class="form-control" required value="">
                                    </div>
                                    <div class="col-md-4 form-group">
                                        <label>State</label>
                                        <input type="text" name="negeri" id="negeri" class="form-control" required value="">
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label>Phone</label>
                                    <input type="text" name="telefon" id="telefon" class="form-control" required value="">
                                </div>

                                <div class="form-group">
                                    <label>Email</label>
                                    <input type="email" name="email" id="email" class="form-control" required value="">
                                </div>
                            </fieldset>
                            <fieldset style="border:1px solid #ccc; padding: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 Details</legend>
                                <div class="form-group">
                                    <label>Bank Name</label>
                                    <input type="text" name="bank" id="bank" class="form-control" value="">
                                </div>
                                <div class="form-group">
                                    <label>Account Name</label>
                                    <input type="text" name="naakaun" id="naakaun" class="form-control" value="">
                                </div>
                                <div class="form-group">
                                    <label>Account No.</label>
                                    <input type="text" name="noakaun" id="noakaun" class="form-control" value="">
                                </div>

                                <div class="form-group">
                                    <label>Beneficiary Name</label>
                                    <input type="text" name="bnama" id="bnama" class="form-control" value="">
                                </div>
                                <div class="form-group">
                                    <label>Beneficiary MyKad / Passport</label>
                                    <input type="text" name="bkp" id="bkp" class="form-control" value="">
                                </div>
                                <div class="form-group">
                                    <label>Relation to Beneficiary</label>
                                    <input type="text" name="brelation" id="brelation" class="form-control" value="">
                                </div>

                            </fieldset>
                        </div>


                    </div>

                    <div style="display:flex; justify-content:flex-end; gap:10px; margin-top:15px;">
                        <button type="button" id="toStep2" class="btn btn-primary">Next &raquo;</button>
                    </div>
                </div>
                <!-- ---------- STEP 2: PACKAGE / PAYMENT / SHIPPING ----------- -->
                <div id="step2_fieldset" style="border:0;"> 
                      <div class="row">
                
                        <!-- Package List -->
                        <div style="padding-top:20px;">
                            <?php
                              $sql = "SELECT * FROM packages ORDER BY price ASC";
                              $result = mysqli_query($con, $sql);
                              while ($p = mysqli_fetch_assoc($result)) {
                                  $pinNeeded = ceil($p['price'] / $pv);
                            ?>
                            <div class="form-group col-md-4" style="display:flex; flex-wrap:wrap; gap:15px;">
                                <label style="flex:1; cursor:pointer; border:2px solid #eee; border-radius:10px; text-align:center; background:#87B6C9; color:#fff; box-shadow:0 4px 8px rgba(0,0,0,0.1); border-radius:8px;">
                                  <input    type="radio" 
                                            name="nilai_value" 
                                            value="<?= $p['price'] ?>" 
                                            data-qtyset="<?= $p['qty_set'] ?>" 
                                            data-name="<?= htmlspecialchars($p['name']) ?>" 
                                            data-id="<?= $p['id'] ?>"
                                            onclick="calculate()"
                                            style="margin-bottom:10px;"
                                            required />
        
                                  
                
                                  <div>
                                    <img src="assets2/ico/tls2u.png" height="200" alt="TLS2U.COM">
                                  </div>
                
                                  <div style="font-weight:bold; font-size:10px; padding-bottom:15px; ">( <?= $p['qty_set'] ?> PAX / set  |  <?= $pinNeeded ?> PIN )</div>
                
                                    <div style="border-radius: 0 0 5px 5px; padding:15px; display: flex; justify-content: space-between; align-items: center; background-color:white;" >
                                        <div class="text-left" style="display: flex; flex-direction: column;">
                                          <span style="font-weight: bold; font-size: 16px; color: #000;">
                                            <?= htmlspecialchars($p['name']) ?>
                                          </span>
                                        </div>
                                        <div style="font-weight: bold; font-size: 20px; color: red; padding: 2px 6px; border-radius: 4px;">
                                            <span class="small" style="font-weight: normal; font-size: 12px;">RM</span> 
                                            <?= number_format($p['price'], 2) ?>
                                        </div>
                                    </div>
                                </label>
                            </div>
                            <?php } ?>
                        </div>
                        <input type="hidden" name="package_id" id="package_id" />
                        <input type="hidden" name="package_name" id="package_name" />
        
                        <!-- Payment Method -->
                        <div class="col-md-6" style="padding-top:20px;">
                          <fieldset style="border:1px solid #ccc; padding: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;">Payment Method</legend>
                            <div style="display:flex; gap:15px; align-items:center;">
                              <label><input type="radio" name="payment_method" value="fpx"  disabled                /> FPX</label>
                              <label><input type="radio" name="payment_method" value="transfer"                     /> Bank Transfer</label>
                              <label><input type="radio" name="payment_method" value="cash" required                /> Cash</label>
                              <label><input type="radio" name="payment_method" value="stockist" ID="payStockist"    /> Pay to Stockist</label>
                            </div>
                          </fieldset>
                        </div>
                
                        <!-- Shipping Method -->
                        <div class="col-md-6" style="padding-top:20px;">
                          <fieldset style="border:1px solid #ccc; padding: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;">Shipping Method</legend>
                            <div style="display:flex; gap:15px; align-items:center;">
                              <label><input type="radio" name="shipping_method" value="selfcollect" required            /> Self Collect</label>
                              <label><input type="radio" name="shipping_method" value="courier"                         /> Courier Services</label>
                              <label><input type="radio" name="shipping_method" value="stockist" id="pickupStockist"    /> Pickup from Stockist</label>
                            </div>
                          </fieldset>
                        </div>
                
                        <!-- Shipping Address -->
                        <div class="col-md-12" style="padding-top:20px;">
                          <fieldset style="border:1px solid #ccc; padding: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;">Shipping Address</legend>
                            <div class="mb-3">
                              <label>
                                <input type="checkbox" id="useCurrentAddress" checked onchange="toggleAddress()" > Use current address
                              </label>
                            </div>
                            <div class="mb-3">
                              <span class="form-label small mb-1">Name</span>
                              <input type="text" class="form-control" id="ship_name" name="ship_name" value="" readonly required />
                            </div>
                            <div class="mb-3">
                              <span class="form-label small mb-1">Address</span>
                              <input type="text" class="form-control" id="ship_address" name="ship_address" value="" readonly required />
                            </div>
                            <div class="row">
                              <div class="col-md-4 mb-3">
                                <span class="form-label small mb-1">Postcode</span>
                                <input type="text" class="form-control" id="ship_postcode" name="ship_postcode" value="" readonly required />
                              </div>
                              <div class="col-md-4 mb-3">
                                <span class="form-label small mb-1">City</span>
                                <input type="text" class="form-control" id="ship_city" name="ship_city" value="" readonly required />
                              </div>
                              <div class="col-md-4 mb-3">
                                <span class="form-label small mb-1">State</span>
                                <input type="text" class="form-control" id="ship_state" name="ship_state" value="" readonly required />
                              </div>
                            </div>
                            <div class="row">
                              <div class="col-md-6 mb-3">
                                <span class="form-label small mb-1">Phone</span>
                                <input type="text" class="form-control" id="ship_phone" name="ship_phone" value="" readonly required />
                              </div>
                              <div class="col-md-6 mb-3">
                                <span class="form-label small mb-1">Email</span>
                                <input type="email" class="form-control" id="ship_email" name="ship_email" value="" readonly required />
                              </div>
                            </div>
                          </fieldset>
                        </div>
                
                        <!-- Terms & Conditions -->
                        <div class="col-md-6" style="padding-top:20px;">
                          <fieldset style="border:1px solid #ccc; padding: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;">Terms & Conditions</legend>
                            <!-- Scrollable box -->
                              <div class="small" style="border:1px solid #ddd; padding:10px; height:150px; overflow-y:auto; font-size:13px; background:#f9f9f9;">
                                <p><strong>1. Payment</strong><br>
                                All payments for stock purchases must be made through the provided methods (FPX, Bank Transfer or Cash). No orders will be processed without payment confirmation.</p>
                            
                                <p><strong>2. Delivery & Self Collection</strong><br>
                                - <strong>Self Collect</strong>: Customers must collect their stock at the designated location within <u>7 working days</u> after payment confirmation.<br>
                                - <strong>Courier Services</strong>: Shipping charges apply. The company is not responsible for delays or damages during delivery handled by third-party couriers.</p>
                            
                                <p><strong>3. Return & Exchange Policy</strong><br>
                                - All stock purchases are <u>final</u> and <u>non-refundable</u> once the transaction is completed.<br>
                                - Exchange is only allowed if the received stock is damaged or incorrect. Issues must be reported within <u>48 hours</u> of receipt.</p>
                            
                                <p><strong>4. Customer Responsibility</strong><br>
                                - Customers are responsible for ensuring that the provided shipping address and personal details are accurate.<br>
                                - The company will not be held liable for any losses resulting from inaccurate information provided by the customer.</p>
                            
                                <p><strong>5. Changes to Terms</strong><br>
                                The company reserves the right to amend or update these Terms & Conditions at any time without prior notice.</p>
                              </div>
                            <div style="margin-top:10px;">
                              <input type="checkbox" id="terms" required> <label for="terms"> I agree to the Terms & Conditions. </label>
                            </div>
                          </fieldset>
                        </div>
                
                        <!-- Totals -->
                        <div class="col-md-6" style="padding-top:30px;">
                          <div style="display:flex; gap:10px; margin-bottom:15px;">
                            <input type="number" class="form-control" style="width:150px;" value="1" name="qty_sets" id="bils" placeholder="Qty (Set)" oninput="calculate()" min="1" readonly />
                            <input type="hidden" class="form-control" style="width:150px;" value="1" name="qty_set" id="bil" placeholder="Qty (Set)" oninput="calculate()" min="1" required />
                            <span class="small">Qty (Set)</span>
                          </div>
                          <div style="display:flex; gap:10px; margin-bottom:15px;">
                            <input type="text" class="form-control" style="width:150px;"   id="total_qty1" readonly />
                            <input type="hidden" class="form-control" style="width:150px;"   name="qty_total" id="total_qty" />
                            <span class="small">Total Unit</span>
                          </div>
                          <div style="display:flex; gap:10px; margin-bottom:15px;">
                            <input type="number" class="form-control" style="width:150px;" id="discount1" readonly />
                            <input type="hidden" class="form-control" style="width:150px;" name="discount" id="discount" />
                            <span class="small">Discount (RM)</span>
                          </div>
                          <div style="display:flex; gap:10px; margin-bottom:15px;">
                            <input type="number" class="form-control" style="width:150px;" id="shipping1" readonly />
                            <input type="hidden" class="form-control" style="width:150px;" name="shipping_fee" id="shipping" />
                            <span class="small">Shipping (RM)</span>
                          </div>
                          <div style="display:flex; gap:10px; margin-bottom:15px;">
                            <input type="number" class="form-control" style="width:150px;" id="tax1" readonly />
                            <input type="hidden" class="form-control" style="width:150px;" name="tax" id="tax" />
                            <span class="small">Tax (RM)</span>
                          </div>
                          <div style="display:flex; gap:10px; margin-bottom:15px;">
                            <input type="number" class="form-control" style="width:150px;" id="jumlah1" readonly />
                            <input type="hidden" class="form-control" style="width:150px;" name="grand_total" id="jumlah" />
                            <span class="small">Total (RM)</span>
                          </div>
                                
                        </div>
                
                      </div>
                      <div style="display:flex; justify-content:space-between; gap:10px; margin-top:15px;">
                        <button type="button" id="backToStep1" class="btn btn-primary">&laquo; Back</button>

                        <!-- Register triggers server-side step=2 -->
                        <div style="display:flex; gap:10px;">
                                <!-- FPX button -->
                                <div id="fpx_btn" class="payment-btn" style="display:none;">
                                  <button type="<?= $butang ?>" name="<?= md5("buynowfpx".$_SESSION['aidi']) ?>" class="btn btn-primary w-100">Pay FPX</button>
                                </div>
                                
                                <!-- Bank Transfer button -->
                                <div id="transfer_btn" class="payment-btn"  style="display:none;">
                                  <button type="<?= $butang ?>" name="<?= md5("transfer".$_SESSION['aidi']) ?>" class="btn btn-success w-100">Register & Pay Bank Transfer</button>
                                </div>
                                
                                <!-- Cash button -->
                                <div id="cash_btn" class="payment-btn"   style="display:none;">
                                  <button type="<?= $butang ?>" name="<?= md5("cash".$_SESSION['aidi']) ?>" class="btn btn-success w-100">Register & Pay Cash</button>
                                </div>
                        </div>
                    </div>
                </div>
            </form>
          </div>
        </div>

        <script>
        const discountTable = <?= json_encode($discounts) ?>;
        const shippingTable = <?= json_encode($shippingCosts) ?>;
        
          // Automatically copy personal → shipping
          function syncShipping() {
            document.getElementById("ship_name").value     = document.getElementById("nama").value;
            document.getElementById("ship_address").value  = document.getElementById("alamat").value;
            document.getElementById("ship_postcode").value = document.getElementById("poskod").value;
            document.getElementById("ship_city").value     = document.getElementById("bandar").value;
            document.getElementById("ship_state").value    = document.getElementById("negeri").value;
            document.getElementById("ship_phone").value    = document.getElementById("telefon").value;
            document.getElementById("ship_email").value    = document.getElementById("email").value;
          }
        
          // Enable/disable shipping fields based on checkbox
          function toggleAddress() {
            const checked = document.getElementById("useCurrentAddress").checked;
            const fields = ["ship_name", "ship_address", "ship_postcode", "ship_city", "ship_state", "ship_phone", "ship_email"];
        
            fields.forEach(id => {
              document.getElementById(id).readOnly = checked;
            });
        
            if (checked) syncShipping();
          }
        
          // Auto-sync whenever personal fields change (if checkbox is checked)
          const personalFields = ["nama", "alamat", "poskod", "bandar", "negeri", "telefon", "email"];
          personalFields.forEach(id => {
            document.getElementById(id).addEventListener("input", function () {
              if (document.getElementById("useCurrentAddress").checked) syncShipping();
            });
          });
        
        function calculate() {
            const sets = parseInt(document.getElementById("bil").value) || 0;
        
            // ✅ Get selected package
            const packageRadios = document.getElementsByName("nilai_value");
            let price = 0;
            let qtySet = 1;
            for (let i = 0; i < packageRadios.length; i++) {
                if (packageRadios[i].checked) {
                    price = parseFloat(packageRadios[i].value) || 0;
                    qtySet = parseInt(packageRadios[i].getAttribute("data-qtyset")) || 1;
                    break;
                }
            }
        
            // ✅ Calculate totals
            const subtotal = sets * price;
            const totalQty = sets * qtySet;
        
            // update both readonly & hidden field
            document.getElementById("total_qty1").value = totalQty;
            document.getElementById("total_qty").value  = totalQty;
        
            // ✅ Discount
            let discount = 0;
            discountTable.forEach(d => {
                //if (totalQty >= d.qty) discount = parseFloat(d.value) || 0;
                if (totalQty >= d.qty) discount = 0;
            });
            document.getElementById("discount1").value = discount.toFixed(2);
            document.getElementById("discount").value  = discount.toFixed(2);
            
            // ✅ Tax ikut Malaysia (SST 6%)
            const taxRate = <?= $tax ?> / 100; 
            const taxableAmount = subtotal - discount; // hanya barang
            const tax = taxRate * taxableAmount;
            document.getElementById("tax1").value = tax.toFixed(2);
            document.getElementById("tax").value  = tax.toFixed(2);

        
            // ✅ Shipping by state
            let shippingFee = 0;
            const shippingSelected = document.querySelector('input[name="shipping_method"]:checked');
            const state = document.getElementById("ship_state") ? document.getElementById("ship_state").value : null;
        
            if (shippingSelected && shippingSelected.value === 'courier' && state && shippingTable[state]) {
                shippingTable[state].forEach(s => {
                    if (totalQty >= s.qty) shippingFee = parseFloat(s.value) || 0;
                });
            }
            document.getElementById("shipping1").value = shippingFee.toFixed(2);
            document.getElementById("shipping").value  = shippingFee.toFixed(2);
        
            // ✅ Final total
            const grandTotal = taxableAmount + tax + shippingFee;
            document.getElementById("jumlah1").value = grandTotal.toFixed(2);
            document.getElementById("jumlah").value  = grandTotal.toFixed(2);
        }
        
        // Events binding
        document.getElementById("bil").addEventListener('input', calculate);
        document.querySelectorAll('input[name="nilai_value"]').forEach(radio => {
            radio.addEventListener('change', function() {
                // run calculate function
                calculate();
        
                // update hidden inputs
                document.getElementById("package_id").value = this.getAttribute("data-id");
                document.getElementById("package_name").value = this.getAttribute("data-name");
            });
        });

        document.querySelectorAll('input[name="shipping_method"]').forEach(r => r.addEventListener('change', calculate));
        if (document.getElementById("ship_state")) {
            document.getElementById("ship_state").addEventListener('change', calculate);
        }
 
 
 
 
    // Wizard controls
    const step1Fieldset = document.getElementById('step1_fieldset');
    const step2Fieldset = document.getElementById('step2_fieldset');
    const formStepInput = document.getElementById('form_step');
    const bar1 = document.getElementById('bar1');
    const bar2 = document.getElementById('bar2');

    // Initialize: show step1, hide step2
    step1Fieldset.style.display = 'block';
    step2Fieldset.style.display = 'none';
    bar1.style.width = '100%';
    bar2.style.width = '0%';

    // NEXT: Step 1 → Step 2
    document.getElementById('toStep2').addEventListener('click', () => {
        // Basic validation
        const required = ['nama','alamat','poskod','bandar','negeri','telefon','email'];
        for (let id of required) {
            const el = document.getElementById(id);
            if (!el || !el.value.trim()) {
                alert('Please complete your profile before proceeding.');
                el && el.focus();
                return;
            }
        }

        // Move to step 2
        formStepInput.value = '2';
        step1Fieldset.style.display = 'none';
        step2Fieldset.style.display = 'block';
        bar1.style.width = '0%';
        bar2.style.width = '100%';
        window.scrollTo({ top: 0, behavior: 'smooth' });
    });

    // BACK: Step 2 → Step 1
    document.getElementById('backToStep1').addEventListener('click', () => {
        formStepInput.value = '1';
        step1Fieldset.style.display = 'block';
        step2Fieldset.style.display = 'none';
        bar1.style.width = '100%';
        bar2.style.width = '0%';
        window.scrollTo({ top: 0, behavior: 'smooth' });
    })
 
 
 
            
        // ✅ Payment Method Toggle
        function togglePaymentButtons() {
            // Hide all first
            document.querySelectorAll('.payment-btn').forEach(el => el.style.display = 'none');
    
            const selected = document.querySelector('input[name="payment_method"]:checked');
            if (!selected) return;
    
            if (selected.value === "fpx") {
                document.getElementById('fpx_btn').style.display = 'block';
            } else if (selected.value === "transfer") {
                document.getElementById('transfer_btn').style.display = 'block';
            } else if (selected.value === "cash") {
                document.getElementById('cash_btn').style.display = 'block';
            }
        }       
            
             // ✅ Payment Method event binding
        document.querySelectorAll('input[name="payment_method"]').forEach(r => {
            r.addEventListener('change', togglePaymentButtons);
        });
    
        // Run on load (in case something pre-selected)
        togglePaymentButtons();
        
        // ✅ Confirm Order Prompt
        function confirmOrder(e) {
            if (!confirm("Are you sure you want to confirm this order ?")) {
                e.preventDefault(); // stop form submission
                return false;
            }
            return true;
        }
        
        // ✅ Attach to all payment buttons
        document.addEventListener("DOMContentLoaded", () => {
            document.querySelectorAll(".payment-btn").forEach(btn => {
                btn.addEventListener("click", confirmOrder);
            });
        });


    // Preview uploaded image
    const profileInput = document.getElementById('profile_photo');
    if (profileInput) {
        profileInput.addEventListener('change', function(e) {
            const f = this.files[0];
            if (!f) return;
            const reader = new FileReader();
            reader.onload = function(ev) {
                document.getElementById('previewPhoto').src = ev.target.result;
            };
            reader.readAsDataURL(f);
        });
    }

    // Username live-check
    const usernameEl = document.getElementById('username');
    const usernameStatus = document.getElementById('username_status');

    if (usernameEl) {
        let debounceTimer = null;
        usernameEl.addEventListener('input', function () {
            const v = this.value.trim();
            usernameStatus.textContent = '';
            if (debounceTimer) clearTimeout(debounceTimer);
            if (!v) return;
            debounceTimer = setTimeout(() => {
                fetch('registration_check.php?q=' + encodeURIComponent(v))
                .then(r => r.json())
                .then(j => {
                    if (j.available) {
                        usernameStatus.style.color = 'green';
                        usernameStatus.textContent = 'available';
                    } else {
                        usernameStatus.style.color = 'red';
                        usernameStatus.textContent = 'taken';
                    }
                })
                .catch(err => {
                    usernameStatus.style.color = 'orange';
                    usernameStatus.textContent = 'error';
                });
            }, 350);
        });
    }


        document.getElementById("poskod").addEventListener("blur", function() {
          const code = this.value.trim();
          if (!code) return;
        
          fetch("postcode.json")
            .then(res => res.json())
            .then(data => {
              let found = false;
              // JSON root is an object with "state" array
              for (const state of data.state) {
                for (const city of state.city) {
                  if (city.postcode.includes(code)) {
                    document.getElementById("bandar").value = city.name;
                    document.getElementById("negeri").value = state.name;
                    found = true;
                    break;
                  }
                }
                if (found) break;
              }
        
              if (!found) {
                document.getElementById("bandar").value = "";
                document.getElementById("negeri").value = "";
                alert("Postcode not found in database.");
              }
            })
            .catch(err => console.error("Error loading postcode data:", err));
        });
        
        //////////////////////////////////////////////////////////
        //  FOR STOCKIST OPTION
        ////////////////////////////////////////////////////////// 
        
        const pay = document.getElementById('payStockist');
        const pickup = document.getElementById('pickupStockist');
        
        // Select both when either is selected
        pay.addEventListener('change', function () {
            pickup.checked = true;
        });
        
        pickup.addEventListener('change', function () {
            pay.checked = true;
        });
        
        // When ANY OTHER radio is selected → unselect both
        document.querySelectorAll('input[name="payment_method"], input[name="shipping_method"]').forEach(radio => {
            radio.addEventListener('change', function () {
                if (this.id !== 'payStockist' && this.id !== 'pickupStockist') {
                    pay.checked = false;
                    pickup.checked = false;
                }
            });
        });
        </script>



   

<? } ?>

    </div>

             <!-- /. PAGE INNER  -->

            </div>

<?

    include "_footer2.php";

}

?>

