<?php
session_start();
$key = md5(date("Y-m-d").":".$_SERVER['REMOTE_ADDR']);
if (isset($_SESSION['aW1iZXN0cmEuY29tLm15']) <> $key) {
    header("location:".$_SERVER['REQUEST_SCHEME']."://".$_SERVER['SERVER_NAME']); // cara baru !
} else {
    include "_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;
    
    
    $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>Stock Purchase</h2>
                    </div>
                </div>
            <hr />
<?
// Example: detect FPX button click
if (isset($_POST[md5("buynowfpx" . $_SESSION['aidi'])])) {
    generateInvoice("fpx");
} elseif (isset($_POST[md5("online" . $_SESSION['aidi'])])) {
    generateInvoice("onlinebanking");
} elseif (isset($_POST[md5("cash" . $_SESSION['aidi'])])) {
    generateInvoice("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">
            <form role="form" method="post">
              <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" required /> FPX</label>
                      <label><input type="radio" name="payment_method" value="online" /> Online Banking</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 & 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, Online Banking, 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;" 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="jumlah1" readonly />
                    <input type="hidden" class="form-control" style="width:150px;" name="grand_total" id="jumlah" />
                    <span class="small">Total (RM)</span>
                  </div>
                        <!-- FPX button -->
                        <div id="fpx_btn" class="form-group payment-btn" style="display:none;">
                          <button type="<?= $butang ?>" name="<?= md5("buynowfpx".$_SESSION['aidi']) ?>" class="btn btn-primary w-100">Pay FPX</button>
                        </div>
                        
                        <!-- Online Banking button -->
                        <div id="online_btn" class="form-group payment-btn" style="display:none;">
                          <button type="<?= $butang ?>" name="<?= md5("online".$_SESSION['aidi']) ?>" class="btn btn-primary w-100">Pay Online Banking</button>
                        </div>
                        
                        <!-- Cash button -->
                        <div id="cash_btn" class="form-group payment-btn" style="display:none;">
                          <button type="<?= $butang ?>" name="<?= md5("cash".$_SESSION['aidi']) ?>" class="btn btn-primary w-100">Pay Cash</button>
                        </div>
                </div>
        
              </div>
            </form>
          </div>
        </div>

        <script>
        const discountTable = <?= json_encode($discounts) ?>;
        const shippingTable = <?= json_encode($shippingCosts) ?>;
        
        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 => document.getElementById(id).readOnly = checked);
        }
        
        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;
            });
            document.getElementById("discount1").value = discount.toFixed(2);
            document.getElementById("discount").value  = discount.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 = subtotal - discount + 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);
        }
            
        // ✅ 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 === "online") {
                document.getElementById('online_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);
            });
        });
        
       
    
        </script>



   

<? } ?>

    </div>

             <!-- /. PAGE INNER  -->

            </div>

<?

    include "_footer2.php";

}

?>

