<!DOCTYPE html>

<html lang="th">

<head>

  <meta charset="UTF-8" />

  <meta name="viewport" content="width=device-width, initial-scale=1.0" />

  <title>JC3 Order</title>


  <script src="https://static.line-scdn.net/liff/edge/2/sdk.js"></script>


  <style>

    body {

      margin: 0;

      font-family: Arial, sans-serif;

      background: #f7f7f7;

      color: #222;

    }


    header {

      background: white;

      padding: 16px;

      position: sticky;

      top: 0;

      z-index: 10;

      box-shadow: 0 2px 8px rgba(0,0,0,0.08);

    }


    h1 {

      font-size: 20px;

      margin: 0;

    }


    .sub {

      font-size: 13px;

      color: #666;

      margin-top: 4px;

    }


    .container {

      padding: 14px;

      padding-bottom: 110px;

    }


    .profile {

      background: #fff7e6;

      padding: 10px 12px;

      border-radius: 12px;

      margin-bottom: 12px;

      font-size: 14px;

    }


    .product {

      background: white;

      border-radius: 16px;

      padding: 12px;

      margin-bottom: 12px;

      display: flex;

      gap: 12px;

      box-shadow: 0 1px 5px rgba(0,0,0,0.06);

    }


    .product img {

      width: 92px;

      height: 92px;

      border-radius: 12px;

      object-fit: cover;

      background: #eee;

    }


    .product-info {

      flex: 1;

    }


    .product-name {

      font-weight: bold;

      font-size: 15px;

      margin-bottom: 6px;

    }


    .product-price {

      color: #c0392b;

      font-weight: bold;

      margin-bottom: 8px;

    }


    .stock {

      font-size: 12px;

      color: #777;

      margin-bottom: 8px;

    }


    button {

      border: none;

      border-radius: 10px;

      padding: 10px 12px;

      font-weight: bold;

      cursor: pointer;

    }


    .add-btn {

      background: #111;

      color: white;

      width: 100%;

    }


    .cart-bar {

      position: fixed;

      left: 12px;

      right: 12px;

      bottom: 16px;

      background: #111;

      color: white;

      border-radius: 18px;

      padding: 14px;

      display: flex;

      justify-content: space-between;

      align-items: center;

      z-index: 20;

      box-shadow: 0 4px 14px rgba(0,0,0,0.25);

    }


    .cart-bar button {

      background: white;

      color: #111;

    }


    .panel {

      position: fixed;

      left: 0;

      right: 0;

      bottom: 0;

      max-height: 86vh;

      overflow-y: auto;

      background: white;

      border-radius: 22px 22px 0 0;

      padding: 16px;

      z-index: 30;

      box-shadow: 0 -4px 18px rgba(0,0,0,0.2);

    }


    .hidden {

      display: none;

    }


    .cart-item {

      border-bottom: 1px solid #eee;

      padding: 10px 0;

      display: flex;

      justify-content: space-between;

      gap: 8px;

    }


    .qty {

      display: flex;

      align-items: center;

      gap: 8px;

    }


    .qty button {

      background: #eee;

      color: #111;

      padding: 6px 10px;

    }


    input, textarea {

      width: 100%;

      box-sizing: border-box;

      border: 1px solid #ddd;

      border-radius: 12px;

      padding: 12px;

      margin: 6px 0 10px;

      font-size: 15px;

    }


    textarea {

      min-height: 80px;

    }


    .submit-btn {

      background: #06c755;

      color: white;

      width: 100%;

      font-size: 16px;

      padding: 14px;

      margin-top: 10px;

    }


    .close-btn {

      background: #eee;

      color: #111;

      width: 100%;

      margin-top: 8px;

    }


    .summary {

      background: #f5f5f5;

      border-radius: 12px;

      padding: 12px;

      margin-top: 10px;

      font-size: 14px;

    }

  </style>

</head>


<body>

  <header>

    <h1>JC3 Japan Order</h1>

    <div class="sub">เลือกสินค้า กรอกที่อยู่ แล้วส่งออเดอร์ใน LINE</div>

  </header>


  <div class="container">

    <div id="profileBox" class="profile">กำลังเชื่อมต่อ LINE...</div>

    <div id="productList"></div>

  </div>


  <div class="cart-bar">

    <div id="cartSummary">ตะกร้า 0 ชิ้น | 0฿</div>

    <button onclick="openCart()">ดูตะกร้า</button>

  </div>


  <div id="cartPanel" class="panel hidden">

    <h2>ตะกร้าสินค้า</h2>

    <div id="cartItems"></div>


    <div class="summary" id="priceSummary"></div>


    <h3>ข้อมูลจัดส่ง</h3>


    <label>ชื่อผู้รับ</label>

    <input id="customerName" placeholder="เช่น คุณจิรวัฒน์" />


    <label>เบอร์โทร</label>

    <input id="phone" placeholder="เช่น 08x-xxx-xxxx" />


    <label>ที่อยู่จัดส่ง</label>

    <textarea id="address" placeholder="บ้านเลขที่ ถนน ตำบล อำเภอ จังหวัด รหัสไปรษณีย์"></textarea>


    <label>หมายเหตุ</label>

    <textarea id="note" placeholder="เช่น ฝากไว้หน้าบ้าน / ไม่รับถุง / ต้องการส่งด่วน"></textarea>


    <button class="submit-btn" onclick="submitOrder()">ยืนยันออเดอร์</button>

    <button class="close-btn" onclick="closeCart()">ปิด</button>

  </div>


  <script>


    const LIFF_ID = "2010388804-NhLEgLHE";


    const APPS_SCRIPT_URL = "https://script.google.com/macros/s/AKfycbzOlWMIvMGoDWd3BWzBxePyOyS6zn6DbXnP8kshWGPFyBFnnW2WmjEFWRXudYIVAQ5c/exec";


    const SHIPPING_FEE = 50;


    const products = [

      {

        id: "P001",

        name: "แผ่นดักไรฝุ่นญี่ปุ่น",

        price: 390,

        stock: 20,

        image: "https://placehold.co/300x300?text=Product+1"

      },

      {

        id: "P002",

        name: "MUJI Japan Item",

        price: 290,

        stock: 15,

        image: "https://placehold.co/300x300?text=Product+2"

      },

      {

        id: "P003",

        name: "ชาเขียวญี่ปุ่น",

        price: 450,

        stock: 10,

        image: "https://placehold.co/300x300?text=Product+3"

      }

    ];


    let cart = JSON.parse(localStorage.getItem("cart") || "{}");

    let lineProfile = {

      userId: "",

      displayName: ""

    };


    async function initLiff() {

      renderProducts();

      updateCartSummary();


      try {

        await liff.init({ liffId: LIFF_ID });


        if (!liff.isLoggedIn() && !liff.isInClient()) {

          liff.login();

          return;

        }


        const profile = await liff.getProfile();

        lineProfile.userId = profile.userId;

        lineProfile.displayName = profile.displayName;


        document.getElementById("profileBox").innerText =

          "สวัสดีคุณ " + profile.displayName + " 👋";


      } catch (error) {

        console.log(error);

        document.getElementById("profileBox").innerText =

          "เปิดใน LINE เพื่อใช้งานได้สมบูรณ์";

      }

    }


    function renderProducts() {

      const productList = document.getElementById("productList");

      productList.innerHTML = "";


      products.forEach(product => {

        const div = document.createElement("div");

        div.className = "product";


        div.innerHTML = `

          <img src="${product.image}" alt="${product.name}" />

          <div class="product-info">

            <div class="product-name">${product.name}</div>

            <div class="product-price">${product.price.toLocaleString()}฿</div>

            <div class="stock">คงเหลือประมาณ ${product.stock} ชิ้น</div>

            <button class="add-btn" onclick="addToCart('${product.id}')">เพิ่มลงตะกร้า</button>

          </div>

        `;


        productList.appendChild(div);

      });

    }


    function addToCart(productId) {

      cart[productId] = (cart[productId] || 0) + 1;

      saveCart();

    }


    function changeQty(productId, amount) {

      cart[productId] = (cart[productId] || 0) + amount;


      if (cart[productId] <= 0) {

        delete cart[productId];

      }


      saveCart();

      renderCart();

    }


    function saveCart() {

      localStorage.setItem("cart", JSON.stringify(cart));

      updateCartSummary();

    }


    function getCartItems() {

      return Object.keys(cart).map(productId => {

        const product = products.find(p => p.id === productId);

        return {

          id: product.id,

          name: product.name,

          price: product.price,

          qty: cart[productId],

          total: product.price * cart[productId]

        };

      });

    }


    function getSubtotal() {

      return getCartItems().reduce((sum, item) => sum + item.total, 0);

    }


    function updateCartSummary() {

      const items = getCartItems();

      const totalQty = items.reduce((sum, item) => sum + item.qty, 0);

      const subtotal = getSubtotal();


      document.getElementById("cartSummary").innerText =

        `ตะกร้า ${totalQty} ชิ้น | ${subtotal.toLocaleString()}฿`;

    }


    function openCart() {

      document.getElementById("cartPanel").classList.remove("hidden");

      renderCart();

    }


    function closeCart() {

      document.getElementById("cartPanel").classList.add("hidden");

    }


    function renderCart() {

      const cartItems = document.getElementById("cartItems");

      const items = getCartItems();


      if (items.length === 0) {

        cartItems.innerHTML = "<p>ยังไม่มีสินค้าในตะกร้า</p>";

      } else {

        cartItems.innerHTML = items.map(item => `

          <div class="cart-item">

            <div>

              <strong>${item.name}</strong><br>

              ${item.price.toLocaleString()}฿ × ${item.qty}

            </div>

            <div class="qty">

              <button onclick="changeQty('${item.id}', -1)">-</button>

              <span>${item.qty}</span>

              <button onclick="changeQty('${item.id}', 1)">+</button>

            </div>

          </div>

        `).join("");

      }


      const subtotal = getSubtotal();

      const shipping = items.length > 0 ? SHIPPING_FEE : 0;

      const total = subtotal + shipping;


      document.getElementById("priceSummary").innerHTML = `

        ค่าสินค้า: ${subtotal.toLocaleString()}฿<br>

        ค่าส่ง: ${shipping.toLocaleString()}฿<br>

        <strong>รวมทั้งหมด: ${total.toLocaleString()}฿</strong>

      `;

    }


    async function submitOrder() {

      const items = getCartItems();


      if (items.length === 0) {

        alert("กรุณาเลือกสินค้าก่อน");

        return;

      }


      const customerName = document.getElementById("customerName").value.trim();

      const phone = document.getElementById("phone").value.trim();

      const address = document.getElementById("address").value.trim();

      const note = document.getElementById("note").value.trim();


      if (!customerName || !phone || !address) {

        alert("กรุณากรอกชื่อ เบอร์โทร และที่อยู่");

        return;

      }


      const subtotal = getSubtotal();

      const shipping = SHIPPING_FEE;

      const total = subtotal + shipping;

      const orderId = "JC" + Date.now().toString().slice(-8);


      const order = {

        orderId,

        lineUserId: lineProfile.userId,

        lineName: lineProfile.displayName,

        customerName,

        phone,

        address,

        items,

        subtotal,

        shipping,

        total,

        note

      };


      const lineText =

`📦 สรุปออเดอร์ ${orderId}


สินค้า:

${items.map(item => `- ${item.name} x ${item.qty} = ${item.total.toLocaleString()}฿`).join("\n")}


ค่าสินค้า: ${subtotal.toLocaleString()}฿

ค่าส่ง: ${shipping.toLocaleString()}฿

รวมทั้งหมด: ${total.toLocaleString()}฿


ชื่อผู้รับ: ${customerName}

เบอร์: ${phone}

ที่อยู่: ${address}


หมายเหตุ: ${note || "-"}


สถานะ: รอดำเนินการ`;


      try {

        // mode no-cors ใช้เพื่อส่งข้อมูลเข้า Apps Script แบบง่าย

        await fetch(APPS_SCRIPT_URL, {

          method: "POST",

          mode: "no-cors",

          headers: {

            "Content-Type": "text/plain;charset=utf-8"

          },

          body: JSON.stringify(order)

        });


        // ส่งข้อความกลับเข้าแชท LINE

        if (typeof liff !== "undefined" && liff.isInClient()) {

          try {

            await liff.sendMessages([

              {

                type: "text",

                text: lineText

              }

            ]);

          } catch (lineError) {

            console.log("LINE send error:", lineError);

          }

        }


        localStorage.removeItem("cart");

        cart = {};

        updateCartSummary();


        alert("ส่งออเดอร์เรียบร้อยแล้ว");

        closeCart();


        if (typeof liff !== "undefined" && liff.isInClient()) {

          liff.closeWindow();

        }


      } catch (error) {

        console.log(error);

        alert("ส่งออเดอร์ไม่สำเร็จ กรุณาลองใหม่");

      }

    }


    initLiff();

  </script>

</body>

</html>