<?php
include "/www/wwwroot/bilspro/config/connect.php";
include "/www/wwwroot/bilspro/payment/paydisini/api_control.php";

if (!isset($_GET['id']) || empty($_GET['id'])) {
    die("ID tidak valid");
}

$board_id = $_GET['id'];

$stmt = $pdo->prepare("SELECT * FROM setting_mikrotik WHERE board_id = :board_id");
$stmt->bindParam(':board_id', $board_id, PDO::PARAM_STR);
$stmt->execute();
$servers = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Daftar Voucher</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="voucher-container" id="voucher-container">
    <!-- Konten akan diisi melalui JavaScript berdasarkan localStorage -->
  </div>

<script>
function tampilkanKonfirmasi(nama, harga, ids, idm, idv) {
  const container = document.getElementById('voucher-container');
  container.innerHTML = `
    <div class="confirm-wrapper">
      <div class="confirm-box">
        <h3 class="confirm-title">Konfirmasi Pembelian</h3>
        <p class="confirm-nama">${nama}</p>
        <p class="confirm-harga">Rp ${harga.toLocaleString()}</p>
        <div class="confirm">
          <input type="text" id="waInput" placeholder="0812xxxxxxx" />
          <p class="confirm-info">Masukkan nomor WhatsApp untuk menerima kode voucher</p>
        </div>
        <div class="button-group">
          <button class="btn-submit" onclick="kirimPembayaran(${ids}, ${idm}, ${idv})">Bayar</button>
          <button class="btn-cancel" onclick="resetPembayaran()">Kembali</button>
        </div>
      </div>
    </div>
  `;
  localStorage.setItem("harga", harga);
  localStorage.setItem("nama", nama);
  kirimHeight();
}

function resetPembayaran() {
  localStorage.clear();
  window.location.reload();
}

function countDown(expiredTimeString) {
  const targetDate = new Date(expiredTimeString.replace(" ", "T"));
  const countdownElement = document.getElementById("countdown");
  if (!countdownElement) return;
  const countdownFunction = setInterval(() => {
    const now = new Date().getTime();
    const distance = targetDate.getTime() - now;
    if (distance <= 0) {
      clearInterval(countdownFunction);
      countdownElement.textContent = "Waktu habis, memeriksa status pembayaran...";
      cekstatusPembayaran();
      return;
    }
    const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((distance % (1000 * 60)) / 1000);
    let countdownText = "";
    if (hours > 0) countdownText += hours + " jam ";
    if (minutes > 0 || hours > 0) countdownText += minutes + " menit ";
    countdownText += seconds + " detik";
    countdownElement.textContent = countdownText;
  }, 1000);
}

function kirimPembayaran(ids, idm, idv) {
  const wa = document.getElementById('waInput').value.trim();
  if (!wa.match(/^[0-9]{10,15}$/)) {
    alert("Nomor WhatsApp tidak valid");
    return;
  }
  const box = document.querySelector(".confirm-box");
  box.innerHTML = `
    <p style="margin-bottom:10px;">Memproses pembayaran...</p>
    <p>Mohon tunggu sebentar.</p>
  `;
  fetch("payment.php", {
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded"
    },
    body: `ids=${encodeURIComponent(ids)}&idm=${encodeURIComponent(idm)}&idv=${encodeURIComponent(idv)}&wa=${encodeURIComponent(wa)}`
  })
  .then(response => response.text())
  .then(text => {
    try {
      const data = JSON.parse(text);
      if (data.success) {
        localStorage.setItem("status", "Pending");
        localStorage.setItem("voucher", data.voucher);
        localStorage.setItem("exppay", data.exppay);
        localStorage.setItem("order_id", data.order_id);
        localStorage.setItem("qr", data.qr);
        tampilkanQR(data.qr, data.exppay);
      } else {
        box.innerHTML = `<p style="color:red;">${data.message}</p>`;
      }
    } catch (e) {
      box.innerHTML = `<p style="color:red;">Respon tidak valid:<br>${text}</p>`;
    }
  })
  .catch(error => {
    box.innerHTML = `<p style="color:red;">Terjadi kesalahan: ${error}</p>`;
  });
}

function cekstatusPembayaran() {
  const order_id = localStorage.getItem("order_id");
  if (!order_id) {
    console.log("ID pembayaran tidak ditemukan.");
    return;
  }

  fetch("cek_status.php", {
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded"
    },
    body: `order_id=${encodeURIComponent(order_id)}`
  })
  .then(response => response.text()) // Tangkap sebagai teks dulu untuk debug
  .then(text => {
    try {
      const data = JSON.parse(text);
      console.log("Response dari cek_status.php:", data);

      if (!data.success) {
        console.log("Cek status gagal:", data.message || "Tidak diketahui");
        if (data.raw_response) console.log("Raw Response:", data.raw_response);
        return;
      }

      const status = data.status;

      if (status === "Lunas") {
        localStorage.setItem("status", "Lunas");
        tampilkanSukses(localStorage.getItem("nama"), "Rp " + localStorage.getItem("harga"), localStorage.getItem("voucher"));
      } else if (status === "Pending") {
        alert("Pembayaran masih diproses.");
      } else if (status === "Canceled" || status === "Failed") {
        alert("Pembayaran dibatalkan atau gagal.");
        resetPembayaran();
      } else {
        console.log("Status tidak dikenali:", status);
      }
    } catch (err) {
      console.log("Gagal parse JSON:", err);
      console.log("Respon mentah:", text);
    }
  })
  .catch(err => {
    console.log("Gagal melakukan request cek status:", err);
  });
}

function tampilkanQR(qrUrl, expPay) {
  const container = document.getElementById("voucher-container");
  container.innerHTML = `
    <div class="confirm-wrapper">
      <div class="confirm-box">
        <p style="font-size: 12px;">Silakan melakukan pembayaran dengan QRIS di bawah ini</p>
        <img src="${qrUrl}" alt="QR Code" style="max-width: 180px;">
        <p style="font-size: 14px;" id="countdown"></p>
        <p style="font-size: 12px;">Kode voucher akan dikirim ke WhatsApp setelah pembayaran berhasil.</p>
        <div class="button-group">
          <button class="btn-cancel" onclick="resetPembayaran()">Batal</button>
          <button class="btn-submit" onclick="cekstatusPembayaran()">Cek Status</button>
        </div>
      </div>
    </div>
  `;
  countDown(expPay);
  kirimHeight();
}

function tampilkanSukses(nama, harga, kodeVoucher) {
  const container = document.getElementById("voucher-container");
  container.innerHTML = `
    <div class="confirm-wrapper">
      <div class="confirm-box">
        <div class="confirm-title">Pembayaran ${nama} ${harga}</div>
        <div class="confirm-harga">BERHASIL</div>
        <div class="confirm-info">Kode Voucher</div>
        <h3>${kodeVoucher}</h3>
        <div class="confirm-info">Silakan masukan kode voucher di atas</div>
        <div class="button-group">
          <button class="btn-cancel" onclick="resetPembayaran()">Tutup</button>
        </div>
      </div>
    </div>
  `;
  kirimHeight();
}

function tampilkanListVoucher() {
  const data = <?php
    $output = [];
    if (!empty($servers)) {
        $id_data_server = $servers[0]['id_data_server'];
        $stmt = $pdo->prepare("SELECT * FROM profile_paket WHERE jenis_profile = 'Hotspot' AND status = '1' AND id_data_server = :id_data_server");
        $stmt->bindParam(':id_data_server', $id_data_server, PDO::PARAM_INT);
        $stmt->execute();
        $paket = $stmt->fetchAll(PDO::FETCH_ASSOC);
        foreach ($paket as $p) {
            $output[] = [
              'nama' => htmlspecialchars($p['nama']),
              'harga' => (int)$p['harga_paket'],
              'ids' => (int)$p['id_data_server'],
              'idm' => (int)$servers[0]['id'],
              'idv' => (int)$p['id']
            ];
        }
    }
    echo json_encode($output);
  ?>;

  const container = document.getElementById("voucher-container");
  container.innerHTML = "";
  if (data.length === 0) {
    container.innerHTML = "<p>Data Mikrotik tidak ditemukan.</p>";
    return;
  }
  data.forEach(p => {
    const html = `
      <div class="voucher-box">
        <div class="voucher-info">
          <div class="voucher-desc">${p.nama}</div>
          <div class="voucher-title">Rp. ${p.harga.toLocaleString()}</div>
        </div>
        <button class="btn-bayar" onclick="tampilkanKonfirmasi('${p.nama}', ${p.harga}, ${p.ids}, ${p.idm}, ${p.idv})">Beli</button>
      </div>
    `;
    container.innerHTML += html;
  });
  kirimHeight();
}

function kirimHeight() {
  const tinggi = document.body.scrollHeight;
  window.parent.postMessage({ frameHeight: tinggi }, "*");
}

window.addEventListener("load", () => {
  const status = localStorage.getItem("status");
  const kodeVoucher = localStorage.getItem("voucher");
  const expPay = localStorage.getItem("exppay");
  const qr = localStorage.getItem("qr");
  if (status === "Pending" && qr && expPay) {
    tampilkanQR(qr, expPay);
  } else if (status === "Lunas") {
    tampilkanSukses(localStorage.getItem("nama"), "Rp " + localStorage.getItem("harga"), localStorage.getItem("voucher"));
    parent.postMessage({
    type: "voucher_paid",
    voucher: localStorage.getItem("voucher")
  }, "*");
  } else {
    tampilkanListVoucher();
  }
});

window.addEventListener("resize", kirimHeight);
</script>
</body>
</html>
