<?php
session_start();
require_once("db.php");

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $email = $_POST['email'];
    $amount = $_POST['amount'];
    $trxID = $_POST['trxID'];
    $bkashNumber = $_POST['bkashNumber'];
    $status = "pending";
    $paymentExecuteTime = date("Y-m-d H:i:s");

    try {
        // Insert payment data
        $sql = "INSERT INTO payment (email, customerMsisdn, trxID, amount, paymentExecuteTime, status) 
                VALUES (:email, :customerMsisdn, :trxID, :amount, :paymentExecuteTime, :status)";
        $query = $dbh->prepare($sql);
        $query->bindParam(':email', $email);
        $query->bindParam(':customerMsisdn', $bkashNumber);
        $query->bindParam(':trxID', $trxID);
        $query->bindParam(':amount', $amount);
        $query->bindParam(':paymentExecuteTime', $paymentExecuteTime);
        $query->bindParam(':status', $status);
        $query->execute();

        // Insert or update users table
        $sql = "INSERT INTO users (email, balance) VALUES (:email, 0) 
                ON DUPLICATE KEY UPDATE email = email"; // Default balance 0
        $query = $dbh->prepare($sql);
        $query->bindParam(':email', $email);
        $query->execute();

        // Send Telegram Notification
        $telegramBotToken = "7858422969:AAEkq4loejtoNAMKVsXLq4Af9UgX_II1SlA";  // Replace with your bot token
        $telegramChatID = "7950396783";  // Replace with your chat ID
        $message = "নতুন রিচার্জ রিকোয়েস্ট:\nইউজার: $email\nএমাউন্ট: $amount টাকা\nট্রানজেকশন আইডি: $trxID\nবিকাশ নম্বর: $bkashNumber";
        $telegramUrl = "https://api.telegram.org/bot$telegramBotToken/sendMessage?chat_id=$telegramChatID&text=" . urlencode($message);
        file_get_contents($telegramUrl); // Sends the message to Telegram

        echo "success"; // return success response
    } catch (Exception $e) {
        echo "error: " . $e->getMessage(); // return error response
    }
}
?>
