const express = require('express');
const router = express();
const multer = require('multer');
const fs = require('fs');
const path = require('path');
const upload = require('../helper/handleFileUpdate');



const {
    // getUserWalletTransactionHistory,
    updateMiniGamesSettings,
    getAllUsersBankDetails,
    subAdminListGridData,
    unApprovedUserListGridData,
    getMarketBidDetails,
    getSearchMarketBidDetails,
    // autoFundRequestListGridData,
    getManualFundRequests,
    getAutoFundRequests,
    acceptAutoFundRequest,
    rejectAutoFundRequest,
    deleteAutoFundRequest,
    getDashboardWithdrawReportDetails,
    loginCheck,
    forgotPassword,
    updatePassword,
    blockDataFunction,
    marketOpenCloseFunction,
    userListGridData,
    acceptFundRequest,
    rejectFundRequest,
    getMiniGamesList,
    creditTransactionTableGridData,
    debitTransactionTableGridData,
    userBidHistoryTableGridData,
    userWinningHistoryData,
    allowedBetting,
    changeLogoutStatus,
    addSubAdmin,
    addMaster,
    addBalanceUserWallet,
    withdrawBalanceUserWallet,
    changeSecurityPin,
    fundRequestListGridData,
    withdrawRequestListGridData,
    approveWithdrawRequest,
    rejectWithdrawRequest,
    bellNotificationList,
    ideaListGridData,
    addBellNotification,
    addAdminBankDetail,
    addAdminUpiDetail,
    addAdminUpiUpdateOtpCheck,
    addAppLink,
    addAdminFixValues_with_maintainence,
    addGameRates,
    lotteryNameListGridData,
    addLottery,
    deleteLottery,
    ticketHistoryListGridData,
    lotteryResultListLoadData,
    getLotteryListForResult,
    getDecleareLotteryData,
    saveLotteryData,
    decleareLotteryData,
    getLotteryWinnerList,
    gameNameListGridData,
    addUpdateGame,
    addOffDay,
    deleteGameName,
    getPredictWinnerList,
    checkOpenMarketResultDeclaration,
    starlineGameNameListGridData,
    addUpdateStarlineGame,
    editStarlineGame,
    addStarelineGameRates,
    starlineUserBidHistory,
    getStarlineBidHistoryData,
    exportOptionBidHistoryData,
    getDecleareStarlineGameData,
    saveOpenStarlineGameData,
    decleareOpenStarlineData,
    deleteOpenStarlineResultData,
    getOpenStarlineWinnerList,
    // getOpenStarlineDeclaredWinnerList,
    getStarlineSellReport,
    getStarlineWinningReport,
    starlineResultHistoryListGridData,
    starlineResultHistoryListLoadData,
    getStarlineWinnerList,
    completeStarlineBidRevert,
    galidisswarGameNameListGridData,
    exportOptionGalidisswarBidHistoryData,
    updateGaliDissawarBid,
    getDecleareGalidisswarGameData,
    getOpenData,
    getCloseData,
    saveGalidisswarGameData,
    decleareGalidisswarData,
    deleteOpenGalidisswarResultData,
    getGalidisswarSellReport,
    getGalidisswarWinningReport,
    fetchGalidissawarGameResultHistory,
    revertGalidissawarBids,
    galidisswarResultHistoryListGridData,
    galidisswarResultHistoryListLoadData,
    getGalidisswarWinnerList,
    getBidRevertData,
    refundAmount,
    addGamesTime,
    changeGameTime,
    tinymceUploadImage,
    addHowToPlayData,
    //sliderImagesListGridData, // slider images
    getSliderImages,
    addSliderImage,
    deleteSliderImage,
    qrcodeImagesListGridData,
    addQrcodeImage,
    deleteQrcodeImage,
    getBidHistoryData,
    getBidArchiveHistoryData,  //archive bid history
    updateBid,
    mainMarketReport,
    showDigit,
    getWinningHistoryData,
    resultHistoryListGridData,
    resultHistoryListLoadData,
    getDecleareGameData,
    saveOpenData,
    decleareOpenData_Result,
    decleareCloseData,
    saveCloseData,
    openResultNotificationContinously,

    deleteOpenCloseResultData_Result, // deleteopenresultwinner
    // deleteOpenResultData_Result, // deleteopenresultwinner
    deleteOpenResultData_Result, // deleteopenresultwinner
    deleteCloseResultData_Result, // deletecloseresultwinner


    revertBidCompletely,
    revertOpenBids,
    revertCloseBids,



    // sub menu bid revert
    revertMultipleBids,
    revertSingleBid,
    editOpenResultData,

    editCloseResultData,
    getOpenWinnerList_starline,
    getCloseWinnerList,
    // deleteCloseResultData, // deletecloseresultwinner
    addContactSettings,
    getContactSettings,
    usersQueryListGridData,
    tipsListGridData,
    addTips,
    userSendNotification,
    getCustomerSellReport,
    getAllWalletTransactionHistory,
    quesListGridData,
    getUserData,
    getUserSearch,
    submitRouletteGame,
    rouletteGameNameListGridData,
    getRouletteBidHistoryData,
    exportOptionRouletteBidHistoryData,
    rouletteResultHistoryListGridData,
    getRouletteWinningReport,
    getAutoDepositeHistory,
    viewWithdrawRequest,
    getMainSettings,
    getHowToPlayData,
    isAlreadyLogin,
    updateSubAdmin,
    deleteSubAdmin,
    deleteNotice,
    updateNotice,
    gameNameListGridDataUpdate,
    getGameRates,
    getGameList,
    getUserProfile,
    userReferralTableGridData,
    userAddFundReqTableGridData,
    userWithdrawFundReqTableGridData,
    userBitHistoryDataReqTableGridData,
    userWalletTransactionHistoryDataReqTableGridData,
    getWalletTransactionArchiveHistory,
    userWinningHistoryDataReqTableGridData,
    adminLogout,
    updateBid_with_property,
    getTransferReport,
    getWithdrawReportDetails,
    deleteStarlineGameName,
    getStarlineGameRates,
    addUpdateGalidisswarGame,
    deleteGalidisswarGameName,
    getGalidisswarGameRates,
    addGalidisswarGameRates,
    getStarlineGameList,
    getGalidisswarGameList,
    getGalidisswarBidHistoryData,
    getOpenWinnerList,
    getDashboardTopData,
    getBidWinningReportDetails,
    getBidReportList,
    getWinningReportDetails,
    getGalidisswarWinnerList_declare,
    getSendNotification_users_date,
    sendFBNotification,
    getStarlineBidRevertData,
    getgalidisswarBidRevertData,


    starlineDeleteBids,
    starlineDeleteSingleBid,
    starlineDeleteMultipleBids,


    galidisswarRefundAmount,
    revertGalidisswarMultipleBids,
    revertGalidisswarSingleBid,
    ideasListGridData,
    deleteIdea,
    changeWingoResult,
    userUpdateWallet,

    // main game bookie corner cutting group data
    cuttingGroupData, //Neon
    getBidDetails, //Neon

    // jackpot game bookie corner cutting group data
    galiDissawarCuttingGroupData, //Neon
    getGaliDissawarBidDetails, //Neon

    // starline game bookie corner cutting group data
    starlineCuttingGroupData, //Neon
    getStarlineBidDetails, //Neon

    addManualPaymentDetails, //Neon
    getManualPaymentDetails, //Neon
    deleteManualPaymentDetails, //Neon
    createAppUpdate, //Neon
    getAppUpdates, //Neon
    toggleAppUpdateStatus, //Neon
    deleteAppUpdate, //Neon
    getLatestAppUpdate, //Neon
    moveWithdrawToProcessing, //Neon
    userTotalAddFundAndWithdrawFundAmount, //Neon
    getFixValue,    //Neon
    reprocessWithdrawRequest,    //Neon
    fetchOpenCloseGameResultHistory,    //Neon
    OcCuttingData,    //Neon
    getContentsRules,    //Neon
    updateContentsRules,    //Neon


    // getPaymentGatewaySettings,   //Neon
    // updatePaymentGatewaySettings,   //Neon

    getDollarBazarSettings,   //Neon
    updateDollarBazarSettings,   //Neon
    getProtonPaySettings,   //Neon
    updateProtonPaySettings,   //Neon



    // getActiveGatewayForAmount,   //Neon
    // testPaymentGateway,   //Neon
    // testDollarBazarConnection,   //Neon

    processDeposit,   //Neon
    // processWithGateway,   //Neon

    // getPGTransactions,   //Neon
    // refreshPGTransaction,   //Neon
    checkPGTransactionStatus,   //Neon
    checkDepositStatus,
    // refundToWallet,
    // deductFromWallet,
    // creditUserWallet,
    rejectWithdrawal,
    approveWithdrawal,
    requestWithdrawal,
    handleWebhook,
    // generateTransactionId



} = require('../controllers/adminController');


// Configure multer for APK files
const apkStorage = multer.diskStorage({
    destination: function (req, file, cb) {
        const uploadsDir = path.join(__dirname, '../uploads/app-updates');
        if (!fs.existsSync(uploadsDir)) {
            fs.mkdirSync(uploadsDir, { recursive: true });
        }
        cb(null, uploadsDir);
    },
    filename: function (req, file, cb) {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
        cb(null, 'app-v' + req.body.version + '-' + uniqueSuffix + '.apk');
    }
});

// Configure multer for slider images
const sliderStorage = multer.diskStorage({
    destination: function (req, file, cb) {
        const uploadsDir = path.join(__dirname, '../uploads/slider-images');
        if (!fs.existsSync(uploadsDir)) {
            fs.mkdirSync(uploadsDir, { recursive: true });
        }
        cb(null, uploadsDir);
    },
    filename: function (req, file, cb) {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
        cb(null, 'slider-' + uniqueSuffix + path.extname(file.originalname));
    }
});


const apkFileFilter = (req, file, cb) => {
    if (file.mimetype === 'application/vnd.android.package-archive') {
        cb(null, true);
    } else {
        cb(new Error('Only APK files are allowed'), false);
    }
};

const sliderFileFilter = (req, file, cb) => {
    if (file.mimetype.startsWith('image/')) {
        cb(null, true);
    } else {
        cb(new Error('Only image files are allowed'), false);
    }
};


// apk file
const uploadAPK = multer({
    storage: apkStorage,
    limits: {
        fileSize: 100 * 1024 * 1024 // 100MB limit
    },
    fileFilter: apkFileFilter
});



// slider
const uploadSlider = multer({
    storage: sliderStorage,
    limits: {
        fileSize: 5 * 1024 * 1024 // 5MB limit
    },
    fileFilter: sliderFileFilter
});



const qrCodeStorage = multer.diskStorage({
    destination: function (req, file, cb) {
        const uploadsDir = path.join(__dirname, '../uploads/qrcode-images');
        if (!fs.existsSync(uploadsDir)) {
            fs.mkdirSync(uploadsDir, { recursive: true });
        }
        cb(null, uploadsDir);
    },
    filename: function (req, file, cb) {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
        cb(null, 'qrcode-' + uniqueSuffix + path.extname(file.originalname));
    }
});

const qrCodeFileFilter = (req, file, cb) => {
    if (file.mimetype.startsWith('image/')) {
        cb(null, true);
    } else {
        cb(new Error('Only image files are allowed'), false);
    }
};

const uploadQrCode = multer({
    storage: qrCodeStorage,
    limits: { fileSize: 5 * 1024 * 1024 }, // 5MB
    fileFilter: qrCodeFileFilter
});






// Configure multer for withdrawal approval slips
const withdrawApprovalStorage = multer.diskStorage({
    destination: function (req, file, cb) {
        const uploadsDir = path.join(__dirname, '../uploads/withdrawal-approvals');
        if (!fs.existsSync(uploadsDir)) {
            fs.mkdirSync(uploadsDir, { recursive: true });
        }
        cb(null, uploadsDir);
    },
    filename: function (req, file, cb) {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
        cb(null, 'withdrawal-approval-' + uniqueSuffix + path.extname(file.originalname));
    }
});

const withdrawApprovalFileFilter = (req, file, cb) => {
    if (file.mimetype.startsWith('image/')) {
        cb(null, true);
    } else {
        cb(new Error('Only image files are allowed for withdrawal approvals'), false);
    }
};

const uploadWithdrawApproval = multer({
    storage: withdrawApprovalStorage,
    limits: {
        fileSize: 5 * 1024 * 1024 // 5MB limit
    },
    fileFilter: withdrawApprovalFileFilter
});



router.post('/admin/create-app-update', uploadAPK.single('apkFile'), createAppUpdate);
// router.post('/admin/add-qrcode-image', uploadQrCode.single('qrCode'), addQrcodeImage);
router.post("/admin/add-qrcode-image", (req, res) => {
    uploadQrCode.single("qrCode")(req, res, (err) => {
        if (err instanceof multer.MulterError) {
            if (err.code === "LIMIT_FILE_SIZE") {
                return res.status(400).json({
                    success: false,
                    msg: "File size exceeds 5MB limit.",
                });
            }
            return res.status(400).json({
                success: false,
                msg: "Multer error: " + err.message,
            });
        } else if (err) {
            return res.status(400).json({
                success: false,
                msg: err.message || "Unknown file upload error.",
            });
        }

        // ✅ Only call controller if no error
        addQrcodeImage(req, res);
    });
});

router.post('/admin/approve-withdraw-request', uploadWithdrawApproval.single('file'), approveWithdrawRequest); // approve withdrawal request by admin
router.post('/admin/reprocess-withdraw-request', uploadWithdrawApproval.single('file'), reprocessWithdrawRequest);

router.post("/admin/move-withdraw-processing", moveWithdrawToProcessing);


router.post('/tinymce-upload-image', upload.single('file'), tinymceUploadImage);
router.post('/admin/add-slider-image', uploadSlider.single('sliderImage'), addSliderImage);

// get methods
router.get('/admin', isAlreadyLogin);  // adminCheckApi
router.get('/admin/view-withdraw-request/:withdrawDB_id', viewWithdrawRequest);
router.get('/admin/get-main-settings', getMainSettings);
router.get('/admin/get-contact-settings', getContactSettings); //admin contact details
router.get('/admin/get-how-to-play-data', getHowToPlayData);
router.get('/admin/get-send-notification-users-data', getSendNotification_users_date);
router.get('/admin/game-name-list-grid-data-update/:gameDB_id', gameNameListGridDataUpdate);
router.get('/admin/get-game-rates', getGameRates);
router.get('/admin/get-game-list', getGameList);
router.get('/admin/get-user-profile/:userDB_id', getUserProfile);
router.get('/admin/logout', adminLogout);
router.get('/admin/get-starline-game-rates', getStarlineGameRates);
router.get('/admin/get-starline-game-list', getStarlineGameList);
router.get('/admin/get-galidisswar-game-rates', getGalidisswarGameRates);
router.get('/admin/get-galidisswar-game-list', getGalidisswarGameList);
router.get('/admin/get-mini-games-list', getMiniGamesList);
router.get('/admin/get-dashboard-top-data', getDashboardTopData); // dashboardApi
router.get('/admin/delete-idea/:ideaDB_id', deleteIdea);








router.get('/admin/get_content_game_rules', getContentsRules);
router.post('/admin/update_content_game_rule', updateContentsRules);










// #region Neon

// Debug route to check file records
router.get('/admin/debug-files', async (req, res) => {
    try {
        const files = await file_module.find().sort({ uploadedAt: -1 }).limit(10);
        const filesWithExistence = await Promise.all(
            files.map(async (file) => {
                const exists = file.path ? fs.existsSync(file.path) : false;
                return {
                    _id: file._id,
                    filename: file.filename,
                    path: file.path,
                    exists: exists,
                    size: file.size,
                    uploadedAt: file.uploadedAt
                };
            })
        );

        res.json({ success: true, files: filesWithExistence });
    } catch (error) {
        console.error('Debug error:', error);
        res.status(500).json({ success: false, error: error.message });
    }
});


// Serve APK files for download
router.get('/downloads/app-updates/:filename', (req, res) => {
    const filename = req.params.filename;
    // const filePath = path.join(__dirname, 'uploads/app-updates', filename);
    const filePath = path.join(__dirname, '../uploads/app-updates', filename);
    if (fs.existsSync(filePath)) {
        res.download(filePath, filename, (err) => {
            if (err) {
                console.error('Error downloading file:', err);
                res.status(500).json({ success: false, msg: 'Error downloading file' });
            }
        });
    } else {
        res.status(404).json({ success: false, msg: 'File not found' });
    }
});






router.post('/admin/loginCheck', loginCheck);
router.post('/admin/change-password', updatePassword);


router.get('/admin/get-app-updates', getAppUpdates);
router.post('/admin/toggle-app-update-status', toggleAppUpdateStatus);
router.post('/admin/delete-app-update', deleteAppUpdate);
router.get('/admin/get-latest-app-update', getLatestAppUpdate);





// #endregion Neon



router.post('/admin/un-approved-user-list-grid-data', unApprovedUserListGridData);
router.post('/admin/block-data-function', blockDataFunction);
// router.post('/admin/auto-fund-request-list-grid-data', autoFundRequestListGridData);


// In your routes file
router.post('/admin/manual-fund-request-list', getManualFundRequests);
router.post('/admin/auto-fund-request-list', getAutoFundRequests);



router.post('/admin/accept-auto-fund-request', acceptAutoFundRequest); // accept add fund manual
router.post('/admin/reject-auto-fund-request', rejectAutoFundRequest);
router.post('/admin/delete-auto-fund-request', deleteAutoFundRequest);
router.post('/admin/get-dashboard-withdraw-report-details', getDashboardWithdrawReportDetails); // dashboard withdraw report details
router.post('/admin/reject-withdraw-request', rejectWithdrawRequest);
router.post('/admin/add-app-link', addAppLink);
router.post('/admin/add-admin-upi-detail', addAdminUpiDetail);


router.post('/admin/add-admin-fix-values-with-maintainence', addAdminFixValues_with_maintainence);
router.get('/admin/getFixValue', getFixValue);  // add admin fix values


router.post('/admin/add-contact-settings', addContactSettings);  // add contact settings admin
// router.post('/admin/slider-images-list-grid-data', sliderImagesListGridData);
router.get('/admin/get-slider-images', getSliderImages);
// Use the same field name consistently
router.post('/admin/delete-slider-image', deleteSliderImage);
router.post('/admin/add-how-to-play-data', addHowToPlayData); // add how to play admin
router.post('/admin/sub-admin-list-grid-data', subAdminListGridData);
router.post('/admin/add-sub-admin', addSubAdmin);
router.post('/admin/update-sub-admin/:adminDB_id', updateSubAdmin);
router.post('/admin/delete-sub-admin', deleteSubAdmin);
router.post('/admin/bell-notification-list', bellNotificationList);
router.post('/admin/add-bell-notification', addBellNotification); // addBellNotification
router.post('/admin/update-notice/:noticeDB_id', updateNotice);
router.post('/admin/delete-notice', deleteNotice);



// router.post("/admin/send-notification", sendFBNotification);
// router.post("/admin/send-notification", async (req, res) => {
//     const { title, message } = req.body;

//     // This single line handles everything beautifully
//     await sendFBNotification(title, message, '', { res });
// });
router.post("/admin/send-notification", async (req, res) => {
    const { title, message: body } = req.body;

    try {
        const result = await sendFBNotification(title, body, null, { res });

        // If it was an API call, the function already sent the response
        // So we just return to prevent double response
        return;
    } catch (err) {
        // In case something goes wrong and function didn't handle res
        if (!res.headersSent) {
            return res.status(500).json({ success: false, error: err.message });
        }
    }
});




router.post('/admin/game-name-list-grid-data', gameNameListGridData);
router.post('/admin/add-off-day', addOffDay);
router.post('/admin/add-update-game', addUpdateGame);
router.post('/admin/delete-game-name', deleteGameName);
router.post('/admin/add-game-rates', addGameRates);
router.post('/admin/user-list-grid-data', userListGridData);
router.post('/admin/user-update-wallet', userUpdateWallet);
router.post('/admin/add-balance-user-wallet', addBalanceUserWallet); // add balance to user wallet
router.post('/admin/get-bid-revert-data', getBidRevertData);
router.post('/admin/get-starline-bid-revert-data', getStarlineBidRevertData);
router.post('/admin/get-galidisswar-bid-revert-data', getgalidisswarBidRevertData);
router.post('/admin/user-referral-table-grid-data/:userDB_id', userReferralTableGridData);
router.post('/admin/user-add-fund-req-table-grid-data/:userDB_id', userAddFundReqTableGridData);
// Add this route to your backend
// router.post('/admin/user-wallet-transaction-history/:userDB_id', getUserWalletTransactionHistory); //New Route for wallet history to calculate the total add fund in user account by user req and admin

router.post('/admin/user-withdraw-fund-req-table-grid-data/:userDB_id', userWithdrawFundReqTableGridData);
router.post('/admin/user-bid-history-data-table-grid-data/:userDB_id', userBitHistoryDataReqTableGridData);
router.post('/admin/user-wallet-transaction-history-data-table-grid-data/:userDB_id', userWalletTransactionHistoryDataReqTableGridData);
// Wallet transaction archive routes
router.post('/admin/get-wallet-transaction-archive-history', getWalletTransactionArchiveHistory);


router.post('/admin/user-winning-history-report-table-grid-data/:userDB_id', userWinningHistoryDataReqTableGridData);
router.post('/admin/change-user-security-pin', changeSecurityPin);
router.post('/admin/withdraw-balance-user-wallet', withdrawBalanceUserWallet);
router.post('/admin/reject-fund-request', rejectFundRequest);
router.post('/admin/refund-amount', refundAmount);


// Original endpoint (for backward compatibility)
router.post('/admin/starline-refund-amount', starlineDeleteBids);

// New endpoints for better clarity
router.post('/admin/starline-revert-single-bid', starlineDeleteSingleBid);
router.post('/admin/starline-revert-multiple-bids', starlineDeleteMultipleBids);




router.post('/admin/galidisswar-refund-amount', galidisswarRefundAmount);
router.post('/admin/galidisswar-revert-single-bid', revertGalidisswarSingleBid);
router.post('/admin/galidisswar-revert-multiple-bids', revertGalidisswarMultipleBids);

router.post('/admin/get-predict-winner-list', getPredictWinnerList);
router.post('/admin/update-bid-digit', updateBid);
router.post('/admin/get-bid-history-data', getBidHistoryData);
router.post('/admin/get-bid-archive-history-data', getBidArchiveHistoryData);
router.post('/admin/update-bid-with-property-digit', updateBid_with_property);
router.post('/admin/get-customer-sell-report', getCustomerSellReport);
router.post('/admin/get-transfer-report', getTransferReport);
router.post('/admin/get-withdraw-report-details', getWithdrawReportDetails); // withdrawReport
router.post('/admin/get-auto-deposite-history', getAutoDepositeHistory);

router.post('/admin/save-open-data', saveOpenData); // save game result pana for future

router.post('/admin/starline-game-name-list-grid-data', starlineGameNameListGridData);
router.post('/admin/add-update-starline-game', addUpdateStarlineGame);
router.post('/admin/delete-starline-game-name', deleteStarlineGameName);
router.post('/admin/add-starline-game-rates', addStarelineGameRates);
router.post('/admin/galidisswar-game-name-list-grid-data', galidisswarGameNameListGridData);
router.post('/admin/add-update-galidisswar-game', addUpdateGalidisswarGame);
router.post('/admin/delete-galidisswar-game-name', deleteGalidisswarGameName);
router.post('/admin/add-galidisswar-game-rates', addGalidisswarGameRates);
router.post('/admin/get-starline-bid-history-data', getStarlineBidHistoryData); // star line bid history data
router.post('/admin/get-galidisswar-bid-history-data', getGalidisswarBidHistoryData);

router.post('/admin/get-decleare-game-data', getDecleareGameData); // main game fetch saved result data

router.post('/admin/result-history-list-load-data', resultHistoryListLoadData);


// game result section bid result delete and bid revert
// router.post('/admin/delete-open-close-result-data', deleteOpenCloseResultData_Result); // game result section result delete
// router.post('/admin/revert-bid-completely', revertBidCompletely);  // game reslut section bid revert


// Delete result routes // mainResultDelete
router.post('/admin/delete-open-close-result-data', deleteOpenCloseResultData_Result); //main game delete Both sessions result
// router.post('/admin/delete-open-result-data', deleteOpenResultData_Result); // main game delete Open session result only
router.post('/admin/delete-close-result-data', deleteCloseResultData_Result); // main game delete Close session result only

// mainBidRevert // mainResultRevert routes
router.post('/admin/revert-bid-completely', revertBidCompletely); // main game Both sessions complete bid revert
router.post('/admin/revert-open-bids', revertOpenBids); // main game Open session complete bid revert
router.post('/admin/revert-close-bids', revertCloseBids); // main game Close session complete bid revert

// mainBidRevert     //main games bid revert sub menu for only revret the placed bid
router.post('/admin/revert-single-bid', revertSingleBid); // main game separate bid revert
router.post('/admin/revert-multiple-bids', revertMultipleBids); // main game separate multi select bid revert

//mainResultDeclare
router.post('/admin/decleare-open-data', decleareOpenData_Result);  // main game open result declare
router.post('/admin/decleare-close-data', decleareCloseData);  // main game close result declare
//mainWinnerList
router.post('/admin/get-open-winner-list', getOpenWinnerList); // show expected winner list according to the saved result value and total bid and win amount
router.post('/admin/get-close-winner-list', getCloseWinnerList);  // show expected winner list according to the saved result value and total bid and win amount

// mainResultHistory to show winner list
router.post("/admin/fetch-open-close-game-result-history", fetchOpenCloseGameResultHistory)


// router.post('/admin/delete-open-result-data', deleteOpenResultData_Result);
// router.post('/admin/delete-close-result-data', deleteCloseResultData);
router.post('/admin/edit-open-result-data', editOpenResultData);
router.post('/admin/edit-close-result-data', editCloseResultData);
router.post('/admin/get-galidisswar-sell-report', getGalidisswarSellReport);
router.post('/admin/get-starline-sell-report', getStarlineSellReport);


router.post('/admin/get-starline-winner-list', getStarlineWinnerList); //star line winning predication
router.post('/admin/complete-starline-bid-revert', completeStarlineBidRevert); // starline complete bid revert after result declare
router.post('/admin/get-galidisswar-winner-list', getGalidisswarWinnerList);
router.post('/admin/get-search-market-bid-details', getSearchMarketBidDetails);
router.post('/admin/get-market-bid-details', getMarketBidDetails);
router.post('/admin/starline-result-history-list-load-data', starlineResultHistoryListLoadData);  // starline game result history data list
router.post('/admin/get-decleare-starline-game-data', getDecleareStarlineGameData);
router.post('/admin/save-open-starline-game-data', saveOpenStarlineGameData); // save starline game result



router.post('/admin/get-open-starline-winner-list', getOpenStarlineWinnerList);  // starline show winner history list before result declare
// router.post('/admin/get-open-starline-winner-list-after-result', getOpenStarlineDeclaredWinnerList);  // starline show winner history list after result declare


router.post('/admin/decleare-open-starline-data', decleareOpenStarlineData); // starline result declare
router.post('/admin/galidisswar-result-history-list-load-data', galidisswarResultHistoryListLoadData);
router.post('/admin/get-decleare-galidisswar-game-data', getDecleareGalidisswarGameData);
router.post('/admin/save-galidisswar-game-data', saveGalidisswarGameData);
router.post('/admin/get-galidisswar-winner-list-declare', getGalidisswarWinnerList_declare);
router.post('/admin/decleare-galidisswar-data', decleareGalidisswarData);// jackpot result declare  
router.post('/admin/starline-result-history-list-grid-data', starlineResultHistoryListGridData);
router.post('/admin/get-starline-winning-report', getStarlineWinningReport);
router.post('/admin/get-galidisswar-winning-report', getGalidisswarWinningReport);
router.post('/admin/fetch-galidissawar-game-result-history', fetchGalidissawarGameResultHistory);
router.post('/admin/revert-galidissawar-bids', revertGalidissawarBids);


// 
router.post('/admin/get-winning-history-data', getWinningHistoryData); // winning history data

router.post('/admin/get-bid-winning-report-details', getBidWinningReportDetails);
router.post('/admin/get-bid-report-list', getBidReportList);
router.post('/admin/get-winning-report-details', getWinningReportDetails);  // market bid/win report
router.get('/admin/qrcode-images-list-grid-data', qrcodeImagesListGridData); // qr list
router.post('/admin/delete-qrcode-image', deleteQrcodeImage);
router.post('/admin/galidisswar-result-history-list-grid-data', galidisswarResultHistoryListGridData);
router.post('/admin/ideas-list-grid-data', ideasListGridData);
router.post('/admin/get-all-wallet-transaction-history', getAllWalletTransactionHistory);
router.post('/admin/get-all-user-bank-details', getAllUsersBankDetails);
router.post('/admin/update-mini-game-settings', updateMiniGamesSettings)



// Neon
router.post('/admin/bookie/cutting-group-data', cuttingGroupData); //main game bookie corner group data
router.post('/admin/bookie/bid-details', getBidDetails); // main game bookie corner group data view bid api
router.post('/admin/bookie/oc-cutting-data', OcCuttingData);


// Gali Dissawar Routes
router.post('/admin/bookie/galidisswar-cutting-group-data', galiDissawarCuttingGroupData);
router.post('/admin/bookie/galidisswar-bid-details', getGaliDissawarBidDetails);

// Starline Routes
router.post('/admin/bookie/starline-cutting-group-data', starlineCuttingGroupData);
router.post('/admin/bookie/starline-bid-details', getStarlineBidDetails);


router.get('/admin/list_manual-payment-details', getManualPaymentDetails);
router.post('/admin/delete-manual-payment-details', deleteManualPaymentDetails);
// router.post('/admin/user- total-transaction-summary', userTotalAddFundAndWithdrawFundAmount);
// Keep the original API endpoint for external calls
router.post('/admin/user-total-transaction-summary', async (req, res) => {
    try {
        const { userDB_id, accessing } = req.body;

        // Add your authentication/authorization logic here if needed
        // if (!accessing || !hasPermission(accessing, '7.1')) {
        //     return res.status(403).json({ success: false, msg: 'Access denied' });
        // }

        const result = await userTotalAddFundAndWithdrawFundAmount(userDB_id);

        if (result.success) {
            res.json(result);
        } else {
            res.status(500).json(result);
        }
    } catch (error) {
        console.error('Error in user-total-transaction-summary API:', error);
        res.status(500).json({
            success: false,
            msg: 'Server error'
        });
    }
});


// Neon

//admin deshboard for wingo
router.post('/admin/change-wingo-result', changeWingoResult);





// Routes
// router.get('/admin/get-payment-gateway-settings', getPaymentGatewaySettings);
// router.post('/admin/update-payment-gateway-settings', updatePaymentGatewaySettings);



// Dollar Bazar Routes
router.get('/admin/get-dollar-bazar-settings', getDollarBazarSettings);
router.post('/admin/update-dollar-bazar-settings', updateDollarBazarSettings);
// router.post('/test-dollar-bazar-connection', testDollarBazarConnection);

// Proton Pay Routes
router.get('/admin/get-proton-pay-settings', getProtonPaySettings);
router.post('/admin/update-proton-pay-settings', updateProtonPaySettings);
// router.post('/test-proton-pay-connection', testProtonPayConnection);






// router.post('/admin/test-payment-gateway', testPaymentGateway); // test payment gateway details is valid or not
router.post('/admin/process-deposit', processDeposit);


// // Routes
// router.get('/admin/get-pg-transactions', getPGTransactions);
// router.post('/admin/refresh-pg-transaction', refreshPGTransaction);

// User Routes (Mobile App)
router.get('/api-process-deposit', processDeposit);
router.get('/api-check-deposit-status/:transactionId', checkDepositStatus);
router.post('/api-/request-withdrawal', requestWithdrawal);

// Admin Routes
router.post('/admin/approve-withdrawal', approveWithdrawal);
router.post('/admin/reject-withdrawal', rejectWithdrawal);

// Webhook Route (No authentication - called by payment gateway)
router.post('/payment/webhook/dollar-bazar', handleWebhook);

// Existing admin routes
// router.get('/admin/get-pg-transactions', getPGTransactions);
// router.post('/admin/refresh-pg-transaction', refreshPGTransaction);
// router.get('/admin/get-payment-gateway-settings', getPaymentGatewaySettings);
// router.post('/admin/update-payment-gateway-settings', updatePaymentGatewaySettings);
// router.post('/admin/test-payment-gateway', testPaymentGateway);















//#region Use Less
router.post('/delete-data', (req, res) => {
    res.send("controller not available")
});
router.post('/credit-transaction-table-grid-data', creditTransactionTableGridData);
router.post('/debit-transaction-table-grid-data', debitTransactionTableGridData);
router.post('/user-bid-history-table-grid-data', userBidHistoryTableGridData);
router.post('/forgot-password', forgotPassword);

router.post('/market-open-close-function', marketOpenCloseFunction);
router.post('/accept-fund-request', acceptFundRequest);
router.post('/user-winning-history-data', userWinningHistoryData);
router.post('/allowed-betting', allowedBetting);
router.post('/change-logout-status', changeLogoutStatus);
router.post('/add-master', addMaster);
router.post('/fund-request-list-grid-data', fundRequestListGridData);
router.post('/withdraw-request-list-grid-data', withdrawRequestListGridData);
router.post('/idea-list-grid-data', ideaListGridData);
router.post('/add-admin-bank-detail', addAdminBankDetail);
router.post('/add-admin-upi-update-otp-check', addAdminUpiUpdateOtpCheck);
router.post('/lottery-name-list-grid-data', lotteryNameListGridData);
router.post('/add-lottery', addLottery);
router.post('/delete-lottery', deleteLottery);
router.post('/ticket-history-list-grid-data', ticketHistoryListGridData);
router.post('/lottery-result-list-load-data', lotteryResultListLoadData);
router.post('/get-lottery-list-for-result', getLotteryListForResult);
router.post('/get-decleare-lottery-data', getDecleareLotteryData);
router.post('/save-lottery-data', saveLotteryData);
router.post('/decleare-lottery-data', decleareLotteryData);
router.post('/get-lottery-winner-list', getLotteryWinnerList);
router.post('/check-open-market-result-declaration', checkOpenMarketResultDeclaration);
router.post('/edit-starline-game/:gameDB_id', editStarlineGame);
router.post('/starline-user-bid-history', starlineUserBidHistory);
router.post('/export-option-starline-bid-history-data', exportOptionBidHistoryData);
// router.post('/delete-open-starline-result-data', deleteOpenStarlineResultData);
router.post('/admin/delete-open-starline-result-data', deleteOpenStarlineResultData);  // delete starline game result and revert the winning amount
router.post('/export-option-galidisswar-bid-history-data', exportOptionGalidisswarBidHistoryData);
router.post('/update-galidissawar-bid', updateGaliDissawarBid);
router.post('/get-open-data', getOpenData);
router.post('/get-close-data', getCloseData);
router.post('/admin/delete-close-galidisswar-result-data', deleteOpenGalidisswarResultData); //jackpotresultdelete
router.post('/add-games-time', addGamesTime);
router.post('/change-game-time', changeGameTime);
router.post('/export-option-bid-history-data', exportOptionBidHistoryData);
router.post('/main-market-report', mainMarketReport);
router.post('/show-digit', showDigit);
router.post('/result-history-list-grid-data', resultHistoryListGridData);
router.post('/save-close-data', saveCloseData);
router.post('/open-result-notification-continusly', openResultNotificationContinously);
router.post('/get-open-winner-stareline-list', getOpenWinnerList_starline);
router.post('/users-querys-list-grid-data', usersQueryListGridData);
router.post('/tips-list-grid-data', tipsListGridData);
router.post('/add-tips', addTips);
router.post('/user-send-notification', userSendNotification);
router.post('/ques-list-grid-data', quesListGridData);
router.post('/get-user-data', getUserData);
router.post('/get-user-search', getUserSearch);
router.post('/submit-roulette-game', submitRouletteGame);
router.post('/roulette-game-name-list-grid-data', rouletteGameNameListGridData);
router.post('/get-roulette-bid-history-data', getRouletteBidHistoryData);
router.post('/export-option-roulette-bid-history-data', exportOptionRouletteBidHistoryData);
router.post('/roulette-result-history-list-grid-data', rouletteResultHistoryListGridData);
router.post('/get-roulette-winning-report', getRouletteWinningReport);
// #endregion Use Less


module.exports = router;