<?php
// payment.php - Active Countdown Payment Gateway & Simulator

require_once 'includes/helper.php';
require_once 'classes/Order.php';

start_secure_session();

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$orderId = (int)($_GET['order_id'] ?? 0);
$orderObj = new Order();
$order = $orderObj->getStatusAndCountdown($orderId);

if (!$order || $order['user_id'] != $_SESSION['user_id']) {
    header("Location: index.php");
    exit();
}

$error = '';
$csrfToken = generate_csrf_token();

// Handle confirm payment request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'confirm_payment') {
    $token = $_POST['csrf_token'] ?? '';
    $paymentMethod = trim($_POST['payment_method'] ?? 'promptpay');

    if (!validate_csrf_token($token)) {
        $error = "ระบบความปลอดภัย: CSRF Token ไม่ถูกต้อง";
    } else {
        try {
            $txnId = 'TXN' . strtoupper(bin2hex(random_bytes(6)));
            
            // This method validates the 20-minute server time check and completes the transaction
            $orderObj->pay($orderId, $paymentMethod, $txnId);
            
            header("Location: success.php?order_id=" . $orderId);
            exit();
        } catch (Exception $e) {
            $error = $e->getMessage();
        }
    }
}

require_once 'includes/header.php';
?>

<div class="max-w-2xl mx-auto my-4 sm:my-6">
    <div class="glass p-6 sm:p-8 rounded-2xl sm:rounded-3xl shadow-2xl relative overflow-hidden">
        <div class="absolute -top-12 -left-12 w-32 h-32 bg-violet-600/10 rounded-full blur-2xl pointer-events-none"></div>

        <h2 class="text-2xl sm:text-3xl font-extrabold text-white mb-2 tracking-tight text-center">ชำระเงินคำสั่งซื้อ #<?= $order['id'] ?></h2>
        <p class="text-slate-400 text-sm text-center mb-6 sm:mb-8">กรุณาชำระเงินจำนวน: <span class="text-violet-400 font-extrabold text-lg sm:text-xl"><?= format_price($order['total_amount']) ?></span></p>

        <?php if ($error): ?>
            <div id="error-alert" class="bg-red-950/60 border border-red-800 text-red-300 p-4 rounded-xl text-sm mb-6 text-center animate-pulse">
                ⚠️ <?= escape($error) ?>
            </div>
        <?php endif; ?>

        <!-- Active Timer Display -->
        <?php if ($order['status'] === 'pending'): ?>
                <div id="payment-section" class="space-y-6 sm:space-y-8">
                <div class="bg-slate-900/60 border border-slate-800 rounded-xl sm:rounded-2xl p-4 sm:p-6 text-center">
                    <p class="text-xs uppercase tracking-wider text-slate-400 font-semibold mb-2">เวลานับถอยหลังในการชำระเงิน</p>
                    
                    <!-- Clock display -->
                    <div id="timer-clock" class="text-4xl sm:text-5xl font-black text-violet-400 font-mono tracking-widest my-2">
                        20:00
                    </div>
                    
                    <div class="w-full bg-slate-800 h-1.5 rounded-full overflow-hidden mt-4">
                        <div id="timer-progress" class="bg-violet-600 h-full w-full transition-all duration-1000"></div>
                    </div>
                </div>

                <!-- Simulation Form -->
                <form action="payment.php?order_id=<?= $order['id'] ?>" method="POST" class="space-y-6">
                    <input type="hidden" name="csrf_token" value="<?= escape($csrfToken) ?>">
                    <input type="hidden" name="action" value="confirm_payment">

                    <div>
                        <label class="block text-xs font-semibold uppercase tracking-wider text-slate-400 mb-3">เลือกวิธีชำระเงินที่ต้องการ</label>
                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                            <label class="border border-slate-800 bg-slate-900/60 rounded-xl p-4 flex items-center gap-3 cursor-pointer hover:border-violet-500/40 transition-all">
                                <input type="radio" name="payment_method" value="promptpay" checked class="text-violet-600 focus:ring-violet-500 shrink-0">
                                <div>
                                    <span class="text-sm font-semibold text-slate-200 block">PromptPay 📲</span>
                                    <span class="text-xs text-slate-500">สแกนเพื่อโอนเงิน</span>
                                </div>
                            </label>
                            <label class="border border-slate-800 bg-slate-900/60 rounded-xl p-4 flex items-center gap-3 cursor-pointer hover:border-violet-500/40 transition-all">
                                <input type="radio" name="payment_method" value="credit_card" class="text-violet-600 focus:ring-violet-500 shrink-0">
                                <div>
                                    <span class="text-sm font-semibold text-slate-200 block">บัตรเครดิต 💳</span>
                                    <span class="text-xs text-slate-500">กรอกข้อมูลบัตร</span>
                                </div>
                            </label>
                        </div>
                    </div>

                    <button type="submit" class="w-full py-3.5 sm:py-4 bg-emerald-600 hover:bg-emerald-500 text-white font-bold rounded-xl sm:rounded-2xl shadow-lg shadow-emerald-600/20 transition-all duration-200 active:scale-95 text-sm sm:text-base">
                        ยืนยันการชำระเงินสำเร็จ (Confirm Payment) ✅
                    </button>
                </form>
            </div>
            
            <!-- Expired State (Hidden by default, shown by JS/AJAX) -->
            <div id="expired-section" class="hidden bg-red-950/20 border border-red-900/30 rounded-2xl p-8 text-center animate-fade-in">
                <span class="text-5xl block mb-3">❌</span>
                <h3 class="text-lg font-bold text-red-400 mb-1">หมดเวลาชำระเงิน ออเดอร์ของคุณถูกยกเลิกแล้ว</h3>
                <p class="text-sm text-slate-400 leading-relaxed max-w-sm mx-auto">เวลาการจ่ายเงิน 20 นาทีหมดลงเรียบร้อยแล้ว ระบบได้ดึงสินค้าของท่านกลับเข้าสต็อกเรียบร้อยแล้ว</p>
                <a href="index.php" class="inline-block mt-6 px-6 py-2.5 bg-slate-900 border border-slate-800 text-sm font-semibold rounded-xl text-slate-300 hover:bg-slate-800 transition-colors">กลับไปที่ร้านค้า</a>
            </div>

        <?php else: ?>
            <!-- Static display if not pending -->
            <div class="bg-red-950/20 border border-red-900/30 rounded-2xl p-8 text-center">
                <span class="text-5xl block mb-3">❌</span>
                <h3 class="text-lg font-bold text-red-400 mb-1">สถานะคำสั่งซื้อไม่ถูกต้อง</h3>
                <p class="text-sm text-slate-400">คำสั่งซื้อนี้มีสถานะเป็น: <?= escape($order['status']) ?></p>
                <a href="index.php" class="inline-block mt-6 px-6 py-2.5 bg-slate-900 border border-slate-800 text-sm font-semibold rounded-xl text-slate-300 hover:bg-slate-800 transition-colors">กลับหน้าหลัก</a>
            </div>
        <?php endif; ?>
    </div>
</div>

<?php if ($order['status'] === 'pending'): ?>
<script>
    const totalDuration = 20 * 60; // 20 mins
    let remainingSeconds = <?= (int)$order['remaining_seconds'] ?>;
    
    const clock = document.getElementById('timer-clock');
    const bar = document.getElementById('timer-progress');
    const paymentSection = document.getElementById('payment-section');
    const expiredSection = document.getElementById('expired-section');
    
    function updateCountdown() {
        if (remainingSeconds <= 0) {
            clearInterval(timerInterval);
            clock.textContent = "00:00";
            bar.style.width = "0%";
            
            // Execute AJAX call to notify server order is expired
            const xhr = new XMLHttpRequest();
            xhr.open("POST", "api_expire.php", true);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    // Update frontend view state
                    paymentSection.classList.add('hidden');
                    expiredSection.classList.remove('hidden');
                    const errorAlert = document.getElementById('error-alert');
                    if (errorAlert) errorAlert.remove();
                }
            };
            xhr.send("order_id=" + <?= $order['id'] ?> + "&csrf_token=<?= escape($csrfToken) ?>");
            return;
        }
        
        const mins = Math.floor(remainingSeconds / 60);
        const secs = remainingSeconds % 60;
        
        clock.textContent = `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
        bar.style.width = `${(remainingSeconds / totalDuration) * 100}%`;
        
        remainingSeconds--;
    }
    
    updateCountdown();
    const timerInterval = setInterval(updateCountdown, 1000);
</script>
<?php endif; ?>

<?php require_once 'includes/footer.php'; ?>
