const express = require('express');
const router = express();
const multer = require('multer');
const fs = require('fs');
const path = require('path');

require("dotenv").config();



const upload = require('../helper/handleFileUpdate');


const {
    // createDepositRequest,
    // checkDepositStatus,
    // initiateDollarBazarPayment
} = require("../controllers/payment.controller");


const { dollarbazarWebhook, dollarbazarPayoutWebhook, protonpayWebhook, protonPayPayoutWebhook } = require("../controllers/webhook.controller");




const {
    getPublicImages,
    apiGetAppKey,
    apiCheckMobile,
    apiCheckUsername,
    apiOtpSent,
    apiResendOtp,
    apiUserRegistration,
    apiUserStatus,
    apiUserLogin,
    apiCheckUserDeviceId,
    apiChangePassword,
    apiUpdatePin,
    apiForgotPin,
    apiForgotPassword,
    apiForgetCheckmobile,
    apiGetState,
    apiGetDistrict,
    apiAddUserAddress,
    apiGetUserAddress,
    apiGetProfile,
    apiProfileUpdate,
    apiCheckSecurityPin,
    apiAdminBankDetails,
    apiFundRequestAdd,
    apiLastFundRequestDetail,
    apiFundPaymentSlipUpload,
    apiAddUserBankDetails,
    apiUserBankDetails,
    apiAddUserUpiDetails,
    apiGetUserPaymentDetails,
    apiGameRates,
    apiFundRequestHistory,
    apiUserWalletBalance,
    apiCheckUserForTransferAmt,
    apiUserTransferWalletBalance,
    apiUserPaymentMethodList,
    apiUserWithdrawFundRequest,
    apiGetBellNotification,
    apiCheckNotificationDot,
    apiHowToPlay,
    apiWalletTransactionHistory,
    apiPassbookBidDataInfo,
    apiViewWalletTransactionHistory,
    apiUserWithdrawTransactionHistory,
    apidepositwithdrawHistoryData,
    apiGetAutoDepositList,
    apiValidateBank,
    apiGetSocialData,
    apiGetDashboardData,
    apiGetUpdateResult,
    apiGetLotteryData,
    apiGetSliderImages,
    apiGetCurrentDate,
    apiCheckGamesActiveInactive,
    apiSubmitBid,
    apiLotteryBid,
    apiLotteryPayment,
    apiBidHistoryData,
    apiGetContactDetails,
    apiSubmitContactUs,
    apiGetNotification,
    apiUpdateUserNotificationControl,
    apiSubmitIdea,
    apiWinningHistoryData,
    apiGetTipsList,
    apiViewTipsDetails,
    apiCheckGameStatus,
    apiNotificationSetting,
    apiGetStatement,
    apiAddMoneyViaUpi,
    checkNotification,
    apiGetAppVersionDetails,
    apiStarlineGameRates,
    apiStarlineGame,
    apiCheckStarLineGameStatus,
    apiCheckStarLineGamesActiveInactive,
    apiStarlineSubmitBid,
    apiStarlineBidHistoryData,
    apiStarlineWiningHistoryData,
    apiStarlineGameNames,
    apiStarlineResultHistoryData,
    apiGaliDisswarGameRates,
    apiGaliDisswarGame,
    apiCheckGaliDisswarGameStatus,
    apiCheckGaliDisswarGamesActiveInactive,
    apiGaliDisswarSubmitBid,
    apiGaliDisswarBidHistoryData,
    apiGaliDisswarWiningHistoryData,
    // apiDisswargamenames,
    apiDisawarResultHistoryData,
    apiRouletteGame,
    apiCheckRouletteGameStatus,
    apiGetRouletteGameInfo,
    apiRouletteSubmitBid,
    apiGetRouletteGameWinningNumber,
    apiRouletteBidHistoryData,
    apiGetSpDPMotorCombination,
    apiGetSpDpTpCombination,
    rouletteResultDeclare,
    apiChatApp,
    apiGetChatApp,
    apiGetQRCode,

    // gameResultChart,
    gameJodiChart,
    gamePanelChart,

    gameResultChart_details,
    gameResult_galidessar_chart_details,
    apiLogout_state_update,
    lobbyData,
    checkToken,
    verifyMpin,
    forgetPasswordMpin,
    verifyForgetOtp,
    changePasswordMpin,
    allGamesResultshistory,
    // apiMainBidHistoryData,
    // apiStarLineBidHistoryData,
    // apiJackpotBidHistoryData,


    saveFirebaseToken,



} = require('../controllers/mobileController');
// const { exitToLobby } = require('../utils/connectPlayer');




router.get('/', (req, res) => res.send('Mobile API is working!'));
router.get('/file/uploads/images/:image_id', getPublicImages);
// router.get('/game-result-chart/:gameDB_id', gameResultChart);
router.get('/game-result-jodi-chart/:gameDB_id', gameJodiChart);
router.get('/game-result-panel-chart/:gameDB_id', gamePanelChart);



router.get('/game-result-chart-details', gameResultChart_details);
router.get('/game-result-galidessar-chart-details', gameResult_galidessar_chart_details);


//pawan

router.post('/api-verify-mpin', verifyMpin);
router.post('/api-forget-password-mpin', forgetPasswordMpin);
router.post('/api-verify-forget-otp', verifyForgetOtp );
router.post('/api-change-password-mpin', changePasswordMpin);


router.post('/api-check-login-token', checkToken);
router.post('/api-get-dashboard-data', apiGetDashboardData);
router.post('/api-lobby-data', lobbyData);


// #region fund-receipt multer

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        const uploadDir = path.join(__dirname, '../uploads/fund-request-receipt')
        if (!fs.existsSync(uploadDir)) {
            fs.mkdirSync(uploadDir, { recursive: true })
        }

        cb(null, uploadDir)

    },
    filename: function (req, file, cb) {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
        console.log("uniqS-", uniqueSuffix, file)
        console.log("filename-", ('receipt-', uniqueSuffix + path.extname(file.originalname)))
        cb(null, 'receipt-' + uniqueSuffix + path.extname(file.originalname))
    }
});

const filter = (req, file, cb) => {
    if (file.mimetype.startsWith('image/')) {
        cb(null, true); // Accept file
    } else {
        cb(new Error('Invalid file type'), false); // Reject file
    }
}

const uploadReceipt = multer({
    storage: storage,
    limits: {
        fileSize: 5 * 1024 * 1024,
        files: 1
    },
    fileFilter: filter
})

// module.exports = upload;




//pawan
router.post('/api-logout-state-update', apiLogout_state_update);
router.post('/api-get-app-key', apiGetAppKey);
router.post('/api-check-mobile', apiCheckMobile);
router.post('/api-check-username', apiCheckUsername);
router.post('/api-otp-sent', apiOtpSent);
router.post('/api-resend-otp', apiResendOtp);
router.post('/api-user-registration', apiUserRegistration);
router.post('/api-user-status', apiUserStatus);
router.post('/api-user-login', apiUserLogin);
router.post('/api-change-password', apiChangePassword);
router.post('/api-update-pin', apiUpdatePin);
router.post('/api-forgot-pin', apiForgotPin);
router.post('/api-forgot-password', apiForgotPassword);
router.post('/api-check-user-deviceid', apiCheckUserDeviceId);
router.post('/api-forget-check-mobile', apiForgetCheckmobile);
router.post('/api-admin-bank-details', apiAdminBankDetails);
router.post('/api_support_contact', apiGetContactDetails); // get contact details for mobile users
router.post('/api-get-slider-images', apiGetSliderImages);
// router.post('/api-add-money-via-upi', apiAddMoneyViaUpi);api-add-money-via-upi
// router.post('/api-add-money-via-upi', uploadReceipt.single('fund-request-receipt'), apiAddMoneyViaUpi);
router.post('/api-add-money-via-upi', apiAddMoneyViaUpi);

router.post('/api-get-current-date', apiGetCurrentDate);
router.post('/api-get-auto-deposit-list', apiGetAutoDepositList);
router.post('/api-deposit-withdraw-history', apidepositwithdrawHistoryData); //user fund withdraw history
router.post('/api-add-user-bank-details', apiAddUserBankDetails); // add user bank details
router.post('/api-get-user-bank-details', apiUserBankDetails); // get user bank details
router.post('/api-wallet-transaction-history', apiWalletTransactionHistory);  // user passbook wallet transaction history
router.post('/api-passbook-bid-info', apiPassbookBidDataInfo);  // user passbook wallet transaction history
router.post('/api-get-qrcode', apiGetQRCode);
// router.get('/admin/list_manual-payment-details', getManualPaymentDetails);
router.post('/api-user-wallet-balance', apiUserWalletBalance);
router.post('/api-submit-bid', apiSubmitBid); // main game submit bid // bidsubmit

router.post('/api-update_user_notification_control', apiUpdateUserNotificationControl);


router.post('/api-get-notification', apiGetNotification);
router.post('/api-get-notice', apiGetBellNotification); // apiGetBellNotification
router.post('/api-get-notice-dot', apiCheckNotificationDot); // apiCheckNotificationDot

router.post('/api-submit-idea', apiSubmitIdea);
router.post('/api-bid-history-data', apiBidHistoryData);
// router.post('/api-main-bid-history', apiMainBidHistoryData);
// withdraw withdraw fund request
router.post('/api-user-withdraw-fund-request', apiUserWithdrawFundRequest); // user withdraw amount request api
router.post('/api-starline-game-rates', apiStarlineGameRates);
router.post('/api-starline-game', apiStarlineGame);
router.post('/api-starline-submit-bid', apiStarlineSubmitBid);  // starline game submit bid // bidsubmit
router.post('/api-galidisswar-game', apiGaliDisswarGame);
router.post('/api-galidisswar-game-rates', apiGaliDisswarGameRates);
router.post('/api-galidisswar-submit-bid', apiGaliDisswarSubmitBid); // bidsubmit
router.post('/api-game-rates', apiGameRates);
router.post('/api-how-to-play', apiHowToPlay);


router.post('/api-all-games-results-history', allGamesResultshistory); // all game types result history for application with date and game type


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

    if (!title || !desc) {
        return res.status(400).json({ error: "Title and description are required." });
    }

    try {
        // map dropdown user to OneSignal segment
        const mapUserToSegment = (userSelection) => {
            switch (userSelection) {
                case "All users": return ["All"];
                case "Active users": return ["Active Users"];
                case "Inactive users": return ["Inactive Users"];
                default: return ["All"];
            }
        };

        const payload = {
            app_id: process.env.ONESIGNAL_APP_ID,
            included_segments: mapUserToSegment(user),
            headings: { en: title },
            contents: { en: desc },
        };

        const response = await axios.post("https://onesignal.com/api/v1/notifications", payload, {
            headers: {
                "Content-Type": "application/json",
                "Authorization": `Basic ${process.env.ONESIGNAL_REST_API_KEY}`,
            },
        });

        res.json({
            success: true,
            message: "Notification sent successfully",
            data: response.data,
        });
    } catch (error) {
        console.error("OneSignal Error:", error.response?.data || error.message);
        res.status(500).json({
            error: error.response?.data?.errors?.[0] || "Failed to send notification.",
        });
    }
});







// #region use less
router.post('/api-get-profile', apiGetProfile);

router.post('/api-get-state', apiGetState);

router.post('/api-get-district', apiGetDistrict);

router.post('/api-add-user-address', apiAddUserAddress);

router.post('/api-get-user-address', apiGetUserAddress);

router.post('/api-profile-update', apiProfileUpdate);

router.post('/api-check-security-pin', apiCheckSecurityPin);

router.post('/api-fund-request-add', apiFundRequestAdd);

router.post('/api-last-fund-request-detail', apiLastFundRequestDetail);

router.post('/api-fund-payment-slip-upload', upload.single('payment_slip'), apiFundPaymentSlipUpload);

router.post('/api-add-user-upi-details', apiAddUserUpiDetails);

router.post('/api-get-user-payment-details', apiGetUserPaymentDetails);

router.post('/api-fund-request-history', apiFundRequestHistory);


router.post('/api-check-user-for-transfer-amt', apiCheckUserForTransferAmt);

router.post('/api-user-transfer-wallet-balance', apiUserTransferWalletBalance);

router.post('/api-user-payment-method-list', apiUserPaymentMethodList);

router.post('/api-view-wallet-transaction-history', apiViewWalletTransactionHistory);

router.post('/api-user-withdraw-transaction-history', apiUserWithdrawTransactionHistory); // user fund withdraw history api for application



router.post('/api-validate-bank', apiValidateBank);

router.post('/api-get-social-data', apiGetSocialData);


router.post('/api-get-update-result', apiGetUpdateResult);

router.post('/api_get_lottery_data', apiGetLotteryData);

router.post('/api_get_lottery_tickets', apiGetLotteryData);


router.post('/api-check-games-active-inactive', apiCheckGamesActiveInactive)


router.post('/api_lottery_bid', apiLotteryBid);

router.post('/api_lottery_payment', apiLotteryPayment);

router.post('/api-submit-contact-us', apiSubmitContactUs);


// controller not available
router.post('/api-wining-result', (req, res) => {
    res.send('Mobile api-wining-result route is working!');
});

router.post('/api-wining-history-data', apiWinningHistoryData);  // main game win history

router.post('/api-get-tips-list', apiGetTipsList);

router.post('/api-view-tips-details', apiViewTipsDetails);

router.post('/api-check-game-status', apiCheckGameStatus);

router.post('/api-notification-setting', apiNotificationSetting);

router.post('/api-get-statement', apiGetStatement);


router.post('/checkNotifiation', checkNotification);

router.post('/api-get-app-version-details', apiGetAppVersionDetails);

router.post('/api-check-starline-game-status', apiCheckStarLineGameStatus);

router.post('/api-check-starline-games-active-inactive', apiCheckStarLineGamesActiveInactive);

router.post('/api-starline-bid-history-data', apiStarlineBidHistoryData);

router.post('/api-starline-wining-history-data', apiStarlineWiningHistoryData); // starline game win history

router.post('/api-starline-gamenames', apiStarlineGameNames);

router.post('/api-starline-result-history-data', apiStarlineResultHistoryData);

router.post('/api-check-galidisswar-game-status', apiCheckGaliDisswarGameStatus);

router.post('/api-check-galidisswar-games-active-inactive', apiCheckGaliDisswarGamesActiveInactive);

router.post('/api-galidisswar-bid-history-data', apiGaliDisswarBidHistoryData);

router.post('/api-galidisswar-wining-history-data', apiGaliDisswarWiningHistoryData); // galidisswar game win history

// router.post('/api-galidisswar-gamenames', apiDisswargamenames);

router.post('/api-disawar-result-history-data', apiDisawarResultHistoryData);

router.post('/api-roulette-game', apiRouletteGame);

// controller not available
router.post('/api-get-roulette-game-time', (req, res) => {
    res.send('Mobile api-get-roulette-game-time route is working!');
});

router.post('/api-check-roulette-game-status', apiCheckRouletteGameStatus);

router.post('/api-get-roulette-game-info', apiGetRouletteGameInfo);

router.post('/api-roulette-submit-bid', apiRouletteSubmitBid);

router.post('/api-get-roulette-game-winning-number', apiGetRouletteGameWinningNumber);

router.post('/api-roulette-bid-history-data', apiRouletteBidHistoryData);

router.post('/api-roulette-wining-history-data', apiRouletteBidHistoryData);

router.post('/api-get-sp-motor-combination', apiGetSpDPMotorCombination);

router.post('/api-get-sp-dp-tp-combination', apiGetSpDpTpCombination);

router.post('/roulette-result-declare', rouletteResultDeclare);

router.post('/api-chat-app', upload.single('file'), apiChatApp);

router.post('/api-get-chat-app', apiGetChatApp);

router.post('/api-save-firebase-token', saveFirebaseToken);

//#endregion


// router.post('/api/deposit/initiate', createDepositRequest);
// router.get('/api/deposit/status/:orderId', checkDepositStatus);
router.post("/api/webhook/dollarbazar", dollarbazarWebhook);
router.post("/api/dollarbazar/payout-webhook", dollarbazarPayoutWebhook);


router.post("/api/webhook/protonpay", protonpayWebhook);
router.post("/api/webhook/protonpay/payout", protonPayPayoutWebhook);





module.exports = router;