//
//  Bill24OnlinePaymentSdk.swift
//  Bill24OnlinePaymentSdk
//  Created by MacbookPro on 12/10/23.
//

import Foundation
import UIKit
import Alamofire

public class B24PaymentSdk {
    
    public init() {}
    let activityIndicator = UIActivityIndicatorView(style: .large)
    
    func startLoading(view: UIView) {
        activityIndicator.startAnimating()
        // You can also disable user interaction while the loading indicator is visible
        view.isUserInteractionEnabled = false
    }
    
    func stopLoading(view: UIView) {
        activityIndicator.stopAnimating()
        // Enable user interaction when the loading indicator is hidden
        view.isUserInteractionEnabled = true
    }
    
    public func initSdk(
        controller: UIViewController,
        transactionId: String,
        refererKey: String,
        language: String? = nil,
        darkMode: Bool? = nil,
        isProduction: Bool? = nil,
        testingEnv:String? = nil,
        pollingIntervalSeconds: TimeInterval? = nil
    ){
        print("**** Loading SDK ****")
        
        SDKVariableSetting.xRefererKey = refererKey
        SDKVariableSetting.currentLanguage = language?.lowercased() ?? ""
        SDKVariableSetting.isDarkMode = darkMode ?? false
        SDKVariableSetting.isProduction = isProduction ?? false
        SDKVariableSetting.testingEnv = testingEnv ?? "DEMO"
        if let pollingIntervalSeconds {
            SDKVariableSetting.pollingIntervalSeconds = pollingIntervalSeconds
        }
        
        
        
        // Configure the activity indicator
        activityIndicator.center = controller.view.center
        activityIndicator.hidesWhenStopped = true
        activityIndicator.color = UIColor.systemBlue
        controller.view.addSubview(activityIndicator)
        startLoading(view: controller.view)
                
        AF.request(CheckoutRouter.checkoutDetail(transactionId: transactionId)).validate().responseData{
            [self](response) in
            switch response.result{
            case .success(let data):
                let transaction: Transaction? = try? JSONDecoder().decode(Transaction.self, from: data)
                if(transaction?.code == "SUCCESS"){
                    if(transaction?.data?.transInfo.status == "success"){
                        // Set up theme
                        Themes.useDefaults(isDarkMode: SDKVariableSetting.isDarkMode)
                    //    Themes.setTheme(isDarkMode: SDKVariableSetting.isDarkMode, themeData: (((transaction?.data?.checkoutPageConfig))?.appearance)!)
                        // transaction success already, so open success controller
                        if TopUpView.isTopUpTransaction {
                            TopUpView.isTopUpTransaction = false
                            let storyboard = UIStoryboard(name: "InstantPaymentMethodView", bundle: B24PaymentSdkHelper.frameworkBundle())
                            if let walletVC = storyboard.instantiateViewController(withIdentifier: "WalletSuccessViewController") as? WalletSuccessViewController {
                                walletVC.modalPresentationStyle = .fullScreen
                                controller.present(walletVC, animated: true, completion: nil)
                            }
                        } else {
                            let storyboard = UIStoryboard(name: "SuccessScreenViewController", bundle: B24PaymentSdkHelper.frameworkBundle())
                            if let successVC = storyboard.instantiateViewController(withIdentifier: "SuccessScreenViewController") as? SuccessScreenViewController {
                                successVC.transactionSuccess = transaction
                                successVC.modalPresentationStyle = .fullScreen
                                controller.present(successVC, animated: true, completion: nil)
                            }
                        }
                    }else{
                        // transaction unpaid, so payment bottomsheet
                        let b24PaymentSdkHelper = B24PaymentSdkHelper()
                        let paymentView = PaymentMethodView(
                            frame: controller.view.frame,
                            controller: controller,
                            transactionId: transactionId,
                            bottomSheetController: b24PaymentSdkHelper.vc,
                            transaction: transaction
                        )
                        b24PaymentSdkHelper.presentBottomSheet(
                            from: controller,
                            view: paymentView,
                            viewType: .ninetyPercent,
                            transactionId: transactionId
                        )
                    }
                }else{
                    // alert error back to merchant
                    //                    B24PaymentSdkHelper.errorSnackbar(
                    //                        view: controller.view,
                    //                        message: (transaction?.messageKh ?? transaction?.message) ??  B24PaymentSdkHelper.localized(SnackBarLocalizedKeys.error.rawValue),
                    //                        forBottomSheet: false
                    //                    )
                    let lan = language?.lowercased() ?? "km"
                    let message = lan == "en" ? transaction?.message : transaction?.messageKh
                    
                    B24PaymentSdkHelper.errorSnackbar(
                        view: controller.view,
                        message: message ?? B24PaymentSdkHelper.localized(SnackBarLocalizedKeys.error.rawValue),
                        forBottomSheet: false
                    )
                }
                stopLoading(view: controller.view)
            case .failure(let error):
                print(error)
                // alert error back to merchant
                B24PaymentSdkHelper.errorSnackbar(
                    view: controller.view,
                    message: B24PaymentSdkHelper.localized(SnackBarLocalizedKeys.error.rawValue),
                    forBottomSheet: false
                )
                stopLoading(view: controller.view)
            }
        }
    }
    
    
    //digital wallet
    
    static let  activityIndicatorWallet = UIActivityIndicatorView(style: .large)
    
    static func startLoadingWallet(view: UIView) {
        B24PaymentSdk.activityIndicatorWallet.startAnimating()
        // You can also disable user interaction while the loading indicator is visible
        view.isUserInteractionEnabled = false
    }
    
    static func stopLoadingWallet(view: UIView) {
        B24PaymentSdk.activityIndicatorWallet.stopAnimating()
        // Enable user interaction when the loading indicator is hidden
        view.isUserInteractionEnabled = true
    }
    
    public static func instantPaymentSdk(
        from presentingViewController: UIViewController,
        userSynCode:String,
        refererKey:String,
        language:String?=nil,
        isDarkMode:Bool?=nil,
        isProduction:Bool?=nil,
        testingEnv:String?=nil,
        isDisplayCurrencySymbol:Bool?=nil,
        pollingIntervalSeconds: TimeInterval? = nil
    ) {
        
        SDKVariableSetting.xRefererKey = refererKey
        SDKVariableSetting.currentLanguage = language?.lowercased() ?? ""
        SDKVariableSetting.isDarkMode = isDarkMode ?? false
        SDKVariableSetting.isProduction = isProduction ?? false
        SDKVariableSetting.testingEnv = testingEnv ?? "DEMO"
        SDKVariableSetting.isDislpayCurrencySymbol=isDisplayCurrencySymbol ?? false
        if let pollingIntervalSeconds {
            SDKVariableSetting.pollingIntervalSeconds = pollingIntervalSeconds
        }

        // Apply local defaults first. If the appearance API returns values,
        // they override these defaults; otherwise the SDK keeps the local theme.
        if SDKVariableSetting.isDarkMode {
            let dark = DWalletMode.darkModeDefaults()
            DefaultAppearance.shared.primaryColor        = UIColor(hex: dark.primaryColor)
            DefaultAppearance.shared.screenBgColor       = UIColor(hex: dark.screenBgColor)
            DefaultAppearance.shared.primaryLabelColor   = UIColor(hex: dark.primaryLabelColor)
            DefaultAppearance.shared.secondaryLabelColor = UIColor(hex: dark.secondaryLabelColor)
            DefaultAppearance.shared.cardColor           = UIColor(hex: dark.cardColor)
            DefaultAppearance.shared.onPrimaryColor      = UIColor(hex: dark.onPrimaryColor)
            DefaultAppearance.shared.dangerColor         = UIColor(hex: dark.dangerColor)
            DefaultAppearance.shared.warningColor        = UIColor(hex: dark.warningColor)
            DefaultAppearance.shared.successColor        = UIColor(hex: dark.successColor ?? "#17A865")
            DefaultAppearance.shared.walletCardColor     = UIColor(hex: dark.walletCardColor ?? "#1A2D4A")
        } else {
            let light = DWalletMode()
            DefaultAppearance.shared.primaryColor        = UIColor(hex: light.primaryColor)
            DefaultAppearance.shared.screenBgColor       = UIColor(hex: light.screenBgColor)
            DefaultAppearance.shared.primaryLabelColor   = UIColor(hex: light.primaryLabelColor)
            DefaultAppearance.shared.secondaryLabelColor = UIColor(hex: light.secondaryLabelColor)
            DefaultAppearance.shared.cardColor           = UIColor(hex: light.cardColor)
            DefaultAppearance.shared.onPrimaryColor      = UIColor(hex: light.onPrimaryColor)
            DefaultAppearance.shared.dangerColor         = UIColor(hex: light.dangerColor)
            DefaultAppearance.shared.warningColor        = UIColor(hex: light.warningColor)
            DefaultAppearance.shared.successColor        = UIColor(hex: light.successColor ?? "#17A865")
            DefaultAppearance.shared.walletCardColor     = UIColor(hex: light.walletCardColor ?? "#214775")
        }

        SharedPreferenceManager.set(value: SDKVariableSetting.currentLanguage, forKey: SharePrefKey.lanuageCode.rawValue)
        SharedPreferenceManager.set(value: userSynCode, forKey: SharePrefKey.customerSyncode.rawValue)
        
        if SDKVariableSetting.isProduction{
            SharedPreferenceManager.set(value: true , forKey: SharePrefKey.isProduction.rawValue)
        }else{
            SharedPreferenceManager.set(value: false , forKey: SharePrefKey.isProduction.rawValue)
            SharedPreferenceManager.set(value: SDKVariableSetting.testingEnv, forKey: SharePrefKey.environment.rawValue)
        }
        
        // Show progress indicator
        B24PaymentSdk.activityIndicatorWallet.center = presentingViewController.view.center
        B24PaymentSdk.activityIndicatorWallet.hidesWhenStopped = true
        B24PaymentSdk.activityIndicatorWallet.color = UIColor.systemBlue
        presentingViewController.view.addSubview(B24PaymentSdk.activityIndicatorWallet)
        B24PaymentSdk.startLoadingWallet(view:presentingViewController.view)
        
        
        
        AF.request(WalletRouter.getAppearance).validate().responseData{
            response in
            switch response.result{
            case .success(let data):
                
                do{
                    let decodedData = try JSONDecoder().decode(ConfigResponseModel.self, from: data)
                    if decodedData.code == StatusCode.succcess.rawValue{
                        
                      //  B24PaymentSdk.stopLoadingWallet(view: presentingViewController.view)
                        
                        DefaultAppearance.shared.setAppearance(decodedData.data!.appearance, isDarkMode: SDKVariableSetting.isDarkMode)
                        
                        
                        fetchAvailablePMType(customerSyncCode: userSynCode)
                        
                        fetchPaymentMethods(
                            customerSynCode: userSynCode,
                            presentingViewController: presentingViewController,
                            language: language!)
                            
                            
                        }else{
                            let lan = language?.lowercased() ?? "km"
                            let message = lan == "en" ? decodedData.message : decodedData.messageKh
                            
                            B24PaymentSdkHelper.errorSnackbar(view: presentingViewController.view,
                                                              message: message ?? B24PaymentSdkHelper.localized(SnackBarLocalizedKeys.error.rawValue))
                           
                            B24PaymentSdk.stopLoadingWallet(view: presentingViewController.view)
                            
                        }
                        
                    }catch{
                        print("Decode Error: \(error)")
                    }
                    
                    break
                    
                    
                case .failure(let error):
                
                    print("====>\(error)")
               
                    B24PaymentSdkHelper.errorSnackbar(
                        view: presentingViewController.view,
                        message: B24PaymentSdkHelper.localized(SnackBarLocalizedKeys.error.rawValue),
                        forBottomSheet: false
                    )
                    B24PaymentSdk.stopLoadingWallet(view: presentingViewController.view)
                    
                }
            }
        }
    
    public static func instantPaymentSdkTopUp(
        from presentingViewController: UIViewController,
        paymentMethodId:String,
        refererKey:String,
        language:String?=nil,
        isDarkMode:Bool?=nil,
        isProduction:Bool?=nil,
        testingEnv:String?=nil,
        isDisplayCurrencySymbol:Bool?=nil,
        pollingIntervalSeconds: TimeInterval? = nil
    ) {
        
        SDKVariableSetting.xRefererKey = refererKey
        SDKVariableSetting.currentLanguage = language?.lowercased() ?? ""
        SDKVariableSetting.isDarkMode = isDarkMode ?? false
        SDKVariableSetting.isProduction = isProduction ?? false
        SDKVariableSetting.testingEnv = testingEnv ?? "DEMO"
        SDKVariableSetting.isDislpayCurrencySymbol=isDisplayCurrencySymbol ?? false
        if let pollingIntervalSeconds {
            SDKVariableSetting.pollingIntervalSeconds = pollingIntervalSeconds
        }
        
        SharedPreferenceManager.set(value: SDKVariableSetting.currentLanguage, forKey: SharePrefKey.lanuageCode.rawValue)
        //SharedPreferenceManager.set(value: userSynCode, forKey: SharePrefKey.customerSyncode.rawValue)
        
        if SDKVariableSetting.isProduction{
            SharedPreferenceManager.set(value: true , forKey: SharePrefKey.isProduction.rawValue)
        }else{
            SharedPreferenceManager.set(value: false , forKey: SharePrefKey.isProduction.rawValue)
            SharedPreferenceManager.set(value: SDKVariableSetting.testingEnv, forKey: SharePrefKey.environment.rawValue)
        }
        
        // Show progress indicator
        B24PaymentSdk.activityIndicatorWallet.center = presentingViewController.view.center
        B24PaymentSdk.activityIndicatorWallet.hidesWhenStopped = true
        B24PaymentSdk.activityIndicatorWallet.color = UIColor.systemBlue
        presentingViewController.view.addSubview(B24PaymentSdk.activityIndicatorWallet)
        B24PaymentSdk.startLoadingWallet(view:presentingViewController.view)
        
        
        
        AF.request(WalletRouter.getAppearance).validate().responseData{
            [self](response) in
            switch response.result{
            case .success(let data):
                
                do{
                    let decodedData = try JSONDecoder().decode(ConfigResponseModel.self, from: data)
                    if decodedData.code == StatusCode.succcess.rawValue{
                        
                      //  B24PaymentSdk.stopLoadingWallet(view: presentingViewController.view)
                        
                        DefaultAppearance.shared.setAppearance(decodedData.data!.appearance, isDarkMode: SDKVariableSetting.isDarkMode)
                        // navigate to new screen                        
                        
                        accountDetail(paymentMethodId: paymentMethodId,
                                      presentingViewController: presentingViewController,
                                      language: language!)
                            
                            
                        }else{
                            let lan = language?.lowercased() ?? "km"
                            let message = lan == "en" ? decodedData.message : decodedData.messageKh
                            
                            B24PaymentSdkHelper.errorSnackbar(view: presentingViewController.view,
                                                              message: message ?? B24PaymentSdkHelper.localized(SnackBarLocalizedKeys.error.rawValue))
                           
                            B24PaymentSdk.stopLoadingWallet(view: presentingViewController.view)
                            
                        }
                        
                    }catch{
                        print("Decode Error: \(error)")
                    }
                    
                    break
                    
                    
                case .failure(let error):
                
                    print("====>\(error)")
               
                    B24PaymentSdkHelper.errorSnackbar(
                        view: presentingViewController.view,
                        message: B24PaymentSdkHelper.localized(SnackBarLocalizedKeys.error.rawValue),
                        forBottomSheet: false
                    )
                    B24PaymentSdk.stopLoadingWallet(view: presentingViewController.view)
                    
                }
            }
        }
    

    public static func instantPaymentSdkDetail(
        from presentingViewController: UIViewController,
        customerSyncCode:String,
        paymentMethodId:String,
        refererKey:String,
        language:String?=nil,
        isDarkMode:Bool?=nil,
        isProduction:Bool?=nil,
        testingEnv:String?=nil,
        isDisplayCurrencySymbol:Bool?=nil,
        pollingIntervalSeconds: TimeInterval? = nil
    ) {
        
        SDKVariableSetting.xRefererKey = refererKey
        SDKVariableSetting.currentLanguage = language?.lowercased() ?? ""
        SDKVariableSetting.isDarkMode = isDarkMode ?? false
        SDKVariableSetting.isProduction = isProduction ?? false
        SDKVariableSetting.testingEnv = testingEnv ?? "DEMO"
        SDKVariableSetting.isDislpayCurrencySymbol=isDisplayCurrencySymbol ?? false
        if let pollingIntervalSeconds {
            SDKVariableSetting.pollingIntervalSeconds = pollingIntervalSeconds
        }
        
        SharedPreferenceManager.set(value: SDKVariableSetting.currentLanguage, forKey: SharePrefKey.lanuageCode.rawValue)
        //SharedPreferenceManager.set(value: userSynCode, forKey: SharePrefKey.customerSyncode.rawValue)
        
        if SDKVariableSetting.isProduction{
            SharedPreferenceManager.set(value: true , forKey: SharePrefKey.isProduction.rawValue)
        }else{
            SharedPreferenceManager.set(value: false , forKey: SharePrefKey.isProduction.rawValue)
            SharedPreferenceManager.set(value: SDKVariableSetting.testingEnv, forKey: SharePrefKey.environment.rawValue)
        }
        
        // Show progress indicator
        B24PaymentSdk.activityIndicatorWallet.center = presentingViewController.view.center
        B24PaymentSdk.activityIndicatorWallet.hidesWhenStopped = true
        B24PaymentSdk.activityIndicatorWallet.color = UIColor.systemBlue
        presentingViewController.view.addSubview(B24PaymentSdk.activityIndicatorWallet)
        B24PaymentSdk.startLoadingWallet(view:presentingViewController.view)
        
        
        
        AF.request(WalletRouter.getAppearance).validate().responseData{
            [self](response) in
            switch response.result{
            case .success(let data):
                
                do{
                    let decodedData = try JSONDecoder().decode(ConfigResponseModel.self, from: data)
                    if decodedData.code == StatusCode.succcess.rawValue{
                        
                      //  B24PaymentSdk.stopLoadingWallet(view: presentingViewController.view)
                        
                        DefaultAppearance.shared.setAppearance(decodedData.data!.appearance, isDarkMode: SDKVariableSetting.isDarkMode)
                        // navigate to new screen                        
                        
                        fetchPaymentMethodsV2(customerSynCode: customerSyncCode, paymentMethodId: paymentMethodId, presentingViewController: presentingViewController, language: language!)
                            
                            
                        }else{
                            let lan = language?.lowercased() ?? "km"
                            let message = lan == "en" ? decodedData.message : decodedData.messageKh
                            
                            B24PaymentSdkHelper.errorSnackbar(view: presentingViewController.view,
                                                              message: message ?? B24PaymentSdkHelper.localized(SnackBarLocalizedKeys.error.rawValue))
                           
                            B24PaymentSdk.stopLoadingWallet(view: presentingViewController.view)
                            
                        }
                        
                    }catch{
                        print("Decode Error: \(error)")
                    }
                    
                    break
                    
                    
                case .failure(let error):
                
                    print("====>\(error)")
               
                    B24PaymentSdkHelper.errorSnackbar(
                        view: presentingViewController.view,
                        message: B24PaymentSdkHelper.localized(SnackBarLocalizedKeys.error.rawValue),
                        forBottomSheet: false
                    )
                    B24PaymentSdk.stopLoadingWallet(view: presentingViewController.view)
                    
                }
            }
        }
    

    private static func accountDetailV2(paymentMethodId:String,
                                      presentingViewController:UIViewController,
                                      language:String,
                                      paymentMethodCount:Int){
    
        AF.request(WalletRouter.instantPaymentMethodDetail(id: paymentMethodId))
            .validate().responseData{
                [self](response) in
                switch response.result{
                case .success(let data):
                    B24PaymentSdk.stopLoadingWallet(view: presentingViewController.view)
                   
                    do{
                        let decodeData = try JSONDecoder().decode(ApiResponse<DataAccountDetail>.self,from: data)
                        if decodeData.code == StatusCode.succcess.rawValue{
                            
                           var dataAccountDetail = decodeData.data
                            
                            //set share Preference
                            setSharePref(pmId: dataAccountDetail.id, walletName: dataAccountDetail.accountName, walletNo: dataAccountDetail.accountNo, amount: dataAccountDetail.amountDisplay, currency: dataAccountDetail.currency,isWalletTopup:true)
                            
                            let storyboard = UIStoryboard(name: "InstantPaymentMethodView", bundle: B24PaymentSdkHelper.frameworkBundle())
                            if let viewController = storyboard.instantiateViewController(withIdentifier: "AccountDetailView") as? AccountDetailView {
                                
                                viewController.paymentMethodCount = paymentMethodCount
                                
                                let navigationController = PortraitNavigationController(rootViewController:viewController)
                                navigationController.modalPresentationStyle = .fullScreen
                                
                                presentingViewController.present(navigationController, animated: true, completion: nil)
                            }
                        }else{
                            let message = language == "en" ? decodeData.message : decodeData.messageKh
                            B24PaymentSdkHelper.errorSnackbar(view:presentingViewController.view,
                                                              message: message )
                        }
                    }catch{
                        print("Decode Error: \(error)")
                    }
                case .failure(let error):
                    print("error \(error)")
                    B24PaymentSdkHelper.errorSnackbar(
                        view:presentingViewController.view,
                                    message: B24PaymentSdkHelper.localized(SnackBarLocalizedKeys.error.rawValue),
                                                        forBottomSheet: false
                                                    )
                    B24PaymentSdk.stopLoadingWallet(view: presentingViewController.view)
                }
            }
        
    }


    private static func accountDetail(paymentMethodId:String,
                                      presentingViewController:UIViewController,
                                      language:String
                                      ){
    
        AF.request(WalletRouter.instantPaymentMethodDetail(id: paymentMethodId))
            .validate().responseData{
                [self](response) in
                switch response.result{
                case .success(let data):
                    B24PaymentSdk.stopLoadingWallet(view: presentingViewController.view)
                   
                    do{
                        let decodeData = try JSONDecoder().decode(ApiResponse<DataAccountDetail>.self,from: data)
                        if decodeData.code == StatusCode.succcess.rawValue{
                            
                           var dataAccountDetail = decodeData.data
                            
                            //set share Preference
                            setSharePref(pmId: dataAccountDetail.id, walletName: dataAccountDetail.accountName, walletNo: dataAccountDetail.accountNo, amount: dataAccountDetail.amountDisplay, currency: dataAccountDetail.currency,isWalletTopup:true)
                            
                            let storyboard = UIStoryboard(name: "InstantPaymentMethodView", bundle: B24PaymentSdkHelper.frameworkBundle())
                            if let viewController = storyboard.instantiateViewController(withIdentifier: "TopUpView") as? TopUpView {
                                
                                viewController.currencyCode=dataAccountDetail.currencyCode
                                viewController.currencySymbol=dataAccountDetail.currencySymbol
//                                let navigationController = UINavigationController(rootViewController: viewController)
                                let navigationController = PortraitNavigationController(rootViewController:viewController)
                                navigationController.modalPresentationStyle = .fullScreen
                                
                                presentingViewController.present(navigationController, animated: true, completion: nil)
                            }
                            
                          
                            
                        }else{
                            
                            let message = language == "en" ? decodeData.message : decodeData.messageKh
                            
                            B24PaymentSdkHelper.errorSnackbar(view:presentingViewController.view,
                                                              message: message )
                           
                        }
                        
                    }catch{
                        print("Decode Error: \(error)")
                    }
                case .failure(let error):
                   
                    
                    print("error \(error)")
                    
                    B24PaymentSdkHelper.errorSnackbar(
                        view:presentingViewController.view,
                                    message: B24PaymentSdkHelper.localized(SnackBarLocalizedKeys.error.rawValue),
                                                        forBottomSheet: false
                                                    )
                    B24PaymentSdk.stopLoadingWallet(view: presentingViewController.view)
        
                    
                }
            }
        
    }
    
    private static func setSharePref(pmId:String,walletName:String,walletNo:String,amount:String,currency:String,isWalletTopup:Bool){
        SharedPreferenceManager.set(value: pmId, forKey: SharePrefKey.paymentMethodId.rawValue)
        SharedPreferenceManager.set(value: walletName, forKey: SharePrefKey.walletName.rawValue)
        SharedPreferenceManager.set(value: walletNo, forKey: SharePrefKey.walletNo.rawValue)
        SharedPreferenceManager.set(value: amount, forKey: SharePrefKey.balance.rawValue)
        SharedPreferenceManager.set(value: currency, forKey: SharePrefKey.currency.rawValue)
        SharedPreferenceManager.set(value: isWalletTopup, forKey: SharePrefKey.isWalletTopup.rawValue)
        

    }


    private static func fetchPaymentMethodsV2(
        customerSynCode:String,
        paymentMethodId:String,
        presentingViewController:UIViewController,
        language:String
        
    ) {
        
        AF.request(WalletRouter.instantPaymentMethod(customerSynCode: customerSynCode, filterBy: " "))
            .validate().responseData{
                [self](response) in
                
                switch response.result{
                case .success(let data):
                    B24PaymentSdk.stopLoadingWallet(view: presentingViewController.view)
                    
                    do{
                        let decodeData = try JSONDecoder().decode(ApiResponse<InstantPaymentMethodsResponse>.self,from: data)
                        
                        if decodeData.code == StatusCode.succcess.rawValue{
                            
                            accountDetailV2(paymentMethodId: paymentMethodId, presentingViewController: presentingViewController, language: language,paymentMethodCount: decodeData.data.paymentMethods?.count ?? 1)
                            
                        }else{
                            
                            let message = language == "en" ? decodeData.message : decodeData.messageKh
                            
                            B24PaymentSdkHelper.errorSnackbar(view:presentingViewController.view,
                                                              message: message )
                            
                        }
                        
                        
                    }catch{
                        print("Decode Error: \(error)")
                    }
                    
                case .failure(let error):
                    print("error \(error)")
                    B24PaymentSdkHelper.errorSnackbar(
                        view:presentingViewController.view,
                        message: B24PaymentSdkHelper.localized(SnackBarLocalizedKeys.error.rawValue),
                        forBottomSheet: false
                    )
                    B24PaymentSdk.stopLoadingWallet(view: presentingViewController.view)
                }
            }
    }
    
    
    //
    private static func fetchPaymentMethods(
        customerSynCode:String,
        presentingViewController:UIViewController,
        language:String
        
    ) {
       
        AF.request(WalletRouter.instantPaymentMethod(customerSynCode: customerSynCode, filterBy: " "))
            .validate().responseData{
                [self](response) in
                
                switch response.result{
                case .success(let data):
                    B24PaymentSdk.stopLoadingWallet(view: presentingViewController.view)
                    
                    do{
                        let decodeData = try JSONDecoder().decode(ApiResponse<InstantPaymentMethodsResponse>.self,from: data)
                        
                        if decodeData.code == StatusCode.succcess.rawValue{
                           
                            let storyboard = UIStoryboard(name: "InstantPaymentMethodView", bundle: B24PaymentSdkHelper.frameworkBundle())
                            if let viewController = storyboard.instantiateViewController(withIdentifier: "InstantPMView") as? InstantPMView {
                                
//                               let navigationController = UINavigationController(rootViewController: viewController)
                                let navigationController = PortraitNavigationController(rootViewController:viewController)
                                navigationController.modalPresentationStyle = .fullScreen
                                
                                presentingViewController.present(navigationController, animated: true, completion: nil)
                            }
                           
                            
                        }else{
                
                            let message = language == "en" ? decodeData.message : decodeData.messageKh
                            
                            B24PaymentSdkHelper.errorSnackbar(view:presentingViewController.view,
                                                              message: message )
                           
                        }
                        
                        
                    }catch{
                        print("Decode Error: \(error)")
                    }
                    
                case .failure(let error):
                    print("error \(error)")
                    B24PaymentSdkHelper.errorSnackbar(
                        view:presentingViewController.view,
                                    message: B24PaymentSdkHelper.localized(SnackBarLocalizedKeys.error.rawValue),
                                                        forBottomSheet: false
                                                    )
                    B24PaymentSdk.stopLoadingWallet(view: presentingViewController.view)
                    }
                }
            }
    
    
    
    private static func fetchAvailablePMType(customerSyncCode:String){
       
        
        AF.request(WalletRouter.getAvailablePMType(customerSyncCode: customerSyncCode)).validate().responseData{
            response in
            
            switch response.result {
            case .success(let data):
                do {
                    // Decode the response data
                    let decodedData = try JSONDecoder().decode(AvailablePMTypeResponseModel.self, from: data)
                    
                    SharedPreferenceManager.set(value: false, forKey: SharePrefKey.isWalletTopup.rawValue)
                    
                    if(decodedData.data.availablePaymentMethodTypes.isEmpty || decodedData.data.availablePaymentMethodTypes.count==0){
                        
                        SharedPreferenceManager.set(value: true, forKey: SharePrefKey.disableFloatButton.rawValue)
                    }else{
                        SharedPreferenceManager.set(value: false, forKey: SharePrefKey.disableFloatButton.rawValue)
                    }
                
                   
                    
                    print("Success: \(decodedData)")
                                // Handle the decoded data as needed
                    } catch let decodeError {
                                // Handle decoding error
                    print("Decoding Error: \(decodeError.localizedDescription)")
                }
                
            case .failure(let failure):
                print("ERROR \(failure)")
            }
        }
    }
    
}

class PortraitNavigationController: UINavigationController {
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }

    override var shouldAutorotate: Bool {
        return false
    }

    override var preferredStatusBarStyle: UIStatusBarStyle {
        return topViewController?.preferredStatusBarStyle ?? .default
    }

    override var childForStatusBarStyle: UIViewController? {
        return topViewController
    }
}
            
            //            AF.request(WalletRouter.getAppearance).validate().responseData { response in
            //                    switch response.result {
            //                    case .success(let data):
            //                        do {
            //                            let decodedData = try JSONDecoder().decode(ConfigResponseModel.self, from: data)
            //                            if decodedData.code == "SUCCESS"{
            //                                DefaultAppearance.shared.setAppearance(decodedData.data.appearance, isDarkMode: false)
            //
            //
            //                                let storyboard = UIStoryboard(name: "InstantPaymentMethodView", bundle: Bundle(for: B24PaymentSdk.self))
            //
            //                                if let viewController = storyboard.instantiateViewController(withIdentifier: "InstantPMView") as? InstantPMView {
            //                                    let navigationController = UINavigationController(rootViewController: viewController)
            //                                    navigationController.modalPresentationStyle = .fullScreen
            //                                    presentingViewController.present(navigationController, animated: true, completion: nil)
            //                                }
            //
            //                                print("Config data: \(decodedData)")
            //                            }else{
            //                                let lan = language?.lowercased() ?? "km"
            //                                let message = lan == "en" ? decodedData?.message : decodedData?.messageKh
            //
            //                                B24PaymentSdkHelper.errorSnackbar(
            //                                    view: presentingViewController.view,
            //                                    message: message ?? B24PaymentSdkHelper.localized(SnackBarLocalizedKeys.error.rawValue),
            //                                    forBottomSheet: false
            //                                )
            //                                }
            //                                stopLoading(view: controller.view)
            //                            }
            //
            //
            //                        } catch {
            //                            print("Decode Error: \(error)")
            //
            //                        }
            //                    case .failure(let error):
            //                        print("Request Error: \(error)")
            //                        B24PaymentSdkHelper.errorSnackbar(
            //                            view: presentingViewController.view,
            //                            message: B24PaymentSdkHelper.localized(SnackBarLocalizedKeys.error.rawValue),
            //                            forBottomSheet: false
            //                        )
            //                        stopLoading(view: controller.view)
            //
            //                    }
            //                }
            
            
            //  fetchConfig { success in
            // Stop and remove progress indicator
            //                    progressIndicator.stopAnimating()
            //                    progressIndicator.removeFromSuperview()
            //
            //                    if success {
            //                        // Navigate to the new screen
            //                        let storyboard = UIStoryboard(name: "InstantPaymentMethodView", bundle: Bundle(for: B24PaymentSdk.self))
            //                        guard let viewController = storyboard.instantiateViewController(withIdentifier: "instantPaymentMethod") as? InstantPaymentMethodViewController else {
            //                            fatalError("ViewController not found in storyboard")
            //                        }
            //                        viewController.modalPresentationStyle = .fullScreen
            //                        presentingViewController.present(viewController, animated: true, completion: nil)
            //                    } else {
            //                        // Handle failure (e.g., show an error message)
            //                        showAlert(on: presentingViewController, title: "Error", message: "Failed to fetch configuration.")
            //                    }
            
            //        if success {
            
            
            //                        let viewController = InstantPaymentMethodViewController()
            //                        viewController.modalPresentationStyle = .fullScreen
            //                        presentingViewController.present(viewController, animated: true, completion: nil)
            
            // Navigate to the new screen
            //                        let storyboard = UIStoryboard(name: "InstantPaymentMethodView", bundle: Bundle(for: B24PaymentSdk.self))
            //
            //                        if let viewController = storyboard.instantiateViewController(withIdentifier: "InstantPMView") as? InstantPMView {
            //                            let navigationController = UINavigationController(rootViewController: viewController)
            //                            navigationController.modalPresentationStyle = .fullScreen
            //                            presentingViewController.present(navigationController, animated: true, completion: nil)
            //                        }
            // let storyboard = UIStoryboard(name: "InstantPMView", bundle: Bundle(for: B24PaymentSdk.self))
            
            //                        if let viewController = storyboard.instantiateViewController(withIdentifier: "InstantPMView") as? InstantPMView {
            //                            let navigationController = UINavigationController(rootViewController: viewController)
            //                            navigationController.modalPresentationStyle = .fullScreen
            //                            presentingViewController.present(navigationController, animated: true, completion: nil)
            //                        }
            
            
            
            //                    } else {
            //                        showAlert(on: presentingViewController, title: "Error", message: "Failed to fetch configuration.")
            //                    }
            //                }
            //
            //            let storyboard = UIStoryboard(name: "AvailablePaymentMethodView", bundle: Bundle(for: B24PaymentSdk.self))
            //            guard let viewController = storyboard.instantiateViewController(withIdentifier: "AvailablePaymentMethodView") as? AvailablePaymentMethodView else {
            //                fatalError("ViewController not found in storyboard")
            //            }
            //
            //            viewController.modalPresentationStyle = .fullScreen
            //
            //            presentingViewController.present(viewController, animated: true, completion: nil)
            //     }
        
    
//    private static func fetchConfig(completion: @escaping (Bool) -> Void){
//        AF.request(WalletRouter.getAppearance).validate().responseData { response in
//                switch response.result {
//                case .success(let data):
//                    do {
//                        let decodedData = try JSONDecoder().decode(ConfigResponseModel.self, from: data)
//                        if decodedData.code == "SUCCESS"{
//                            DefaultAppearance.shared.setAppearance(decodedData.data.appearance, isDarkMode: false)
//                            print("Config data: \(decodedData)")
//                        }
//                        
//                        completion(true)
//                    } catch {
//                        print("Decode Error: \(error)")
//                        completion(false)
//                    }
//                case .failure(let error):
//                    print("Request Error: \(error)")
//                    completion(false)
//                }
//            }
//            
//    }
    
    // Helper: Create a progress indicator
//    private static func createProgressIndicator() -> UIActivityIndicatorView {
//        let progressIndicator = UIActivityIndicatorView(style: .large)
//        progressIndicator.color = .gray
//        progressIndicator.translatesAutoresizingMaskIntoConstraints = false
//        return progressIndicator
//    }
//    
    
    // Helper: Show alert for error handling
//    private static func showAlert(on viewController: UIViewController, title: String, message: String) {
//        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
//        alert.addAction(UIAlertAction(title: "OK", style: .default))
//        viewController.present(alert, animated: true, completion: nil)
//    }
//    
//}



