<?php
session_start();
require_once 'config.php';

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

$userId = $_SESSION['user_id'];
global $pdo;

// 1. HANDLE UTR SUBMISSION & CREATE ORDER
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submit_utr'])) {
    $original_amount = (float)$_SESSION['pending_deposit']['amount'];
    $actual_amount = (float)$_SESSION['pending_deposit']['actual_amount'];
    $channel_id = (int)$_SESSION['pending_deposit']['channel_id'];
    $utr = trim($_POST['utr_number']);

    if (!empty($utr) && strlen($utr) >= 12) {
        // GENERATE UNIQUE ORDER ID
        $order_id = "RC" . date('YmdHis') . rand(1000, 9999);

        $ins = $pdo->prepare("INSERT INTO deposit_requests (order_id, user_id, channel_id, amount, actual_pay_amount, utr_number, status) VALUES (?, ?, ?, ?, ?, ?, 'pending')");
        $ins->execute([$order_id, $userId, $channel_id, $original_amount, $actual_amount, $utr]);
        
        unset($_SESSION['pending_deposit']);
        header("Location: deposit_history.php");
        exit;
    }
}

// 2. SECURE SESSION STORAGE (When coming from deposit.php)
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['amount']) && isset($_POST['channel_id'])) {
    $discount = rand(1, 99) / 100;
    $_SESSION['pending_deposit'] = [
        'amount' => (float)$_POST['amount'],
        'channel_id' => (int)$_POST['channel_id'],
        'discount' => $discount,
        'actual_amount' => (float)$_POST['amount'] - $discount,
        'time' => time()
    ];
}

// 3. FETCH DATA FROM SESSION
$originalAmount = $_SESSION['pending_deposit']['amount'] ?? 0;
$channelId = $_SESSION['pending_deposit']['channel_id'] ?? 0;
$discount = $_SESSION['pending_deposit']['discount'] ?? 0;
$actualPayAmount = $_SESSION['pending_deposit']['actual_amount'] ?? 0;

// Silent Redirect without Popup if accessed directly
if ($originalAmount <= 0 || $channelId <= 0) {
    header("Location: deposit.php");
    exit;
}

// 4. FETCH UPI ID FROM DATABASE
$stmt = $pdo->prepare("SELECT pay_address FROM payment_channels WHERE id = ?");
$stmt->execute([$channelId]);
$upi_id = $stmt->fetchColumn();

if (!$upi_id) {
    die("Payment channel not configured properly by Admin.");
}

// 5. GENERATE UPI URL FOR QR
$merchantName = "ARPay";
$upi_url = "upi://pay?pa={$upi_id}&pn={$merchantName}&am={$actualPayAmount}&cu=INR";
$qr_image_url = "https://api.qrserver.com/v1/create-qr-code/?size=250x250&data=" . urlencode($upi_url);

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>ArUpiPay - Gateway</title>
    <style>
        @font-face { font-family: 'Bahnschrift'; src: url('https://91appt.com/assets/woff2/bahnschrift-610d57ac.woff2') format('woff2'); font-display: swap; }
        :root { --bg-color: #F1F2F5; --main-red: #F95959; --text-dark: #333; --text-light: #999; }
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: -apple-system, sans-serif; -webkit-tap-highlight-color: transparent;}
        body { background: var(--bg-color); color: var(--text-dark); max-width: 480px; margin: 0 auto; padding-bottom: 20px; }
        .bahnschrift { font-family: 'Bahnschrift', sans-serif !important; }

        .header { background: #fff; display: flex; justify-content: space-between; align-items: center; padding: 15px; box-shadow: 0 2px 5px rgba(0,0,0,0.05); }
        .back-btn { font-size: 18px; color: #666; cursor: pointer; text-decoration: none;}
        .title { font-size: 16px; font-weight: 600; }
        .cs-btn { background: #ffeded; color: var(--main-red); font-size: 11px; padding: 4px 10px; border-radius: 15px; font-weight: bold; }

        .container { padding: 15px; }
        .top-card { background: #fff; border-radius: 10px; padding: 15px; display: flex; justify-content: space-between; align-items: center; box-shadow: 0 2px 8px rgba(0,0,0,0.02); margin-bottom: 15px; }
        .amt-wrapper { display: flex; align-items: center; gap: 8px; }
        .amt-text { font-size: 26px; font-weight: bold; color: var(--text-dark); }
        .discount-tag { background: #ffeded; color: var(--main-red); font-size: 10px; padding: 2px 6px; border-radius: 4px; border: 1px solid #ffcdcd; }
        .timer-text { font-size: 18px; font-weight: bold; color: var(--main-red); }

        .sec-title { font-size: 13px; font-weight: bold; color: var(--main-red); display: flex; align-items: center; gap: 5px; margin-bottom: 10px; }
        .sec-title::before { content: ''; width: 4px; height: 4px; background: var(--main-red); border-radius: 50%; }

        .apps-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 20px; }
        .app-btn { border-radius: 8px; padding: 12px; text-align: center; text-decoration: none; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 5px; box-shadow: 0 2px 5px rgba(0,0,0,0.05); transition: 0.2s; }
        .app-btn:active { transform: scale(0.97); }
        .btn-paytm { background: linear-gradient(180deg, #E6F3FF 0%, #CDE6FF 100%); border: 1px solid #B3D8FF; }
        .btn-phonepe { background: linear-gradient(180deg, #F5E6FF 0%, #E8CDFF 100%); border: 1px solid #DDB3FF; }
        .app-name { font-size: 14px; font-weight: bold; color: #333; display: flex; align-items: center; gap:5px;}
        .app-sub { font-size: 11px; color: #666; font-weight: 500; }

        .qr-card { background: #fff; border-radius: 10px; padding: 20px; text-align: center; box-shadow: 0 2px 8px rgba(0,0,0,0.02); margin-bottom: 20px; }
        .qr-img { width: 180px; height: 180px; border: 1px solid #eee; padding: 5px; border-radius: 10px; margin: 0 auto 15px; display: block; }
        .instructions { font-size: 11px; color: var(--text-light); text-align: left; line-height: 1.5; }

        .utr-card { background: #fff; border-radius: 10px; padding: 15px; box-shadow: 0 2px 8px rgba(0,0,0,0.02); margin-bottom: 20px;}
        .warning-text { color: var(--main-red); font-size: 11px; font-weight: bold; margin-bottom: 10px; text-align: center;}
        
        .input-wrap { position: relative; display: flex; align-items: center; }
        .utr-input { width: 100%; border: 1px solid #ddd; border-radius: 25px; padding: 12px 15px; font-size: 14px; outline: none; background: #f9f9f9; transition: 0.3s;}
        .utr-input:focus { border-color: var(--main-red); background: #fff; }
        .paste-btn { position: absolute; right: 5px; background: var(--main-red); color: #fff; border: none; width: 34px; height: 34px; border-radius: 50%; display: flex; align-items: center; justify-content: center; cursor: pointer; }
        .imp-reminder { font-size: 12px; font-weight: bold; color: #333; margin-top: 15px; display: flex; align-items: center; gap: 5px;}
        .imp-reminder::before { content: ''; width: 4px; height: 4px; background: #333; border-radius: 50%; }

        .action-btns { display: flex; gap: 10px; }
        .btn-cancel { flex: 1; background: #fff; border: 1px solid #ddd; color: #666; padding: 12px; border-radius: 25px; font-weight: bold; font-size: 14px; cursor: pointer; text-align:center; text-decoration:none;}
        .btn-submit { flex: 2; background: #ccc; border: none; color: #fff; padding: 12px; border-radius: 25px; font-weight: bold; font-size: 14px; transition: 0.3s; cursor: not-allowed; }
        .btn-submit.active { background: linear-gradient(90deg, #ff7b7b, #f3595b); box-shadow: 0 4px 10px rgba(243, 89, 91, 0.3); cursor: pointer; }
    </style>
</head>
<body>

    <div class="header">
        <a href="deposit.php" class="back-btn">❮</a>
        <div class="title">ArUpiPay</div>
        <div class="cs-btn">Customer Service</div>
    </div>

    <div class="container">
        
        <div class="top-card">
            <div class="amt-wrapper">
                <span class="amt-text bahnschrift">₹<?= $actualPayAmount ?></span>
                <span class="discount-tag">Discount ₹<?= $discount ?></span>
            </div>
            <div class="timer-text bahnschrift" id="timer">15:00</div>
        </div>

        <div class="sec-title">Choose a payment method to pay</div>
        <div class="apps-grid">
            <a href="paytmmp://pay?pa=<?= $upi_id ?>&pn=<?= $merchantName ?>&am=<?= $actualPayAmount ?>&cu=INR" class="app-btn btn-paytm">
                <div class="app-name">
                    <svg viewBox="0 0 24 24" width="18" height="18" fill="#00baf2"><path d="M7 13.5v-3h1v3H7zm3.5-3h-1.5v3h1v-1.5h.5c.8 0 1.5-.5 1.5-1.5s-.7-1.5-1.5-1.5zm0 1.2h-.5v-.5h.5c.3 0 .5.1.5.5s-.2.7-.5.7zm4.5 1.8v-3h-1v3h1zm3.5-3h-1.5v3h1v-1.5h.5c.8 0 1.5-.5 1.5-1.5s-.7-1.5-1.5-1.5zm0 1.2h-.5v-.5h.5c.3 0 .5.1.5.5s-.2.7-.5.7zM2 4h20v16H2V4z"/></svg>
                    Paytm
                </div>
                <div class="app-sub">Wake up support</div>
            </a>
            
            <a href="phonepe://pay?pa=<?= $upi_id ?>&pn=<?= $merchantName ?>&am=<?= $actualPayAmount ?>&cu=INR" class="app-btn btn-phonepe">
                <div class="app-name">
                    <svg viewBox="0 0 24 24" width="18" height="18" fill="#5f259f"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 14.5v-4H8v-2h3V8c0-1.1.9-2 2-2h3v2h-3v2.5h3v2h-3v4h-2z"/></svg>
                    PhonePe
                </div>
                <div class="app-sub">Wake up support</div>
            </a>
        </div>

        <div class="sec-title">Use Mobile Scan code to pay</div>
        <div class="qr-card">
            <img src="<?= $qr_image_url ?>" class="qr-img" alt="UPI QR Code">
            <div class="instructions">
                1. Please use another device to scan the QR code with your payment app.<br>
                2. If you scan the QR code from this device's gallery, the payment amount may be limited (≤2000).<br>
                3. Pay to UPI: <b><?= htmlspecialchars($upi_id) ?></b>
            </div>
        </div>

        <div class="sec-title">Input UTR/ Paste UTR</div>
        <div class="utr-card">
            <div class="warning-text">If you do not back fill UTR/ paste UTR, 100% will fail.</div>
            
            <form method="POST" action="" id="payForm">
                <div class="input-wrap">
                    <input type="number" name="utr_number" id="utr_input" class="utr-input bahnschrift" placeholder="Input 12 digits here" required oninput="validateUTR()">
                    <button type="button" class="paste-btn" onclick="pasteUTR()">
                        <svg width="16" height="16" fill="#fff" viewBox="0 0 24 24"><path d="M19 2h-4.18C14.4.84 13.3 0 12 0c-1.3 0-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-7 0c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm7 18H5V4h2v3h10V4h2v16z"/></svg>
                    </button>
                </div>
                <div class="imp-reminder">Important reminder: Please ensure the UTR is correct.</div>
            </form>
        </div>

        <div class="action-btns">
            <a href="deposit.php" class="btn-cancel">Cancel</a>
            <button type="submit" name="submit_utr" form="payForm" id="submit_btn" class="btn-submit" disabled>Submit (UTR not entered)</button>
        </div>

    </div>

    <script>
        let timeLeft = 15 * 60;
        const timerEl = document.getElementById('timer');
        
        const countdown = setInterval(() => {
            if (timeLeft <= 0) {
                clearInterval(countdown);
                alert("Payment time expired!");
                window.location.href = 'deposit.php';
            } else {
                let m = Math.floor(timeLeft / 60);
                let s = timeLeft % 60;
                timerEl.innerText = (m < 10 ? '0' : '') + m + ':' + (s < 10 ? '0' : '') + s;
                timeLeft--;
            }
        }, 1000);

        function validateUTR() {
            const val = document.getElementById('utr_input').value;
            const btn = document.getElementById('submit_btn');
            
            if (val.length >= 12) {
                btn.disabled = false;
                btn.classList.add('active');
                btn.innerText = 'Submit';
            } else {
                btn.disabled = true;
                btn.classList.remove('active');
                btn.innerText = 'Submit (UTR not entered)';
            }
        }

        async function pasteUTR() {
            try {
                const text = await navigator.clipboard.readText();
                if(/^\d+$/.test(text.trim())) {
                    document.getElementById('utr_input').value = text.trim();
                    validateUTR();
                } else {
                    alert("Clipboard does not contain a valid UTR number.");
                }
            } catch (err) {
                alert('Failed to read clipboard contents.');
            }
        }
    </script>
</body>
</html>