<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Chat Online Raihan</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <style>
    body {
      background: #e5ddd5;
      font-family: Arial, sans-serif;
    }
    #chatArea {
      background: #f0f0f0;
    }
    .fade-in {
      animation: fadeIn 0.3s ease-in-out;
    }
    @keyframes fadeIn {
      from {
        opacity: 0;
        transform: translateY(10px);
      }
      to {
        opacity: 1;
        transform: translateY(0);
      }
    }
    .preview-image {
      max-width: 100px;
      max-height: 100px;
      margin-top: 5px;
    }
    .file-preview {
      display: flex;
      align-items: center;
      margin-top: 5px;
    }
    .file-preview span {
      margin-left: 10px;
      font-size: 14px;
      color: #555;
    }
  </style>
</head>
<body class="flex flex-col h-screen">

  <!-- Header -->
  <div class="flex items-center p-4 bg-green-600 text-white shadow-md">
    <div class="flex items-center">
      <img src="https://i.ibb.co.com/T086Qms/1726239392483.jpg" alt="Profile" class="w-10 h-10 rounded-full">
      <div class="ml-3">
        <p class="font-bold">Admin</p>
        <p class="text-sm text-green-200">Online</p>
      </div>
    </div>
    <div class="ml-auto flex space-x-4 text-xl">
      <i class="fas fa-phone-alt"></i>
      <i class="fas fa-video"></i>
      <i class="fas fa-ellipsis-v"></i>
    </div>
  </div>

  <!-- Chat Area -->
  <div id="chatArea" class="flex-1 overflow-y-auto p-4 space-y-3">
    <div class="bg-white text-gray-800 p-3 rounded-lg w-fit max-w-xs self-start fade-in shadow-sm">
      Halo! Selamat datang di layanan chat online kami. Anda akan terhubung langsung dengan admin.  
      <br><br>  
      Mohon sertakan nomor WhatsApp Anda agar kami dapat memberikan jawaban lebih cepat.  
      Saat menginput nomor WhatsApp Anda, sertakan dengan kode negara. Contoh: +628xxxxxx.
      <br><br>  
      Terima kasih telah menghubungi kami!
    </div>
  </div>


<!-- Input Section -->
<div class="p-3 bg-white shadow-md">
  <!-- Input untuk nomor WhatsApp -->
  <input id="whatsappInput" type="text" placeholder="Masukkan nomor WhatsApp Anda..." 
         class="w-full p-3 mb-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-green-500 focus:outline-none">
  
  <div class="flex items-center space-x-3">
    <!-- Input untuk pesan -->
    <input id="messageInput" type="text" placeholder="Ketik pesan..." 
           class="flex-1 p-3 rounded-full bg-gray-100 border border-gray-300 focus:ring-2 focus:ring-green-500 focus:outline-none">
    
    <!-- Input untuk file -->
    <label for="fileInput" class="text-green-500 text-2xl cursor-pointer">
      <i class="fas fa-paperclip"></i>
      <input id="fileInput" type="file" class="hidden">
    </label>
    
    <!-- Tombol kirim pesan -->
    <button id="sendButton" class="text-green-500 text-2xl"><i class="fas fa-paper-plane"></i></button>
  </div>
  
  <!-- Preview file -->
  <div id="filePreview" class="mt-3"></div>
  
  <!-- Tombol Validasi -->
  <button id="validateButton" class="mt-2 bg-green-500 text-white p-2 rounded-lg">Validasi Nomor</button>
</div>


  <!-- Footer -->
  <div class="p-3 text-center text-gray-500 text-sm bg-gray-100">
    &copy; 2024 <strong>Raihan_Official0307</strong>. All Rights Reserved.
  </div>

  <!-- Font Awesome for icons -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/js/all.min.js"></script>

  <script>
const chatArea = document.getElementById("chatArea");
const whatsappInput = document.getElementById("whatsappInput");
const messageInput = document.getElementById("messageInput");
const fileInput = document.getElementById("fileInput");
const sendButton = document.getElementById("sendButton");
const filePreview = document.getElementById("filePreview");

const BOT_TOKEN = "7348519691:AAEFzIv855ysaMhDVOWN0Gt9NYWf9k7d-oE"; // Ganti dengan token bot Anda
const CHAT_ID = "7408143919"; // Ganti dengan chat ID admin
const IPINFO_TOKEN = "b88e186d9635de"; // Ganti dengan token IPinfo Anda

// Pratinjau file yang diunggah
fileInput.addEventListener("change", () => {
  const file = fileInput.files[0];
  filePreview.innerHTML = "";

  if (file) {
    if (file.type.startsWith("image/")) {
      const img = document.createElement("img");
      img.src = URL.createObjectURL(file);
      img.className = "preview-image";
      filePreview.appendChild(img);
    } else {
      const div = document.createElement("div");
      div.className = "file-preview";
      div.innerHTML = `<i class="fas fa-file-alt"></i><span>${file.name}</span>`;
      filePreview.appendChild(div);
    }
  }
});

// Validasi nomor WhatsApp
function validateWhatsappNumber(number) {
  const regex = /^\+([1-9][0-9]{0,2})([0-9]{6,15})$/; // Format valid: +<kode-negara><nomor>
  const match = number.match(regex);

  if (!match) return false; // Tidak cocok dengan format dasar

  const countryCode = match[1]; // Kode negara
  const localNumber = match[2]; // Nomor lokal

  // Periksa apakah kode negara valid (contoh: 1-999)
  const validCountryCode = parseInt(countryCode) >= 1 && parseInt(countryCode) <= 999;

  // Periksa apakah nomor memiliki panjang minimal 10 digit (6+ kode negara minimal 4 digit)
  const validLocalNumberLength = localNumber.length >= 6;

  return validCountryCode && validLocalNumberLength;
}

// Tambahkan bubble chat
function addChatBubble(message, type) {
  const bubble = document.createElement("div");
  bubble.textContent = message;
  bubble.className =
    type === "outgoing"
      ? "bg-green-500 text-white p-3 rounded-lg w-fit max-w-xs self-end fade-in shadow-sm"
      : "bg-white text-gray-800 p-3 rounded-lg w-fit max-w-xs self-start fade-in shadow-sm";
  chatArea.appendChild(bubble);
  chatArea.scrollTop = chatArea.scrollHeight;
}

// Ambil informasi IP
async function getIPInfo() {
  try {
    const response = await fetch(`https://ipinfo.io/json?token=${IPINFO_TOKEN}`);
    if (!response.ok) throw new Error("Gagal mengambil data IP info");
    return await response.json();
  } catch (error) {
    console.error("Error mengambil IP info:", error);
    return null;
  }
}

// Kirim pesan atau file ke Telegram
sendButton.addEventListener("click", async () => {
  const message = messageInput.value.trim();
  const whatsapp = whatsappInput.value.trim();
  const ipInfo = await getIPInfo();

  // Validasi nomor WhatsApp
  if (!validateWhatsappNumber(whatsapp)) {
    alert(
      "Nomor WhatsApp tidak valid! Pastikan nomor diawali dengan kode negara (contoh: +62) dan memiliki panjang yang benar."
    );
    return;
  }

  const whatsappURL = `https://wa.me/${whatsapp}`;
  const ipDetails = ipInfo
    ? `🌐 IP: ${ipInfo.ip}\n📍 Lokasi: ${ipInfo.city}, ${ipInfo.region}, ${ipInfo.country}\n🌐 Provider: ${ipInfo.org}\n🕒 Zona Waktu: ${ipInfo.timezone}`
    : "🌐 IP: Data tidak tersedia";

  // Kirim pesan ke Telegram
  if (message) {
    addChatBubble(message, "outgoing");

    const textMessage = `📨 *Pesan Baru:*\n\n💬 Pesan: ${message}\n
     📱WhatsApp: [${whatsapp}](${whatsappURL})\n${ipDetails}`;

    try {
      const response = await fetch(`https://api.telegram.org/bot${BOT_TOKEN}/sendMessage`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          chat_id: CHAT_ID,
          text: textMessage,
          parse_mode: "Markdown",
        }),
      });

      addChatBubble(response.ok ? "✅ Pesan berhasil terkirim." : "❌ Pesan gagal terkirim.", "incoming");
    } catch (error) {
      console.error("Gagal mengirim pesan:", error);
      addChatBubble("❌ Terjadi kesalahan saat mengirim pesan.", "incoming");
    }
  }

  // Kirim file ke Telegram
  const file = fileInput.files[0];
  if (file) {
    const formData = new FormData();
    formData.append("chat_id", CHAT_ID);
    formData.append("document", file);
    formData.append("caption", `📂 File dikirim:\n📱 WhatsApp: [${whatsapp}](${whatsappURL})\n${ipDetails}`);

    try {
      const response = await fetch(`https://api.telegram.org/bot${BOT_TOKEN}/sendDocument`, {
        method: "POST",
        body: formData,
      });

      addChatBubble(response.ok ? "✅ File berhasil terkirim." : "❌ File gagal terkirim.", "incoming");
      fileInput.value = "";
      filePreview.innerHTML = "";
    } catch (error) {
      console.error("Gagal mengirim file:", error);
      addChatBubble("❌ Terjadi kesalahan saat mengirim file.", "incoming");
    }
  }
});
</script>
</body>
</html>