<?php

include 'header.php';
include 'config/koneksi.php';

date_default_timezone_set('Asia/Jakarta');

if (!isset($_GET['order_id'], $_GET['method'])) {
    header("Location: membership.php");
    exit;
}

$order_id = $_GET['order_id'];
$method = $_GET['method'];
$va_number = $_GET['va'] ?? null;

$query = "SELECT * FROM orders WHERE order_id = '$order_id'";
$result = mysqli_query($conn, $query);

if (!$order = mysqli_fetch_assoc($result)) {
    header("Location: membership.php");
    exit;
}

$status = strtolower($order['status']);
if ($status === 'selesai' || $status === 'dibayar') {
    header("Location: transaksi.php");
    exit;
}

$tanggal_order = $order['tanggal_order'];
$deadline_timestamp = strtotime($tanggal_order) + (24 * 60 * 60); 
?>

<div class="container my-5">
    <h2 class="text-center mb-4">Detail Pembayaran</h2>

    <div id="countdown" class="alert alert-warning text-center fw-bold mb-4"></div>

    <?php if ($method == "Bayar Admin"): ?>
        <div class="alert alert-info text-center">
            <h5>Tunjukkan Order ID ini ke Admin:</h5>
            <h4><strong><?= htmlspecialchars($order_id) ?></strong></h4>
            <p>Total yang harus dibayar: <strong>Rp <?= number_format($order['total_harga'], 0, ',', '.') ?></strong></p>
        </div>

    <?php elseif ($method == "Transfer Bank" && $va_number): ?>
        <div class="alert alert-success text-center">
            <h5>Transfer ke Virtual Account berikut:</h5>
            <h4><strong><?= htmlspecialchars($va_number) ?></strong></h4>
            <p>Total yang harus ditransfer: <strong>Rp <?= number_format($order['total_harga'], 0, ',', '.') ?></strong></p>
        </div>

    <?php else: ?>
        <div class="alert alert-danger text-center">
            Metode pembayaran tidak valid.
        </div>
    <?php endif; ?>
</div>

<script>
const deadline = <?= $deadline_timestamp * 1000 ?>;
const countdownEl = document.getElementById("countdown");

function updateCountdown() {
    const now = new Date().getTime();
    const distance = deadline - now;

    if (distance <= 0) {
        countdownEl.innerHTML = "⏳ Waktu pembayaran telah habis!";
        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);

    countdownEl.innerHTML = `Sisa Waktu: ${hours} jam ${minutes} menit ${seconds} detik`;
}

updateCountdown();
setInterval(updateCountdown, 1000);
</script>

<?php
include 'footer.php';
ob_end_flush(); 
?>
