<?php
/**
 * CV111_nagad_deposit.php
 * ===========================================================
 * এটা তোমার নিজের CV111 সার্ভারে (cv111.site) থাকবে।
 * PaymentGatewayClient.php দিয়ে আমাদের payment backend-এর সাথে কথা
 * বলে (verify + claim), আর pool-crediting সরাসরি তোমার নিজের
 * database-এই হয় (তোমার নিজের conn.php ব্যবহার করে)।
 *
 * URL যেভাবে খুলবে: CV111_nagad_deposit.php?amount=300&uid=123
 * ===========================================================
 */

require_once __DIR__ . '/PaymentGatewayClient.php';

// ⚠️ তোমার conn.php-এর সঠিক path বসাও (এটা তোমার নিজের CV111
// project-এ যেখানে conn.php আছে, সেই অনুযায়ী বদলাতে হতে পারে)
require_once __DIR__ . '/../../conn.php'; // $conn (mysqli) এখান থেকে পাওয়া যাবে

// ⚠️ তোমার নিজের API credentials — Merchant Panel থেকে পাওয়া
$client = new PaymentGatewayClient(
    'https://getaway.winbigplay6.site/api',
    'pk_696bce9caafa58193521115b',   // <-- তোমার key_id
    'তোমার_SECRET_এখানে'              // <-- তোমার secret
);

$amount = isset($_GET['amount']) ? (float) $_GET['amount'] : 500.00;
$uid = isset($_GET['uid']) ? (int) $_GET['uid'] : 0;

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

/**
 * তোমার sms_receive.php-এর হুবহু pool logic — এখানে সরাসরি mysqli
 * ($conn) ব্যবহার করে, যেহেতু এটা তোমার নিজের সার্ভারেই চলছে।
 */
function credit_pool_local($conn, int $userId, float $amount): array
{
    $poolIsAgent = false;
    $poolId = null;

    $selfQ = $conn->query("SELECT code FROM shonu_subjects WHERE id = '" . (int) $userId . "'");
    $selfRow = $selfQ ? $selfQ->fetch_assoc() : null;

    if ($selfRow && !empty($selfRow['code'])) {
        $refQ = $conn->query("SELECT id FROM shonu_subjects WHERE owncode = '" . $conn->real_escape_string($selfRow['code']) . "'");
        $refRow = $refQ ? $refQ->fetch_assoc() : null;
        if ($refRow) {
            $agentChk = $conn->query("SELECT userid FROM tb_agent WHERE userid = '{$refRow['id']}' AND status = '1'");
            if ($agentChk && $agentChk->num_rows > 0) {
                $poolIsAgent = true;
                $poolId = $refRow['id'];
            }
        }
    }

    if (!$poolIsAgent) {
        $adminRow = $conn->query("SELECT unohs FROM nirvahaka_shonu ORDER BY unohs ASC LIMIT 1")->fetch_assoc();
        $poolId = $adminRow['unohs'] ?? null;
    }

    if ($poolId === null) {
        return ['success' => false, 'reason' => 'pool_not_found'];
    }

    if ($poolIsAgent) {
        $poolBalRow = $conn->query("SELECT motta FROM shonu_kaichila WHERE balakedara = '$poolId'")->fetch_assoc();
    } else {
        $poolBalRow = $conn->query("SELECT motta FROM nirvahaka_shonu WHERE unohs = '$poolId'")->fetch_assoc();
    }
    $poolBalance = $poolBalRow ? (float) $poolBalRow['motta'] : 0;

    if ($poolBalance < $amount) {
        return ['success' => false, 'reason' => 'insufficient_pool_balance'];
    }

    $conn->begin_transaction();
    try {
        if ($poolIsAgent) {
            $deduct = $conn->prepare("UPDATE shonu_kaichila SET motta = motta - ? WHERE balakedara = ?");
        } else {
            $deduct = $conn->prepare("UPDATE nirvahaka_shonu SET motta = motta - ? WHERE unohs = ?");
        }
        $deduct->bind_param("di", $amount, $poolId);
        $deduct->execute();
        if ($deduct->affected_rows <= 0) throw new Exception('pool_deduction_failed');

        $userUpd = $conn->prepare("UPDATE shonu_kaichila SET motta = motta + ? WHERE balakedara = ?");
        $userUpd->bind_param("di", $amount, $userId);
        $userUpd->execute();

        if ($userUpd->affected_rows <= 0) {
            $check = $conn->prepare("SELECT balakedara FROM shonu_kaichila WHERE balakedara = ?");
            $check->bind_param("i", $userId);
            $check->execute();
            $exists = $check->get_result()->num_rows > 0;
            if (!$exists) {
                $create = $conn->prepare("INSERT INTO shonu_kaichila (balakedara, motta) VALUES (?, ?)");
                $create->bind_param("id", $userId, $amount);
                $create->execute();
                if ($create->affected_rows <= 0) throw new Exception('balance_row_create_failed');
            } else {
                throw new Exception('balance_update_failed');
            }
        }

        $conn->commit();
        return ['success' => true, 'reason' => null];
    } catch (Throwable $e) {
        $conn->rollback();
        error_log('credit_pool_local failed: ' . $e->getMessage());
        return ['success' => false, 'reason' => 'internal_error: ' . $e->getMessage()];
    }
}

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

    if ($trxId === '') {
        $message = 'TrxID অবশ্যই পূরণ করতে হবে।';
        $messageType = 'error';
    } else {
        try {
            $checkResult = $client->checkByTrxId($trxId, $postedAmount);

            if (!$checkResult['found']) {
                $message = 'এই TrxID খুঁজে পাওয়া যায়নি। কিছুক্ষণ পর আবার চেষ্টা করো।';
                $messageType = 'error';
            } else {
                $claimResult = $client->claimPayment($checkResult['transaction']['id'], 'CV111_' . $postedUid);

                if (!$claimResult['claimed']) {
                    $message = 'এই payment ইতিমধ্যে ব্যবহার হয়ে গেছে।';
                    $messageType = 'error';
                } else {
                    // ✅ Payment verify হয়ে গেছে — এখন তোমার নিজের database-এ
                    // pool থেকে কেটে user-এর balance-এ যোগ করো
                    $poolResult = credit_pool_local($conn, $postedUid, $postedAmount);

                    if (!$poolResult['success']) {
                        error_log('CV111 pool credit failed: ' . $poolResult['reason']);
                    }

                    $message = 'ডিপোজিট সফল হয়েছে! ৳' . number_format($postedAmount, 2) . ' যোগ হয়েছে।';
                    $messageType = 'success';
                }
            }
        } catch (Exception $e) {
            $message = 'যাচাই করতে সমস্যা হয়েছে, আবার চেষ্টা করো।';
            $messageType = 'error';
        }
    }
}

$walletInfo = $client->getWalletNumber('nagad');
$WALLET_NO = $walletInfo['wallet_number'] ?? 'সংযুক্ত করা হয়নি';
?>
<!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>
</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">
            <h1 class="text-3xl font-bold">BDT <?php echo number_format($amount, 2); ?></h1>
        </div>

        <?php if ($message): ?>
        <div class="p-3 text-sm font-medium text-center <?php echo $messageType === 'success' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'; ?>">
            <?php echo htmlspecialchars($message); ?>
        </div>
        <?php endif; ?>

        <div class="p-4 pt-5">
            <div class="bg-[#EC1C24] text-white rounded-xl p-3 flex items-center mb-6">
                <span class="text-lg 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($uid); ?>">

            <div class="mb-5">
                <label class="block text-gray-800 font-bold text-base mb-1">Wallet No</label>
                <input type="text" value="<?php echo htmlspecialchars($WALLET_NO); ?>" readonly
                    class="w-full border border-gray-200 rounded-lg py-3.5 px-3 text-gray-800 font-semibold text-lg bg-white">
            </div>

            <div class="mb-6">
                <label class="block text-[#4A154B] font-bold text-base mb-2">TrxID লিখুন</label>
                <input type="text" name="trxid" required
                    class="w-full border border-[#B0729B] rounded-lg py-3.5 px-3 text-lg text-center">
            </div>

            <button type="submit" class="w-full bg-[#006A4E] text-white font-bold py-3 rounded-lg">নিশ্চিত</button>
            </form>
        </div>
    </div>

</body>
</html>
