<?php
/**
 * pay/bkash.php
 * bKash Deposit Gateway Integration
 */

include(__DIR__ . "/../service/samparka.php");

/* =========================================================
   PAYMENT GATEWAY SETTINGS
   ========================================================= */
define('PG_BASE_URL', 'https://getaway.winbigplay6.site/api');
define('PG_API_KEY_ID', 'pk_fbc6109b3ad854f2324e8372');
define('PG_API_SECRET', '39ced892f4c4bfaa9468e3a9da2d783082ba310225693a97');

/* =========================================================
   GATEWAY CLIENT
   ========================================================= */
class CV111GatewayClient
{
    private string $baseUrl;
    private string $apiKeyId;
    private string $apiSecret;

    public function __construct(string $baseUrl, string $apiKeyId, string $apiSecret)
    {
        $this->baseUrl = rtrim($baseUrl, '/');
        $this->apiKeyId = $apiKeyId;
        $this->apiSecret = $apiSecret;
    }

    private function signedGet(string $path): array
    {
        $timestamp = time();
        $nonce = bin2hex(random_bytes(16));
        $rawBody = '';
        $payload = $timestamp . '.' . $nonce . '.' . $rawBody;
        $signature = hash_hmac('sha256', $payload, $this->apiSecret);

        $ch = curl_init($this->baseUrl . $path);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => [
                'X-Api-Key: ' . $this->apiKeyId,
                'X-Timestamp: ' . $timestamp,
                'X-Nonce: ' . $nonce,
                'X-Signature: ' . $signature,
            ],
            CURLOPT_TIMEOUT => 15,
            CURLOPT_CONNECTTIMEOUT => 8,
            CURLOPT_SSL_VERIFYPEER => true,
        ]);

        $response = curl_exec($ch);
        $httpCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);
        curl_close($ch);

        if ($response === false) {
            return [
                'found' => false,
                'reason' => 'network_error',
                'message' => $curlError
            ];
        }

        $decoded = json_decode($response, true);

        if (!is_array($decoded)) {
            return [
                'found' => false,
                'reason' => 'invalid_response'
            ];
        }

        if ($httpCode !== 200) {
            return [
                'found' => false,
                'reason' => $decoded['error'] ?? 'gateway_error',
                'message' => $decoded['message'] ?? ''
            ];
        }

        return $decoded;
    }

    public function getWalletNumber(string $provider): array
    {
        return $this->signedGet(
            '/merchant/get_wallet.php?' . http_build_query([
                'provider' => $provider
            ])
        );
    }

    public function checkByTrxId(string $trxId, float $amount): array
    {
        return $this->signedGet(
            '/merchant/check_by_trxid.php?' . http_build_query([
                'trxid' => $trxId,
                'amount' => number_format($amount, 2, '.', '')
            ])
        );
    }

    public function claimPayment($transactionId, string $claimedBy): array
    {
        $timestamp = time();
        $nonce = bin2hex(random_bytes(16));

        $bodyArr = [
            'transaction_id' => $transactionId,
            'claimed_by' => $claimedBy
        ];

        $rawBody = json_encode($bodyArr, JSON_UNESCAPED_SLASHES);
        $payload = $timestamp . '.' . $nonce . '.' . $rawBody;
        $signature = hash_hmac('sha256', $payload, $this->apiSecret);

        $ch = curl_init($this->baseUrl . '/merchant/claim_transaction.php');

        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $rawBody,
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'X-Api-Key: ' . $this->apiKeyId,
                'X-Timestamp: ' . $timestamp,
                'X-Nonce: ' . $nonce,
                'X-Signature: ' . $signature,
            ],
            CURLOPT_TIMEOUT => 15,
            CURLOPT_CONNECTTIMEOUT => 8,
            CURLOPT_SSL_VERIFYPEER => true,
        ]);

        $response = curl_exec($ch);
        $httpCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);
        curl_close($ch);

        if ($response === false) {
            return [
                'claimed' => false,
                'reason' => 'network_error',
                'message' => $curlError
            ];
        }

        $decoded = json_decode($response, true);

        if (!is_array($decoded)) {
            return [
                'claimed' => false,
                'reason' => 'invalid_response'
            ];
        }

        if ($httpCode < 200 || $httpCode >= 300) {
            $decoded['claimed'] = false;
            $decoded['reason'] = $decoded['reason'] ?? ($decoded['error'] ?? 'gateway_error');
        }

        return $decoded;
    }
}

/* =========================================================
   BASIC HELPERS
   ========================================================= */
function e($value): string
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function gatewayConfigLooksUnset(): bool
{
    return PG_API_KEY_ID === '' ||
           PG_API_SECRET === '' ||
           PG_API_KEY_ID === 'pk_xxxxxxxxxxxxxxxx' ||
           PG_API_SECRET === 'PUT_YOUR_GATEWAY_SECRET_HERE';
}

/* =========================================================
   USER / URL DATA
   ========================================================= */
$auto_uid = isset($_GET['uid']) ? (int)$_GET['uid'] : (isset($_POST['uid']) ? (int)$_POST['uid'] : 0);
$auto_amount = isset($_GET['amount']) ? (float)$_GET['amount'] : (isset($_POST['locked_amount']) ? (float)$_POST['locked_amount'] : 0);
$auto_wants_bonus = isset($_GET['wantsBonus']) && $_GET['wantsBonus'] === '1';

$auto_user = null;

if ($auto_uid > 0) {
    $uidEsc = (int)$auto_uid;

    $userQ = mysqli_query(
        $conn,
        "SELECT id, mobile FROM shonu_subjects WHERE id = '$uidEsc' AND status = '1' LIMIT 1"
    );

    if ($userQ) {
        $auto_user = mysqli_fetch_assoc($userQ);
    }
}

/* =========================================================
   FIRST DEPOSIT BONUS ELIGIBILITY
   ========================================================= */
$isFirstDepositEligible = false;

if ($auto_user) {
    $checkUid = (int)$auto_user['id'];

    $prevDep = @mysqli_query(
        $conn,
        "SELECT id FROM thevani
         WHERE balakedara = '$checkUid' AND sthiti = 1
         LIMIT 1"
    );

    $prevBonus = @mysqli_query(
        $conn,
        "SELECT id FROM first_deposit_bonus_claims
         WHERE user_id = '$checkUid'
         LIMIT 1"
    );

    $noPrevDeposit = $prevDep ? (mysqli_num_rows($prevDep) === 0) : true;
    $noPrevBonus = $prevBonus ? (mysqli_num_rows($prevBonus) === 0) : true;

    $isFirstDepositEligible = $noPrevDeposit && $noPrevBonus;
}

/* =========================================================
   GATEWAY WALLET NUMBER
   ========================================================= */
$BKASH_NUMBER = 'Gateway wallet unavailable';

if (!gatewayConfigLooksUnset()) {
    try {
        $gateway = new CV111GatewayClient(
            PG_BASE_URL,
            PG_API_KEY_ID,
            PG_API_SECRET
        );

        $walletResult = $gateway->getWalletNumber('bkash');

        if (
            !empty($walletResult['wallet_number']) &&
            is_string($walletResult['wallet_number'])
        ) {
            $BKASH_NUMBER = $walletResult['wallet_number'];
        } elseif (!empty($walletResult['wallet']['number'])) {
            $BKASH_NUMBER = $walletResult['wallet']['number'];
        }
    } catch (Throwable $e) {
        error_log('Gateway wallet error: ' . $e->getMessage());
    }
}

/* =========================================================
   MESSAGE STATE
   ========================================================= */
$message = '';
$message_type = '';
$submitted_ok = false;
$verified_trx = '';

/* =========================================================
   DEPOSIT SUBMIT
   ========================================================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_deposit'])) {

    $posted_amount = (float)($_POST['amount'] ?? 0);
    $locked_amount = (float)($_POST['locked_amount'] ?? 0);

    $amount = $locked_amount > 0 ? $locked_amount : $posted_amount;

    $trx_id = trim($_POST['trx_id'] ?? '');
    $sender_mobile = trim($_POST['mobile'] ?? '');
    $posted_uid = (int)($_POST['uid'] ?? $auto_uid);

    $wantsBonus = isset($_POST['wants_bonus']) &&
                  $_POST['wants_bonus'] == '1';

    if (gatewayConfigLooksUnset()) {
        $message = 'Gateway API Key এবং Secret এখনো সেট করা হয়নি।';
        $message_type = 'danger';
    } elseif ($amount <= 0) {
        $message = 'সঠিক Amount দাও।';
        $message_type = 'danger';
    } elseif ($amount < 100) {
        $message = 'সর্বনিম্ন ৳100 Deposit করতে হবে।';
        $message_type = 'danger';
    } elseif ($trx_id === '' || strlen($trx_id) < 6) {
        $message = 'সঠিক Transaction ID দাও।';
        $message_type = 'danger';
    } elseif ($posted_uid <= 0) {
        $message = 'Account শনাক্ত করা যায়নি। App-এর ভেতর থেকে Deposit করো।';
        $message_type = 'danger';
    } else {
        $uid = $posted_uid;

        $userQ = mysqli_query(
            $conn,
            "SELECT id, mobile
             FROM shonu_subjects
             WHERE id = '$uid' AND status = '1'
             LIMIT 1"
        );

        $userRow = $userQ ? mysqli_fetch_assoc($userQ) : null;

        if (!$userRow) {
            $message = 'Account পাওয়া যায়নি।';
            $message_type = 'danger';
        } else {
            if ($wantsBonus) {
                $reVerifyDep = @mysqli_query(
                    $conn,
                    "SELECT id FROM thevani WHERE balakedara = '$uid' AND sthiti = 1 LIMIT 1"
                );
                $reVerifyBonus = @mysqli_query(
                    $conn,
                    "SELECT id FROM first_deposit_bonus_claims WHERE user_id = '$uid' LIMIT 1"
                );

                $reNoPrevDep = $reVerifyDep ? mysqli_num_rows($reVerifyDep) === 0 : true;
                $reNoPrevBonus = $reVerifyBonus ? mysqli_num_rows($reVerifyBonus) === 0 : true;

                if (!($reNoPrevDep && $reNoPrevBonus)) {
                    $wantsBonus = false;
                }
            }

            $limitBlocked = false;
            $limitQ = mysqli_query(
                $conn,
                "SELECT daily_deposit_limit, weekly_deposit_limit, monthly_deposit_limit
                 FROM responsible_gambling_settings WHERE user_id = '$uid' LIMIT 1"
            );
            $limitRow = $limitQ ? mysqli_fetch_assoc($limitQ) : null;

            if ($limitRow) {
                $periods = [
                    'daily_deposit_limit' => ['label' => 'দৈনিক', 'interval' => '1 DAY'],
                    'weekly_deposit_limit' => ['label' => 'সাপ্তাহিক', 'interval' => '7 DAY'],
                    'monthly_deposit_limit' => ['label' => 'মাসিক', 'interval' => '30 DAY'],
                ];

                foreach ($periods as $col => $info) {
                    if (!$limitBlocked && $limitRow[$col] !== null && (float)$limitRow[$col] > 0) {
                        $limitVal = (float)$limitRow[$col];
                        $sumQ = mysqli_query(
                            $conn,
                            "SELECT COALESCE(SUM(motta),0) AS total FROM thevani
                             WHERE balakedara = '$uid' AND dinankavannuracisi >= DATE_SUB(NOW(), INTERVAL {$info['interval']})"
                        );
                        $sumRow = $sumQ ? mysqli_fetch_assoc($sumQ) : null;
                        $alreadyDeposited = (float)($sumRow['total'] ?? 0);

                        if (($alreadyDeposited + $amount) > $limitVal) {
                            $limitBlocked = true;
                            $message = "তোমার সেট করা {$info['label']} Deposit-Limit ৳{$limitVal} পার হয়ে যাচ্ছে।";
                            $message_type = 'danger';
                        }
                    }
                }
            }

            if (!$limitBlocked) {
                $trxEsc = mysqli_real_escape_string($conn, $trx_id);
                $dupQ = mysqli_query($conn, "SELECT shonu FROM thevani WHERE ullekha = '$trxEsc' LIMIT 1");

                if ($dupQ && mysqli_num_rows($dupQ) > 0) {
                    $message = 'এই Transaction ID আগেই ব্যবহার করা হয়েছে।';
                    $message_type = 'danger';
                } else {
                    $poolIsAgent = false;
                    $poolId = null;

                    $selfQ = mysqli_query($conn, "SELECT code FROM shonu_subjects WHERE id = '$uid' LIMIT 1");
                    $selfRow = $selfQ ? mysqli_fetch_assoc($selfQ) : null;

                    if ($selfRow && !empty($selfRow['code'])) {
                        $codeEsc = mysqli_real_escape_string($conn, $selfRow['code']);
                        $refQ = mysqli_query($conn, "SELECT id FROM shonu_subjects WHERE owncode = '$codeEsc' LIMIT 1");
                        $refRow = $refQ ? mysqli_fetch_assoc($refQ) : null;

                        if ($refRow) {
                            $refId = (int)$refRow['id'];
                            $agentQ = mysqli_query($conn, "SELECT userid FROM tb_agent WHERE userid = '$refId' AND status = '1' LIMIT 1");
                            if ($agentQ && mysqli_num_rows($agentQ) > 0) {
                                $poolIsAgent = true;
                                $poolId = $refId;
                            }
                        }
                    }

                    if (!$poolIsAgent) {
                        $adminQ = mysqli_query($conn, "SELECT unohs FROM nirvahaka_shonu ORDER BY unohs ASC LIMIT 1");
                        $adminRow = $adminQ ? mysqli_fetch_assoc($adminQ) : null;
                        $poolId = $adminRow['unohs'] ?? null;
                    }

                    $poolBalance = 0;
                    if ($poolId !== null) {
                        $poolIdInt = (int)$poolId;
                        $balQ = mysqli_query(
                            $conn,
                            $poolIsAgent
                                ? "SELECT motta FROM shonu_kaichila WHERE balakedara = '$poolIdInt' LIMIT 1"
                                : "SELECT motta FROM nirvahaka_shonu WHERE unohs = '$poolIdInt' LIMIT 1"
                        );
                        $balRow = $balQ ? mysqli_fetch_assoc($balQ) : null;
                        $poolBalance = $balRow ? (float)$balRow['motta'] : 0;
                    }

                    if ($poolId === null) {
                        $message = 'Admin/Agent balance pool পাওয়া যায়নি।';
                        $message_type = 'danger';
                    } elseif ($poolBalance < $amount) {
                        $message = $poolIsAgent ? '⚠️ আপনার Agent-এর account balance অপর্যাপ্ত।' : '⚠️ Admin-এর account balance অপর্যাপ্ত।';
                        $message_type = 'danger';
                    } else {
                        try {
                            $gateway = new CV111GatewayClient(PG_BASE_URL, PG_API_KEY_ID, PG_API_SECRET);
                            $verify = $gateway->checkByTrxId($trx_id, $amount);

                            if (!empty($verify['found'])) {
                                $txData = $verify['transaction'] ?? [];
                                $txIdInGateway = $txData['id'] ?? null;

                                if (!$txIdInGateway) {
                                    $message = 'Gateway-তে Transaction ID পাওয়া যায়নি।';
                                    $message_type = 'danger';
                                } else {
                                    $claimedBy = "User#{$uid}";
                                    $claimRes = $gateway->claimPayment($txIdInGateway, $claimedBy);

                                    if (!empty($claimRes['claimed'])) {
                                        $finalBonusAmount = 0;
                                        if ($wantsBonus) {
                                            $finalBonusAmount = $amount * 1.00;
                                        }

                                        $totalAddAmount = $amount + $finalBonusAmount;

                                        mysqli_begin_transaction($conn);

                                        try {
                                            $upUser = mysqli_query(
                                                $conn,
                                                "UPDATE shonu_kaichila SET motta = motta + $totalAddAmount WHERE balakedara = '$uid'"
                                            );

                                            if ($poolIsAgent) {
                                                $upPool = mysqli_query(
                                                    $conn,
                                                    "UPDATE shonu_kaichila SET motta = motta - $amount WHERE balakedara = '$poolIdInt'"
                                                );
                                            } else {
                                                $upPool = mysqli_query(
                                                    $conn,
                                                    "UPDATE nirvahaka_shonu SET motta = motta - $amount WHERE unohs = '$poolIdInt'"
                                                );
                                            }

                                            $mobileEsc = mysqli_real_escape_string($conn, $sender_mobile);
                                            $insDep = mysqli_query(
                                                $conn,
                                                "INSERT INTO thevani (balakedara, kula, motta, mobila, ullekha, dinamka, dinankavannuracisi, sthiti)
                                                 VALUES ('$uid', 'bKash-Gateway', '$amount', '$mobileEsc', '$trxEsc', CURDATE(), NOW(), 1)"
                                            );

                                            if ($finalBonusAmount > 0) {
                                                @mysqli_query(
                                                    $conn,
                                                    "INSERT INTO first_deposit_bonus_claims (user_id, deposit_amount, bonus_amount, claimed_at)
                                                     VALUES ('$uid', '$amount', '$finalBonusAmount', NOW())"
                                                );
                                            }

                                            if ($upUser && $upPool && $insDep) {
                                                mysqli_commit($conn);
                                                $submitted_ok = true;
                                                $verified_trx = $trx_id;
                                                $message = 'আপনার Deposit সফল হয়েছে এবং Account Balance যোগ করা হয়েছে!';
                                                $message_type = 'success';
                                            } else {
                                                mysqli_rollback($conn);
                                                $message = 'Database Update ব্যর্থ হয়েছে। Admin-এর সাথে যোগাযোগ করুন।';
                                                $message_type = 'danger';
                                            }
                                        } catch (Throwable $ex) {
                                            mysqli_rollback($conn);
                                            $message = 'Error: ' . $ex->getMessage();
                                            $message_type = 'danger';
                                        }
                                    } else {
                                        $reason = $claimRes['reason'] ?? 'unknown';
                                        if ($reason === 'already_claimed') {
                                            $message = 'এই Transaction আগেই ক্লেইম করা হয়ে গেছে।';
                                        } else {
                                            $message = 'Payment Claim ব্যর্থ হয়েছে (' . e($reason) . ')।';
                                        }
                                        $message_type = 'danger';
                                    }
                                }
                            } else {
                                $reason = $verify['reason'] ?? 'not_found';
                                if ($reason === 'amount_mismatch') {
                                    $message = 'Transaction ID পাওয়া গেছে কিন্তু Amount মিলছে না।';
                                } elseif ($reason === 'already_claimed') {
                                    $message = 'এই Transaction ID আগেই ক্লেইম করা হয়ে গেছে।';
                                } else {
                                    $message = 'Transaction ID অথবা Amount সঠিক নয়।';
                                }
                                $message_type = 'danger';
                            }
                        } catch (Throwable $e) {
                            error_log('Gateway verify exception: ' . $e->getMessage());
                            $message = 'Gateway-এর সাথে সংযোগ স্থাপন করা যায়নি।';
                            $message_type = 'danger';
                        }
                    }
                }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>bKash Deposit</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-slate-900 text-white min-h-screen flex items-center justify-center p-4">
    <div class="max-w-md w-full bg-slate-800 rounded-2xl shadow-xl p-6 border border-slate-700">
        <div class="text-center mb-6">
            <span class="bg-pink-600 text-white font-bold px-4 py-1 rounded-full text-sm">bKash Deposit</span>
            <h2 class="text-2xl font-bold mt-2">বিকাশ পেমেন্ট</h2>
        </div>

        <?php if ($message): ?>
            <div class="mb-4 p-3 rounded text-sm text-center <?php echo $message_type === 'danger' ? 'bg-red-500/20 text-red-400 border border-red-500/30' : 'bg-green-500/20 text-green-400 border border-green-500/30'; ?>">
                <?php echo e($message); ?>
            </div>
        <?php endif; ?>

        <?php if (!$submitted_ok): ?>
            <div class="bg-slate-700/50 p-4 rounded-xl mb-6 text-center border border-slate-600">
                <p class="text-xs text-slate-400 mb-1">বিকাশ পার্সোনাল নম্বরে টাকা পাঠান:</p>
                <p class="text-2xl font-mono font-bold text-pink-400 select-all"><?php echo e($BKASH_NUMBER); ?></p>
            </div>

            <form method="POST" action="<?php echo e($_SERVER['REQUEST_URI']); ?>" class="space-y-4">
                <input type="hidden" name="uid" value="<?php echo e($auto_uid); ?>">
                <input type="hidden" name="locked_amount" value="<?php echo e($auto_amount); ?>">

                <div>
                    <label class="block text-xs text-slate-400 mb-1">অ্যামাউন্ট (BDT)</label>
                    <input type="number" step="any" name="amount" value="<?php echo $auto_amount > 0 ? e($auto_amount) : ''; ?>" <?php echo $auto_amount > 0 ? 'readonly' : ''; ?> required class="w-full bg-slate-900 border border-slate-700 rounded-lg p-3 text-white focus:outline-none focus:border-pink-500">
                </div>

                <div>
                    <label class="block text-xs text-slate-400 mb-1">আপনার বিকাশ মোবাইল নম্বর (ঐচ্ছিক)</label>
                    <input type="text" name="mobile" placeholder="017xxxxxxxx" class="w-full bg-slate-900 border border-slate-700 rounded-lg p-3 text-white focus:outline-none focus:border-pink-500">
                </div>

                <div>
                    <label class="block text-xs text-slate-400 mb-1">bKash TrxID (ট্রানজেকশন আইডি)</label>
                    <input type="text" name="trx_id" placeholder="Ex: 8N7A6D5C" required class="w-full bg-slate-900 border border-slate-700 rounded-lg p-3 text-white uppercase focus:outline-none focus:border-pink-500">
                </div>

                <?php if ($isFirstDepositEligible): ?>
                    <div class="flex items-center space-x-2 pt-2">
                        <input type="checkbox" name="wants_bonus" value="1" id="wants_bonus" <?php echo $auto_wants_bonus ? 'checked' : ''; ?> class="w-4 h-4 rounded text-pink-600 focus:ring-pink-500">
                        <label for="wants_bonus" class="text-sm text-pink-400 font-semibold">100% ফার্স্ট ডিপোজিট বোনাস নিন!</label>
                    </div>
                <?php endif; ?>

                <button type="submit" name="submit_deposit" class="w-full bg-pink-600 hover:bg-pink-700 text-white py-3 rounded-lg font-bold transition">পেমেন্ট নিশ্চিত করুন</button>
            </form>
        <?php else: ?>
            <div class="text-center space-y-4">
                <p class="text-sm text-slate-300">Transaction ID: <span class="font-mono font-bold text-pink-400"><?php echo e($verified_trx); ?></span></p>
                <a href="/" class="inline-block w-full bg-slate-700 hover:bg-slate-600 py-3 rounded-lg text-sm font-bold transition">মূল পেজে ফিরে যান</a>
            </div>
        <?php endif; ?>
    </div>
</body>
</html>