<?php
require_once __DIR__ . '/../includes/pay_engine.php';
require_once __DIR__ . '/../includes/response.php';
require_once __DIR__ . '/../includes/CV111_pool_credit.php';

$keyId = trim($_GET['key'] ?? '');
if ($keyId === '') {
    http_response_code(400);
    die('Missing "key" parameter.');
}

$resolved = pay_resolve_key($keyId);
if (!$resolved) {
    http_response_code(404);
    die('Invalid or inactive key.');
}

$merchantId = $resolved['merchant_id'];
$subAccountId = $resolved['sub_account_id'];
$claimedByLabel = $subAccountId !== null ? ('subaccount_' . $subAccountId) : ('merchant_' . $merchantId);

$amount = isset($_GET['amount']) ? (float) $_GET['amount'] : 500.00;
// ✅ URL-এ redirect= না দিলে sub-account-এ সেভ করা website_url ব্যবহার হবে
$REDIRECT_URL = isset($_GET['redirect']) ? $_GET['redirect'] : ($resolved['website_url'] ?? '');
$REDIRECT_SECONDS = 25;

// ✅ ঐচ্ছিক — coin/balance automatic যোগ করার জন্য
$gameUid = trim($_GET['uid'] ?? '');

$walletInfo = pay_get_wallet_number($merchantId, 'nagad');
$WALLET_NO = $walletInfo ?? 'সংযুক্ত করা হয়নি';
$INSTRUCTION_TEXT = 'এই নম্বরে Send Money করুন';

$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['trxid'])) {
    $trxId = trim($_POST['trxid']);
    $postedAmount = (float) $_POST['amount'];
    $postedUid = trim($_POST['uid'] ?? $gameUid);

    if ($trxId === '') {
        $message = 'TrxID অবশ্যই পূরণ করতে হবে।';
        $messageType = 'error';
    } else {
        $result = pay_check_and_claim($merchantId, $subAccountId, $trxId, $postedAmount, $claimedByLabel);

        if (!$result['success']) {
            switch ($result['reason']) {
                case 'trxid_not_found':
                    $message = 'এই TrxID খুঁজে পাওয়া যায়নি। কিছুক্ষণ পর আবার চেষ্টা করো।';
                    break;
                case 'amount_mismatch':
                    $message = 'TrxID মিলেছে কিন্তু Amount মেলেনি।';
                    break;
                case 'already_claimed':
                    $message = 'এই payment ইতিমধ্যে ব্যবহার হয়ে গেছে।';
                    break;
                default:
                    $message = 'যাচাই করা যায়নি, আবার চেষ্টা করো।';
            }
            $messageType = 'error';
        } else {
            if ($postedUid !== '') {
                $poolResult = credit_CV111_balance_with_pool((int) $postedUid, $postedAmount);
                if (!$poolResult['success']) {
                    error_log('CV111 pool credit failed for transaction ' . $result['transaction_id'] . ': ' . $poolResult['reason']);
                }
            }

            $message = 'ডিপোজিট সফল হয়েছে! ৳' . number_format($postedAmount, 2) . ' যোগ হয়েছে।';
            $messageType = 'success';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>NAGAD Deposit</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body class="bg-gray-100 font-sans flex justify-center items-center min-h-screen p-0 sm:p-4">

    <div class="w-full max-w-md bg-white shadow-md rounded-none sm:rounded-lg overflow-hidden">

        <div class="bg-[#006A4E] text-white p-4">
            <div class="flex justify-between items-center mb-1">
                <h1 class="text-3xl font-bold">BDT <?php echo number_format($amount, 2); ?></h1>
                <div class="flex items-center space-x-2">
                    <span class="bg-white text-[#006A4E] text-xs font-bold px-2 py-0.5 rounded">PAY</span>
                    <span class="text-xs font-medium tracking-wide">SERVICE</span>
                </div>
            </div>
            <p class="text-base font-light">কম বা বেশি টাকা পাঠান করবেন না</p>
        </div>

        <?php if ($message): ?>
        <div class="p-3 text-base font-medium text-center <?php echo $messageType === 'success' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'; ?>">
            <?php echo htmlspecialchars($message); ?>
            <?php if ($messageType === 'success' && $REDIRECT_URL): ?>
                <div id="redirectCountdown" style="margin-top:6px; font-weight:600;">
                    <span id="countdownNumber"><?php echo $REDIRECT_SECONDS; ?></span> সেকেন্ডে ফিরে যাচ্ছেন...
                </div>
            <?php endif; ?>
        </div>
        <?php endif; ?>

        <div class="p-4 pt-5">
            <p class="text-red-600 font-semibold text-base leading-relaxed mb-4">
                আপনি যদি টাকার পরিমাণ পরিবর্তন করেন (BDT <?php echo number_format($amount, 2); ?>), আপনি ক্রেডিট পেতে সক্ষম হবেন না।
            </p>

            <div class="bg-[#EC1C24] text-white rounded-xl p-3 flex items-center mb-6 shadow-sm">
                <div class="w-10 h-10 flex items-center justify-center mr-3 flex-shrink-0">
                    <img src="https://getaway.winbigplay6.site/pay/unnamed.png" alt="Nagad" class="w-full h-full object-contain">
                </div>
                <span class="text-xl font-bold">NAGAD Deposit</span>
            </div>

            <form method="POST">
            <input type="hidden" name="amount" value="<?php echo htmlspecialchars($amount); ?>">
            <input type="hidden" name="uid" value="<?php echo htmlspecialchars($gameUid); ?>">

            <div class="mb-5">
                <label class="block text-gray-800 font-semibold text-sm mb-1">
                    Wallet No <span class="text-purple-700">*</span>
                </label>
                <p class="text-xs text-gray-600 mb-2">
                    <?php echo htmlspecialchars($INSTRUCTION_TEXT); ?>
                </p>
                <div class="relative">
                    <input
                        type="text"
                        id="walletNo"
                        value="<?php echo htmlspecialchars($WALLET_NO); ?>"
                        readonly
                        class="w-full border border-gray-300 rounded-lg py-3.5 px-3 text-gray-800 font-semibold text-lg focus:outline-none bg-gray-50"
                    >
                    <button type="button" onclick="copyWalletNo()" class="absolute right-3 top-1/2 -translate-y-1/2 text-red-500 hover:text-red-700">
                        <i class="fa-regular fa-copy text-xl"></i>
                    </button>
                </div>
            </div>

            <div class="mb-6">
                <label class="block text-[#5B2C6F] font-bold text-base mb-2">
                    সেন্ড মানির TrxID নাম্বারটি লিখুন<span class="text-[#5B2C6F]">(প্রয়োজন)</span>
                </label>
                <input
                    type="text"
                    name="trxid"
                    required
                    placeholder="TrxID অবশ্যই পূরণ করতে হবে!"
                    class="w-full border border-red-300 rounded-lg py-3.5 px-3 text-gray-600 placeholder-gray-400 text-lg focus:outline-none focus:border-red-500 text-center"
                >
            </div>

            <div class="flex justify-center mb-8">
                <button type="submit" class="w-2/5 border border-gray-300 bg-white hover:bg-gray-50 text-gray-800 font-semibold text-base py-2.5 px-4 rounded-lg shadow-sm text-center">
                    নিশ্চিত
                </button>
            </div>
            </form>

            <div class="space-y-3">
                <h3 class="text-red-600 font-bold text-lg">সতর্কতাঃ</h3>
                <p class="text-red-600 font-bold text-base leading-snug">
                    লেনদেন আইডি সঠিকভাবে পূরণ করতে হবে, অন্যথায় স্কোর ব্যর্থ হবে!!
                </p>
                <p class="text-gray-400 text-sm leading-relaxed">
                    অনুগ্ৰহ করে নিশ্চিত হয়ে নিন যে আপনি NAGAD ওয়ালেট নাম্বারে সেন্ড মানি করেছেন।
                </p>
            </div>

        </div>
    </div>

    <script>
        function copyWalletNo() {
            const copyText = document.getElementById("walletNo");
            navigator.clipboard.writeText(copyText.value);
            alert("Wallet number copied: " + copyText.value);
        }

        <?php if ($messageType === 'success' && $REDIRECT_URL): ?>
        (function () {
            let secondsLeft = <?php echo $REDIRECT_SECONDS; ?>;
            const numberEl = document.getElementById('countdownNumber');
            const timer = setInterval(function () {
                secondsLeft--;
                if (numberEl) numberEl.textContent = secondsLeft;
                if (secondsLeft <= 0) {
                    clearInterval(timer);
                    window.location.href = <?php echo json_encode($REDIRECT_URL); ?>;
                }
            }, 1000);
        })();
        <?php endif; ?>
    </script>
</body>
</html>
