<?php
require_once '../includes/functions.php';
requireLogin();

$settings = getSettings($pdo);
$site_name = $settings['website_name'] ?? 'CRS Delhi';
$upi_id = $settings['upi_id'] ?? '';
$upi_name = $settings['upi_name'] ?? $site_name;

// Protection: Check if POSTed and Hash matches
$valid_hash = md5($_SESSION['user_id'] . 'RECHARGE_SALT');
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['amount']) || !isset($_POST['hash']) || $_POST['hash'] !== $valid_hash) {
    header("Location: my_wallet.php");
    exit();
}

$amount = number_format($_POST['amount'], 2, '.', '');
$upi_url = "upi://pay?pa=" . $upi_id . "&pn=" . rawurlencode($upi_name) . "&am=" . $amount . "&cu=INR";

include '../includes/header.php';
?>

<!-- QR JS Library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>

<div class="row justify-content-center animate-fade-in">
    <div class="col-md-5 col-lg-4">
        <div class="glass-card p-3 p-md-4 text-center">
            <div class="mb-3">
                <h5 class="fw-bold mb-0">UPI Payment</h5>
                <p class="text-muted small mb-0">Scan and pay to recharge</p>
            </div>

            <div class="bg-light p-3 rounded-4 mb-3 position-relative">
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <div id="payment-timer" class="badge bg-danger rounded-pill px-2 py-1 small">
                        05:00
                    </div>
                </div>
                
                <div class="mb-2">
                    <h3 class="fw-800 text-primary mb-0">₹<?php echo $amount; ?></h3>
                    <p class="text-muted small mb-0">Payable to: <strong><?php echo htmlspecialchars($upi_name); ?></strong></p>
                </div>

                <div class="qr-container bg-white p-2 d-inline-block rounded-3 shadow-sm mb-2">
                    <div id="qrcode"></div>
                </div>

                <div class="mt-1">
                    <a href="<?php echo $upi_url; ?>" class="btn btn-outline-primary btn-sm rounded-pill d-md-none py-1">
                        <i class="fas fa-mobile-screen me-1"></i> Pay via UPI App
                    </a>
                </div>
            </div>

            <form action="my_wallet.php" method="POST" enctype="multipart/form-data" id="upi-confirm-form">
                <input type="hidden" name="amount" value="<?php echo $amount; ?>">
                
                <div class="text-start mb-3">
                    <label class="form-label fw-bold x-small mb-1 text-uppercase text-muted">Transaction ID / UTR</label>
                    <div class="input-group input-group-sm">
                        <span class="input-group-text bg-white border-end-0 text-muted"><i class="fas fa-fingerprint"></i></span>
                        <input type="text" name="utr" class="form-control border-start-0 bg-white" placeholder="12-digit UTR No" required pattern="[0-9]{12,20}">
                    </div>
                </div>

                <div class="text-start mb-3">
                    <label class="form-label fw-bold x-small mb-1 text-uppercase text-muted">Screenshot (Optional)</label>
                    <input type="file" name="screenshot" class="form-control form-control-sm bg-white" accept="image/*">
                </div>

                <button type="submit" class="btn btn-premium btn-sm w-100 py-2 shadow fw-bold">
                    CONFIRM PAYMENT <i class="fas fa-paper-plane ms-2"></i>
                </button>
                
                <a href="my_wallet.php" class="btn btn-link text-muted mt-2 text-decoration-none x-small d-block">
                    <i class="fas fa-arrow-left me-1"></i> Cancel
                </a>
            </form>
        </div>
    </div>
</div>

<style>
    .x-small { font-size: 0.75rem; }
    #qrcode img { margin: 0 auto; max-width: 180px; }
    .glass-card { border-radius: 1.5rem; }
</style>

<script>
    // Generate QR Code
    new QRCode(document.getElementById("qrcode"), {
        text: "<?php echo $upi_url; ?>",
        width: 180,
        height: 180,
        colorDark : "#000000",
        colorLight : "#ffffff",
        correctLevel : QRCode.CorrectLevel.M
    });

    // Timer Logic
    let timeLeft = 300; // 5 minutes
    const timerDisplay = document.getElementById('payment-timer');

    const countdown = setInterval(() => {
        if (timeLeft <= 0) {
            clearInterval(countdown);
            timerDisplay.innerHTML = "Expired";
            document.getElementById('upi-confirm-form').innerHTML = '<div class="alert alert-danger border-0 rounded-4 p-4"><i class="fas fa-clock-rotate-left fa-2x mb-3"></i><h4>Session Expired</h4><p>The payment session has expired. Please try again.</p><a href="my_wallet.php" class="btn btn-danger rounded-pill px-4">Restart Payment</a></div>';
        } else {
            const minutes = Math.floor(timeLeft / 60);
            const seconds = timeLeft % 60;
            timerDisplay.innerHTML = `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
        }
        timeLeft -= 1;
    }, 1000);

    // Prevent Double Submit
    document.getElementById('upi-confirm-form').onsubmit = function() {
        this.querySelector('button[type="submit"]').disabled = true;
        this.querySelector('button[type="submit"]').innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i> Verifying...';
    };
</script>

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