<?php

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

    // helper: ensure uploads dir exists
    $uploadDir = __DIR__ . '/uploads/members/';
    if (!is_dir($uploadDir)) {
        @mkdir($uploadDir, 0755, true);
    }

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

    // Default userDetail
    $userDetail = [
        'id' => '',
        'nama' => '',
        'alamat' => '',
        'bandar' => '',
        'poskod' => '',
        'negeri' => '',
        'telefon' => '',
        'email' => '',
        'username' => '',
        'password' => '',
        'bank' => '',
        'naakaun' => '',
        'noakaun' => '',
        'bnama' => '',
        'bkp' => '',
        'brelation' => ''
    ];

    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 = array_merge($userDetail, $row);
        }
        mysqli_stmt_close($stmt);
    }

    // Messages
    $msg = "";
    $err = "";

    // Handle profile save (step 1) or registration (step 2)
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {

        // If user submitted Step 1 (save profile)
        if (isset($_POST['step']) && $_POST['step'] === '1') {
            // Collect fields (validate minimally)
            $nama = mysqli_real_escape_string($con, trim($_POST['nama'] ?? ''));
            $alamat = mysqli_real_escape_string($con, trim($_POST['alamat'] ?? ''));
            $bandar = mysqli_real_escape_string($con, trim($_POST['bandar'] ?? ''));
            $poskod = mysqli_real_escape_string($con, trim($_POST['poskod'] ?? ''));
            $negeri = mysqli_real_escape_string($con, trim($_POST['negeri'] ?? ''));
            $telefon = mysqli_real_escape_string($con, trim($_POST['telefon'] ?? ''));
            $email = mysqli_real_escape_string($con, trim($_POST['email'] ?? ''));

            // New fields
            $username = mysqli_real_escape_string($con, trim($_POST['username'] ?? ''));
            $bank = mysqli_real_escape_string($con, trim($_POST['bank'] ?? ''));
            $naakaun = mysqli_real_escape_string($con, trim($_POST['naakaun'] ?? ''));
            $noakaun = mysqli_real_escape_string($con, trim($_POST['noakaun'] ?? ''));
            $bnama = mysqli_real_escape_string($con, trim($_POST['bnama'] ?? ''));
            $bkp = mysqli_real_escape_string($con, trim($_POST['bkp'] ?? ''));
            $brelation = mysqli_real_escape_string($con, trim($_POST['brelation'] ?? ''));

            if (!$aidi) {
                $err = "Session invalid. Unable to update profile.";
            } else {
                // check username uniqueness if provided and changed
                if ($username !== '' && $username !== $userDetail['username']) {
                    $sql_check = "SELECT id FROM ahli WHERE username = ? AND id <> ?";
                    $stc = mysqli_prepare($con, $sql_check);
                    mysqli_stmt_bind_param($stc, "si", $username, $aidi);
                    mysqli_stmt_execute($stc);
                    $resc = mysqli_stmt_get_result($stc);
                    if ($rowc = mysqli_fetch_assoc($resc)) {
                        $err = "Username already taken. Choose another.";
                        mysqli_stmt_close($stc);
                    } else {
                        mysqli_stmt_close($stc);
                        // ok to proceed
                    }
                }

                if (!$err) {
                    // determine if we must generate password: generate if existing password empty (or null)
                    $generatePassword = false;
                    $plainPassword = '';
                    if ($username !== '') {
                        // if current stored password empty -> generate
                        if (empty($userDetail['password'])) {
                            $generatePassword = true;
                            $plainPassword = randomPass(); // from _functions.php
                            $passwordToStore = md5($plainPassword); // store MD5 to match varchar(32)
                        } else {
                            // keep existing password hash
                            $passwordToStore = $userDetail['password'];
                        }
                    } else {
                        // keep existing username/password if username empty
                        $username = $userDetail['username'];
                        $passwordToStore = $userDetail['password'];
                    }

                    // Update ahli table with new fields
                    $sql = "UPDATE ahli SET nama=?, alamat=?, bandar=?, poskod=?, negeri=?, telefon=?, email=?, username=?, password=?, bank=?, naakaun=?, noakaun=?, bnama=?, bkp=?, brelation=? WHERE id=?";
                    $stmt = mysqli_prepare($con, $sql);
                    mysqli_stmt_bind_param($stmt, "sssssssssssssssi",
                        $nama, $alamat, $bandar, $poskod, $negeri, $telefon, $email,
                        $username, $passwordToStore, $bank, $naakaun, $noakaun, $bnama, $bkp, $brelation,
                        $aidi
                    );
                    if (mysqli_stmt_execute($stmt)) {
                        $msg = "Profile saved.";
                        // refresh userDetail
                        $userDetail['nama'] = $nama;
                        $userDetail['alamat'] = $alamat;
                        $userDetail['bandar'] = $bandar;
                        $userDetail['poskod'] = $poskod;
                        $userDetail['negeri'] = $negeri;
                        $userDetail['telefon'] = $telefon;
                        $userDetail['email'] = $email;
                        $userDetail['username'] = $username;
                        $userDetail['bank'] = $bank;
                        $userDetail['naakaun'] = $naakaun;
                        $userDetail['noakaun'] = $noakaun;
                        $userDetail['bnama'] = $bnama;
                        $userDetail['bkp'] = $bkp;
                        $userDetail['brelation'] = $brelation;
                        if ($generatePassword) {
                            // show plaintext pass once (admin should copy)
                            $msg .= "<br><strong>Generated password:</strong> " . htmlspecialchars($plainPassword);
                        }
                    } else {
                        $err = "Failed to save profile.";
                    }
                    mysqli_stmt_close($stmt);
                }
            }

            // Handle photo upload if present (kept original)
            if (isset($_FILES['profile_photo']) && $_FILES['profile_photo']['error'] !== UPLOAD_ERR_NO_FILE) {
                $f = $_FILES['profile_photo'];
                if ($f['error'] === UPLOAD_ERR_OK) {
                    // basic mime check
                    $finfo = finfo_open(FILEINFO_MIME_TYPE);
                    $mime = finfo_file($finfo, $f['tmp_name']);
                    finfo_close($finfo);

                    $allowed = ['image/jpeg', 'image/png', 'image/webp', 'image/jpg'];
                    if (!in_array($mime, $allowed)) {
                        $err .= ($err ? "<br>" : "") . "Invalid image type. Use JPG/PNG/WEBP.";
                    } else {
                        // filename by username (as requested) — fallback to id if username missing
                        $username_for_file = $userDetail['username'] ?: ('user' . $aidi);
                        // sanitize filename fragment
                        $safeUsername = preg_replace('/[^a-zA-Z0-9_\-]/', '_', $username_for_file);
                        // always save as jpg for consistency (convert if needed) — but here we just keep original extension for simplicity
                        $ext = pathinfo($f['name'], PATHINFO_EXTENSION);
                        $ext = strtolower($ext);
                        // enforce jpg extension if jpeg
                        if ($mime === 'image/jpeg' || $ext === 'jpeg') $ext = 'jpg';

                        $target = $uploadDir . $safeUsername . '.' . $ext;

                        // move uploaded file
                        if (move_uploaded_file($f['tmp_name'], $target)) {
                            // Optionally convert PNG/webp to jpg to keep consistent filename as .jpg
                            $forceJpgPath = $uploadDir . $safeUsername . '.jpg';
                            // Try to convert to jpg using GD (if available)
                            $converted = false;
                            if (function_exists('imagecreatefromstring')) {
                                $imgData = @file_get_contents($target);
                                if ($imgData !== false) {
                                    $im = @imagecreatefromstring($imgData);
                                    if ($im !== false) {
                                        // save as jpeg
                                        @imagejpeg($im, $forceJpgPath, 88);
                                        imagedestroy($im);
                                        @unlink($target); // remove original
                                        $converted = true;
                                    }
                                }
                            }
                            if ($converted) {
                                $msg .= ($msg ? "<br>" : "") . "Profile photo uploaded.";
                            } else {
                                // if conversion not possible, rename to username.jpg if file is already jpg or leave original extension
                                if ($ext === 'jpg') {
                                    // ensure final name is {username}.jpg
                                    @rename($target, $forceJpgPath);
                                } else {
                                    // not jpg and conversion failed — try to still rename adding extension
                                    @rename($target, $forceJpgPath);
                                }
                                $msg .= ($msg ? "<br>" : "") . "Profile photo uploaded.";
                            }
                        } else {
                            $err .= ($err ? "<br>" : "") . "Failed to move uploaded file.";
                        }
                    }
                } else {
                    $err .= ($err ? "<br>" : "") . "Upload error code: " . $f['error'];
                }
            }

        } elseif (isset($_POST['step']) && $_POST['step'] === '2') {
            // Step 2 - final register action. We'll capture selected payment_method and dispatch to existing generateInvoice
            // Ensure required fields present (package selection etc).
            $package_id = intval($_POST['package_id'] ?? 0);
            $package_name = mysqli_real_escape_string($con, $_POST['package_name'] ?? '');
            $qty_set = intval($_POST['qty_set'] ?? 1);
            $shipping_method = mysqli_real_escape_string($con, $_POST['shipping_method'] ?? '');
            $payment_method = mysqli_real_escape_string($con, $_POST['payment_method'] ?? '');

            // Save shipping details to session or DB as needed. Here we just set message and call invoice generator.
            // Validate payment method
            if (!in_array($payment_method, ['fpx', 'transfer', 'cash'])) {
                $err = "Please select a payment method.";
            } else {
                // set a small hidden hack: call generateInvoice like earlier
                if (function_exists('generateInvoice')) {
                    // generateInvoice will probably exit or redirect; call it
                    generateInvoice($payment_method);
                    // If generateInvoice returns, set msg
                    $msg = "Invoice generated with payment method: " . strtoupper($payment_method);
                } else {
                    $err = "Payment processor unavailable.";
                }
            }
        }
    } // end POST handling

    // Prepare discounts & shipping arrays (same as original)
    $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;
    }

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

    // For package list
    $packages = [];
    $sql = "SELECT * FROM packages ORDER BY price ASC";
    $result = mysqli_query($con, $sql);
    while ($p = mysqli_fetch_assoc($result)) {
        $packages[] = $p;
    }

    // For available pins / credit example (if you need to show availability like old basic code)
    $availablePins = [];
    if ($aidi) {
        $sql_pin = "SELECT no FROM bestpin WHERE userid = ? AND status = 0 ORDER BY datesold ASC";
        $stmt_pin = mysqli_prepare($con, $sql_pin);
        mysqli_stmt_bind_param($stmt_pin, "i", $aidi);
        mysqli_stmt_execute($stmt_pin);
        $res_pin = mysqli_stmt_get_result($stmt_pin);
        while ($rpp = mysqli_fetch_assoc($res_pin)) {
            $availablePins[] = $rpp['no'];
        }
        mysqli_stmt_close($stmt_pin);
    }
    $totalPin = count($availablePins);
    $totalCredit = $totalPin * $pv;

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

    <?php if ($msg): ?>
        <div class="alert alert-success"><?= $msg ?></div>
    <?php endif; ?>
    <?php if ($err): ?>
        <div class="alert alert-danger"><?= $err ?></div>
    <?php endif; ?>

    <!-- Wizard header / progress -->
    <div class="panel panel-default">
        <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>
                                <div class="form-group">
                                    <label>Password (auto-generated on first save)</label>
                                    <input type="text" id="generated_password" class="form-control" readonly value="">
                                    <small class="text-muted">System will auto generate.</small>
                                </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="<?= htmlspecialchars($userDetail['nama']) ?>">
                                </div>

                                <div class="form-group">
                                    <label>Address</label>
                                    <input type="text" name="alamat" id="alamat" class="form-control" required value="<?= htmlspecialchars($userDetail['alamat']) ?>">
                                </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="<?= htmlspecialchars($userDetail['poskod']) ?>">
                                    </div>
                                    <div class="col-md-4 form-group">
                                        <label>City</label>
                                        <input type="text" name="bandar" id="bandar" class="form-control" required value="<?= htmlspecialchars($userDetail['bandar']) ?>">
                                    </div>
                                    <div class="col-md-4 form-group">
                                        <label>State</label>
                                        <input type="text" name="negeri" id="negeri" class="form-control" required value="<?= htmlspecialchars($userDetail['negeri']) ?>">
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label>Phone</label>
                                    <input type="text" name="telefon" id="telefon" class="form-control" required value="<?= htmlspecialchars($userDetail['telefon']) ?>">
                                </div>

                                <div class="form-group">
                                    <label>Email</label>
                                    <input type="email" name="email" id="email" class="form-control" required value="<?= htmlspecialchars($userDetail['email']) ?>">
                                </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</label>
                                    <input type="text" name="bank" id="bank" class="form-control" value="<?= htmlspecialchars($userDetail['bank']) ?>">
                                </div>
                                <div class="form-group">
                                    <label>Nama Akaun (naakaun)</label>
                                    <input type="text" name="naakaun" id="naakaun" class="form-control" value="<?= htmlspecialchars($userDetail['naakaun']) ?>">
                                </div>
                                <div class="form-group">
                                    <label>No Akaun (noakaun)</label>
                                    <input type="text" name="noakaun" id="noakaun" class="form-control" value="<?= htmlspecialchars($userDetail['noakaun']) ?>">
                                </div>

                                <div class="form-group">
                                    <label>Beneficiary Name (bnama)</label>
                                    <input type="text" name="bnama" id="bnama" class="form-control" value="<?= htmlspecialchars($userDetail['bnama']) ?>">
                                </div>
                                <div class="form-group">
                                    <label>Beneficiary KP (bkp)</label>
                                    <input type="text" name="bkp" id="bkp" class="form-control" value="<?= htmlspecialchars($userDetail['bkp']) ?>">
                                </div>
                                <div class="form-group">
                                    <label>Relation to Beneficiary (brelation)</label>
                                    <input type="text" name="brelation" id="brelation" class="form-control" value="<?= htmlspecialchars($userDetail['brelation']) ?>">
                                </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>
                        <button type="submit" id="saveProfileBtn" class="btn btn-success">Save Profile</button>
                    </div>
                </div>
                <!-- ---------- STEP 2: PACKAGE / PAYMENT / SHIPPING ----------- -->

                <div id="step2_fieldset" style="border:0;">
                    <!-- Keep your existing package/payment/shipping panels here (unchanged) -->
                    <div class="row"  >
                        <!-- Package List -->
                        <div style="padding-top:20px; width:100%;">
                            <?php foreach ($packages as $p): 
                                $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);">
                                        <input type="radio"
                                               name="nilai_value"
                                               value="<?= htmlspecialchars($p['price']) ?>"
                                               data-qtyset="<?= (int)$p['qty_set'] ?>"
                                               data-name="<?= htmlspecialchars($p['name']) ?>"
                                               data-id="<?= (int)$p['id'] ?>"
                                               onclick="calculate();"
                                               style="margin-bottom:10px;"
                                               required />
                                        <div>
                                            <img src="assets2/ico/tls2u.png" height="120" alt="TLS2U.COM" style="margin:8px 0;">
                                        </div>
                                        <div style="font-weight:bold; font-size:12px; padding-bottom:8px;">( <?= (int)$p['qty_set'] ?> PAX / set | <?= $pinNeeded ?> PIN )</div>
                                        <div style="border-radius: 0 0 5px 5px; padding:10px; display:flex; justify-content:space-between; align-items:center; background:white; color:#000;">
                                            <div style="text-align:left;">
                                                <div style="font-weight:bold; font-size:14px;"><?= htmlspecialchars($p['name']) ?></div>
                                            </div>
                                            <div style="font-weight:bold; font-size:18px; color:red;">
                                                <span style="font-size:12px;">RM</span> <?= number_format($p['price'], 2) ?>
                                            </div>
                                        </div>
                                    </label>
                                </div>
                            <?php endforeach; ?>
                        </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" required /> FPX</label>
                              <label><input type="radio" name="payment_method" value="transfer" /> Bank Transfer</label>
                              <label><input type="radio" name="payment_method" value="cash" /> Cash</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>
                            </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="<?= htmlspecialchars($userDetail['nama']) ?>" 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="<?= htmlspecialchars($userDetail['alamat']) ?>" 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="<?= htmlspecialchars($userDetail['poskod']) ?>" 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="<?= htmlspecialchars($userDetail['bandar']) ?>" 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="<?= htmlspecialchars($userDetail['negeri']) ?>" 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="<?= htmlspecialchars($userDetail['telefon']) ?>" 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="<?= htmlspecialchars($userDetail['email']) ?>" readonly required />
                              </div>
                            </div>
                          </fieldset>
                        </div>

                        <!-- Terms & Totals (right column) -->
                        <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>
                              <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>
                              </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>

                        <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;">Totals</legend>
                            <div style="display:flex; gap:10px; margin-bottom:10px;">
                                <input type="number" class="form-control" style="width:150px;" name="qty_set" id="bil" placeholder="Qty (Set)" oninput="calculate()" min="1" value="1" required />
                                <span class="small">Qty (Set)</span>
                            </div>
                            <div style="display:flex; gap:10px; margin-bottom:10px;">
                                <input type="text" class="form-control" style="width:150px;" id="total_qty1" readonly />
                                <input type="hidden" name="qty_total" id="total_qty" />
                                <span class="small">Total Unit</span>
                            </div>
                            <div style="display:flex; gap:10px; margin-bottom:10px;">
                                <input type="number" class="form-control" style="width:150px;" id="discount1" readonly />
                                <input type="hidden" name="discount" id="discount" />
                                <span class="small">Discount (RM)</span>
                            </div>
                            <div style="display:flex; gap:10px; margin-bottom:10px;">
                                <input type="number" class="form-control" style="width:150px;" id="shipping1" readonly />
                                <input type="hidden" name="shipping_fee" id="shipping" />
                                <span class="small">Shipping (RM)</span>
                            </div>
                            <div style="display:flex; gap:10px; margin-bottom:10px;">
                                <input type="number" class="form-control" style="width:150px;" id="tax1" readonly />
                                <input type="hidden" name="tax" id="tax" />
                                <span class="small">Tax (RM)</span>
                            </div>
                            <div style="display:flex; gap:10px; margin-bottom:10px;">
                                <input type="number" class="form-control" style="width:150px;" id="jumlah1" readonly />
                                <input type="hidden" name="grand_total" id="jumlah" />
                                <span class="small">Total (RM)</span>
                            </div>
                          </fieldset>
                        </div>

                    </div> <!-- end row -->

                    <div style="display:flex; justify-content:space-between; gap:10px; margin-top:15px;">
                        <button type="button" id="backToStep1" class="btn btn-default">&laquo; Back</button>

                        <!-- Register triggers server-side step=2 -->
                        <div style="display:flex; gap:10px;">
                            <button type="submit" id="registerBtn" class="btn btn-success">Register & Pay</button>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- JS: wizard + calculation + payment toggle (keeps your original script) -->
<script>
    const discountTable = <?= json_encode($discounts) ?>;
    const shippingTable = <?= json_encode($shippingCosts) ?>;
    const TAX_RATE = <?= (float)$tax ?> / 100;

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

    // Optional: make Save Profile button set step=1 before submit
    const saveProfileBtn = document.getElementById('saveProfileBtn');
    saveProfileBtn.addEventListener('click', () => {
        formStepInput.value = '1';
    });

    const registerBtn = document.getElementById('registerBtn');
    registerBtn.addEventListener('click', () => {
        formStepInput.value = '2';
    });

    // Toggle address editing
    function toggleAddress() {
      const checked = document.getElementById("useCurrentAddress").checked;
      const fields = ["ship_name","ship_address","ship_city","ship_postcode","ship_state","ship_phone","ship_email"];
      fields.forEach(id => {
          const el = document.getElementById(id);
          if (el) el.readOnly = checked;
      });
    }
    
    function updateShippingDetails() {
        const fields = ['nama', 'alamat', 'poskod', 'bandar', 'negeri', 'telefon', 'email'];
        const shipFields = ['ship_name', 'ship_address', 'ship_postcode', 'ship_city', 'ship_state', 'ship_phone', 'ship_email'];
    
        fields.forEach((field, index) => {
            const personalVal = document.getElementById(field).value.trim();
            document.getElementById(shipFields[index]).value = personalVal || '';
        });
    }
    
    // Trigger update on input change
    ['nama','alamat','poskod','bandar','negeri','telefon','email'].forEach(id => {
        document.getElementById(id).addEventListener('input', updateShippingDetails);
    });

    // Calculate totals (kept from original, with small DOM-safe guards)
    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;
            }
        }

        const subtotal = sets * price;
        const totalQty = sets * qtySet;

        // update both readonly & hidden field
        const totalQty1 = document.getElementById("total_qty1");
        const totalQtyHidden = document.getElementById("total_qty");
        if (totalQty1) totalQty1.value = totalQty;
        if (totalQtyHidden) totalQtyHidden.value = totalQty;

        // Discount
        let discount = 0;
        discountTable.forEach(d => {
            if (totalQty >= d.qty) discount = parseFloat(d.value) || 0;
        });
        const discount1 = document.getElementById("discount1");
        const discountHidden = document.getElementById("discount");
        if (discount1) discount1.value = discount.toFixed(2);
        if (discountHidden) discountHidden.value = discount.toFixed(2);

        // Tax
        const taxableAmount = subtotal - discount;
        const tax = TAX_RATE * taxableAmount;
        const tax1 = document.getElementById("tax1");
        const taxHidden = document.getElementById("tax");
        if (tax1) tax1.value = tax.toFixed(2);
        if (taxHidden) taxHidden.value = tax.toFixed(2);

        // Shipping
        let shippingFee = 0;
        const shippingSelected = document.querySelector('input[name="shipping_method"]:checked');
        const stateEl = document.getElementById("ship_state");
        const state = stateEl ? stateEl.value : null;

        if (shippingSelected && shippingSelected.value === 'courier' && state && shippingTable[state]) {
            shippingTable[state].forEach(s => {
                if (totalQty >= s.qty) shippingFee = parseFloat(s.value) || 0;
            });
        }
        const shipping1 = document.getElementById("shipping1");
        const shippingHidden = document.getElementById("shipping");
        if (shipping1) shipping1.value = shippingFee.toFixed(2);
        if (shippingHidden) shippingHidden.value = shippingFee.toFixed(2);

        // Final total
        const grandTotal = taxableAmount + tax + shippingFee;
        const jumlah1 = document.getElementById("jumlah1");
        const jumlahHidden = document.getElementById("jumlah");
        if (jumlah1) jumlah1.value = grandTotal.toFixed(2);
        if (jumlahHidden) jumlahHidden.value = grandTotal.toFixed(2);
    }

    // Bind events safely (guard elements exist)
    const bilEl = document.getElementById("bil");
    if (bilEl) bilEl.addEventListener('input', calculate);
    document.querySelectorAll('input[name="nilai_value"]').forEach(radio => {
        radio.addEventListener('change', function() {
            calculate();
            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));
    const shipStateEl = document.getElementById("ship_state");
    if (shipStateEl) shipStateEl.addEventListener('change', calculate);

    // Payment buttons visibility (keeps original behavior but now the Register button triggers server side)
    function togglePaymentButtons() {
        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") {
            const fpxBtn = document.getElementById('fpx_btn');
            if (fpxBtn) fpxBtn.style.display = 'block';
        } else if (selected.value === "transfer") {
            const t = document.getElementById('transfer_btn');
            if (t) t.style.display = 'block';
        } else if (selected.value === "cash") {
            const c = document.getElementById('cash_btn');
            if (c) c.style.display = 'block';
        }
    }
    document.querySelectorAll('input[name="payment_method"]').forEach(r => r.addEventListener('change', togglePaymentButtons));
    togglePaymentButtons();

    // On form submit: ensure form_step is 2 (so server knows to process step 2) and do basic checks
    document.getElementById('regForm').addEventListener('submit', function (e) {
        // If we're submitting from step1 Save Profile button, form_step will be '1' (that's fine)
        // If user clicked Register (while step2 visible), ensure step=2
        const stepVal = formStepInput.value;
        if (stepVal !== '2') {
            // Determine if we are in step2 visually
            if (step2Fieldset.style.display !== 'none') {
                formStepInput.value = '2';
            } else {
                formStepInput.value = '1';
            }
        }
        // If step=2, ensure payment method selected
        if (formStepInput.value === '2') {
            const pm = document.querySelector('input[name="payment_method"]:checked');
            if (!pm) {
                alert('Please select a payment method.');
                e.preventDefault();
                return false;
            }
            // we proceed — server will call generateInvoice(payment_method)
        }
    });

    // 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');
    const generatedPasswordEl = document.getElementById('generated_password');

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

    // If server generated a password on last save, display it in generated_password box
    <?php if (strpos($msg, 'Generated password:') !== false): 
        // Extract password from $msg to show in field (safe: was just generated)
        if (preg_match('/Generated password:<\/strong>\s*([^<\s]+)/', $msg, $mp)) {
            $displayPass = htmlspecialchars($mp[1]);
        } else {
            $displayPass = '';
        }
    ?>
    generatedPasswordEl.value = "<?= $displayPass ?>";
    <?php endif; ?>

    // Attach confirm for existing payment btns if any (keeps behaviour)
    document.addEventListener("DOMContentLoaded", () => {
        document.querySelectorAll(".payment-btn").forEach(btn => {
            btn.addEventListener("click", function(e) {
                if (!confirm("Are you sure you want to confirm this order ?")) {
                    e.preventDefault();
                    return false;
                }
            });
        });
    });

</script>

<?php
    include "_footer2.php";
} // end session else
?>
