import React,{useState,useEffect,useRef} from 'react';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
import { globalStyles,customStyles,GetPageTheme } from "../styles/Global";
import {StatusBar,Image,TextInput,View,Text,ScrollView,TouchableOpacity,Platform,PermissionsAndroid,FlatList, Alert, Animated, AppState, Keyboard, DeviceEventEmitter} from 'react-native';
import { ReactReduxContext,connect,useSelector, useDispatch  } from 'react-redux';
import { mapStateToProps,mapDispatchToProps } from '../reducers/contextProvider';
import {notify} from '../components/notify';
import moment from 'moment';
import {UploadData2, getDownloadJson,getKPIFields,marktext1,marktext2, resizeImage, restore_ImageWithMetaData, validateNumber} from '../controller/functions';
import {get_item,set_item,clear_item} from '../components/localStorage';
import {version,sloganline,appname,testurl,db, colors_Arr, common_ImagePath,ImageFolderPath, HierarchyTbls} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {Card, Menu, Switch} from 'react-native-paper';
import {AntDesign, Entypo, FontAwesome, Fontisto, MaterialCommunityIcons} from '../components/icons';

import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import { AppTables } from '../constants/tableConstants';
import * as RNFS from 'react-native-fs';
import GradientButton from '../components/gradientButton';
import CustomModal from '../components/CustomModal';
import { ConfirmSaveAlert } from '../components/alert';
import ModalSelector from 'react-native-modal-selector'
import { CustomPicker, CustomPicker2 } from '../components/CustomPicker';
import CustomCamera from '../components/Camera';
import ImageViewer from 'react-native-image-zoom-viewer';
import DateTimePicker from '@react-native-community/datetimepicker';
import CheckBox from '@react-native-community/checkbox';

import CameraImg from '../assets/performics/camera_front_image.svg'
import MultiSelect from 'react-native-multiple-select';
import CameraImg3 from '../assets/performics/camera_tick.svg';
import CameraImg2 from '../assets/performics/camera_icon.svg';
import CameraImg5 from '../assets/image/astrickcamera.svg';
import IRLogin from '../components/IRLogin';
import { METHODS } from '../constants/methodNames';
import { SyncIRsessionsInKPI } from '../constants/uploadData';


function PromotionOneAppIR(props) { 
    const route = useRoute();
    const ST=props.StaticText || {};

    // get all theme styles acc to current theme set 
    const PageTheme=GetPageTheme(props.DarkMode,route.name);
    const customStyle=customStyles(props.DarkMode,route.name);
    const animatedChoice=useRef(new Animated.Value(0)).current;
    
    const [processing, setProcessing] = useState(true);
    const [loaderTitle, setLoaderTitle] = useState();
    const [isAdhocScreen, setIsAdhocScreen] = useState(false);
    const [storeData, setStoreData] = useState({});
    const [StoreCameraAllow, setStoreCameraAllow] = useState(true);
    const [currentMenu, setCurrentMenu] = useState({});
    const [rerenderdata, setrerenderdata]= useState(0);
    const [rerenderdata2, setrerenderdata2]= useState(0);
    const [rerenderdata3, setrerenderdata3]= useState(0);
    const [rerenderdata4, setrerenderdata4]= useState(0);
    
    const [hasUnsavedChanges,setHasUnsavedChanges] = useState(false);
    
    const [WindowData, setWindowData] = useState([]);
    const [reasons_list, setReasons_list] = useState([]);
    const [Windows, setWindows] = useState([]);

    const [refImageIndex, setrefImageIndex] = useState(0);
    const [refImageIndex2, setrefImageIndex2] = useState(0);

    const [showAlert, setShowAlert] = useState(false);
    const [zoomImageUrl, setZoomImageUrl] = useState([]);
    const [zoomImageUrl2, setZoomImageUrl2] = useState([]);

    const [show_zoomImage, setShow_zoomImage] = useState(false);
    const [show_zoomImage2, setShow_zoomImage2] = useState(false);

    const [showCamera, setShowCamera] = useState(false);
    const [getImageProps,setGetImageProps]= useState({});
    const zoomView=useRef(null);
    const zoomView2=useRef(null);

    const Show_zoomImageRef=useRef(false);
    const Show_zoomImageRef2=useRef(false);

    const [showRating, setShowRating] = useState(false);
    const [RatingQtn, setRatingQtn] = useState({});
    const [RatingWindow, setRatingWindow] = useState({});
    const [RatingOrder, setRatingOrder] = useState([]);

    const [Products, setProducts] = useState([]);
    const [DisplayList, setDisplayList] = useState([]);
    const [toRemoveId,setToRemoveId]= useState('');
    const [toRemoveItem,setToRemoveItem]= useState({});
    const [showRemoveConfirm_M,setshowRemoveConfirm_M]= useState(false);
    const [showRAllC_M,setShowRAllC_M]= useState(false);
    const [searchedItem, setSearchedItem]= useState('');
    const [globalWindows, setGlobalWindows] = useState([]);
    const [KPIFields, setKPIFields] = useState([]);
    const [showSwitchCamera,setShowSwitchCamera]= useState(false);

    const [DataCleanModal, setDataCleanModal] = useState(false);
    const [DataCleanAnim, setDataCleanAnim] = useState("");
    const [DataCleanItem, setDataCleanItem] = useState({});
    const [isPresentClean, setIsPresentClean] = useState(0);

    const [InputChange, setInputChange] = useState([]);
    const [SelectedImg, setSelectedImg] = useState('');
    const [showModal, setShowModal] = useState(false);
    const [reCapImgModalObj, setReCapImgModalObj] = useState({});
    const [showImageSaveOp, setShowImageSaveOp] = useState(true);
    const [ImgMadCount, setImgMadCount] = useState({img1:0,img2:0});
    const [FilteredPromoValues,setFilteredPromoValues]= useState([]);
    const [ShowCatWise,setShowCatWise]= useState(false);
    const [CatData,setCatData]= useState(false);
    const [ColId, setColId] = useState("");
    const [ColName, setColName] = useState("");
    const [ItemsInView,setItemsInView] = useState([]);
    const [windIRParams, setWindIRParams] = useState({});
    const [isDataUploaded, setisDataUploaded] = useState("N");

    const [showRetakeModal, setshowRetakeModal] = useState(false);
    const [retakeMData, setretakeMData] = useState({});
    const [showUploadAlert, setshowUploadAlert] = useState(false);

    const inputRefs = useRef({});
    const hasUnsavedChangesRef = React.useRef(hasUnsavedChanges);
    const WindowDataRef=React.useRef(WindowData);
    const StoreIdRef=React.useRef(null);
    const ScreenNameRef=React.useRef('');
    const PSGroupData=React.useRef(''); // Grouping data (Category/ SubCategory/ Brand ) for BG save fuunctionality with Partial Save Scenario
    const BGPSAllow=React.useRef(false);

    const WindowIRImages=useRef([]);
    const GbTempSessionId=useRef("");
    const GbTempSessionObj=useRef({});
    const sessionsToUpload = useRef([]);
    const sessionsToUploadDetails = useRef([]);
    const sessionsUploadedCount = useRef(0);
    const sessionsReceived = useRef(0);


    


    const onViewableItemsChanged = ({ viewableItems,}) => {
        // Do stuff
        console.log("onViewableItemsChanged called:")
        setItemsInView(viewableItems);
    };

    // error field states
    const [errorfield, setErrorField] = useState({});
    const [error, setError] = useState(false);
    
    const FlatLConfCallbackPairs=useRef([{viewabilityConfig:{itemVisiblePercentThreshold:50},onViewableItemsChanged}]);

    const d1=new Date();
    const d2=moment(d1).format('MM/DD/YYYY');
    
  
    useEffect(() => {
        setLoaderTitle(ST.Loading+'...')
        let params=props.route.params? props.route.params:{};
        let storeData1=params.storeData || {};
        let menu1=params.menu || {};
        let ShowCatWise1=params.ShowCatWise!=null?params.ShowCatWise:false;
        let CatData1=params.CatData!=null?params.CatData:{};
        let isAdhoc=params.isAdhoc || false;

        
        setIsAdhocScreen(isAdhoc);
        setShowCatWise(ShowCatWise1);
        setCatData(CatData1);
        setStoreData(storeData1);
        setCurrentMenu(menu1);

        let cameraAllow=storeData1.CameraAllow=='true' || storeData1.CameraAllow==1?true:false;
        setStoreCameraAllow(cameraAllow);

        let IR_Creds=props.IR_Creds!=null?JSON.parse(props.IR_Creds):[];
        let IR_CredsObj=IR_Creds.length>0?IR_Creds[0]:{};
        let PROMO_IRCreds=IR_CredsObj.Promotion!=null && IR_CredsObj.Promotion.length>0?IR_CredsObj.Promotion[0]:{};
        setWindIRParams(PROMO_IRCreds);
            
        StoreIdRef.current=storeData1.StoreId
        ScreenNameRef.current=menu1.ScreenName
        getData(storeData1,menu1,CatData1,ShowCatWise1);

        const AppStateSubscription = AppState.addEventListener('change', (pro)=>{ _handleAppStateChange(pro)});
        const removeIRListener=DeviceEventEmitter.addListener('onIRImageUpload',(data)=>{ onIRImageUpload(data,storeData1,menu1)});
        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
        
        return function cleanup() {
            AppStateSubscription.remove();
            removeIRListener.remove();
            return unsubscribe;
        };
    }, []);

    async function onIRImageUpload(data,storeData1,menu1){
        console.log('onIRImageUpload on receive',data);
        let {message,sessionId,status}=data;
        let snum=sessionsReceived.current+1;
        let su_num=sessionsUploadedCount.current;
        console.log('onreceive data',data);
        sessionsReceived.current=snum;
        let thisIR_SessObjIndex=sessionsToUploadDetails.current.findIndex(i=>i.TEMP_SESSION_ID==sessionId);
        let thisIR_SessObj=sessionsToUploadDetails.current[thisIR_SessObjIndex];
        if(status!=null && status=='200' && sessionId!=null && sessionId!=''){
            
            let UnSessionId=await IRLogin.getDataIRSession(sessionId);
            if(UnSessionId!=null && UnSessionId!=''){
                sessionsUploadedCount.current=++su_num;
                let isUpdated=await UpdateIRUploadStatus(storeData1,menu1,sessionId,UnSessionId);
                let isUploaded=await LogImageUpload(storeData1,menu1,sessionId,UnSessionId,message,status,thisIR_SessObj);
                console.log("su_num:",su_num);
                if(isUploaded){
                    console.log('Image Uploaded');
                    notify("Images Log uploaded for session:"+sessionId);
                }
                else{
                    console.log('cannot Uploaded image');
                    notify("cannot upload log for session:"+sessionId);
                }

            }
            else{
                console.log('OnReceived UnSessionId get',UnSessionId);
                notify("Cannot upload images for session:"+sessionId+". Universal Id not found");
                let isUploaded=await LogImageUpload(storeData1,menu1,sessionId,"",message,status,thisIR_SessObj);
                if(isUploaded){
                    console.log('Image Uploaded');
                    notify("Images Log uploaded for session:"+sessionId);
                }
                else{
                    console.log('cannot Uploaded image');
                    notify("cannot upload log for session:"+sessionId);
                }

            }
            
        }
        else{
            console.log('Cannot get OnReceived UnSessionId');
            notify((message!=null && message!=""?message+". ":"")+"Cannot upload images for session:"+sessionId);
            let isUploaded=await LogImageUpload(storeData1,menu1,sessionId,"",message,status,thisIR_SessObj);
            if(isUploaded){
                console.log('Image Uploaded');
                notify("Images Log uploaded for session:"+sessionId);
            }
            else{
                console.log('cannot Uploaded image');
                notify("cannot upload log for session:"+sessionId);
            }
            
          
        }
        
        console.log("check snum and su_num:",snum,su_num,sessionsToUpload.current.length);
        // if last broadcast received either uploaded or not update the processing status to false
        if(snum==sessionsToUpload.current.length){
            setProcessing(false);
            console.log('Deregister event when last received');
            IRLogin.deRegisterReceiver();
        }

        // All IR Sessions with Images Uploaded : set DataUploaded Status to U (Fully Upload)
        if(su_num==sessionsToUpload.current.length){
            setisDataUploaded("U");
            setProcessing(false);
            notify("All IR images uploaded!");
            console.log('set all uploaded true to U');
        }
        // Some Of IR Sessions with Images Uploaded but some are yet pending : set DataUploaded Status to P (Partial Upload)
        else if(su_num>0 && su_num!=sessionsToUpload.current.length){
            // setProcessing(false);
            setisDataUploaded("P");
            notify("Some IR Images are still not uploaded!");
            console.log('set all uploaded true to P');
        }
    }

    async function LogImageUpload(storeData1,menu1,TempSessionId,UnSessionId,message,status,thisIR_SessObj={}){
        let {StoreId,StoreName}=storeData1;
        const url=props.baseurl+getMethodName(METHODS.UPLOADJSON_METHOD);
        const nowTime=moment().format('HH:mm:ss');
        let ImageCount=await getImageCount(storeData1,menu1,TempSessionId);
        let {SESSION_STORECODE,SESSION_TASKNAME,SESSION_CATNAME,SESSION_PHOTOTYPE}=thisIR_SessObj;

        ////Replaced special charecter and white space
        let storeTittle = StoreName.replace(`@!%&`, '').replace(' ', '-');
        console.log("storeTittle:",storeTittle,StoreName);
 
        let obj={};
        obj['StoreId']=StoreId;
        obj['Username']=props.UserId;
        obj['VisitDate']=d2;
        obj['InTime']=nowTime;
        obj['TempSessionId']=TempSessionId;
        obj['UnSessionId']=UnSessionId;
        obj['Status']=status;
        obj['Message']=message;
        obj['ImageCount']=ImageCount;
        obj['StoreTitle']=storeTittle;
        obj['StoreCode']=SESSION_STORECODE;
        obj['TaskName']=SESSION_TASKNAME;
        obj['CategoryName']=SESSION_CATNAME;
        obj['PhotoType']=SESSION_PHOTOTYPE;
        obj['KPIType']=currentMenu.MenuName;
        obj['ScreenName']=currentMenu.ScreenName;
        obj['UploadType']="New";

                                
        let postData={};
        postData['MID']=0;
        postData['Keys']='IR_UPLOAD_LOG_MSG';
        postData['JsonData']=JSON.stringify(obj);
        postData['UserId']=props.UserId;

        console.log('postData',postData);
        
        return await UploadData2(url,postData)
        .then((res)=>{
            if(res.UploadJsonResult!=null && res.UploadJsonResult=='Success'){
                return true;
            }
            return false;
        })
        .catch((err)=>{
            console.log(err);
            return false;
        });
    }

    async function UpdateIRUploadStatus(storeData1,menu1,TempSessionId,UnSessionId){
        console.log('UpdateIRUploadStatus');
        return new Promise((resolve,reject)=>{

            let {StoreId,ChainId,StateId,StoreTypeId}=storeData1;
            db.transaction(async function (txn) {    
                // update upload status and sync status here : when files are uploaded and we have got the universal session id for that 
                let q=`Update ${AppTables.PROMO_IRUPLOAD} set UN_SESSION_ID='${UnSessionId}',UPLOAD_STATUS='1',SYNC_STATUS='Synced' where STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and TEMP_SESSION_ID='${TempSessionId}' `;
                // console.log("update IR Upload q:",q);
                await txn.executeSql(q,[],async function (txn2, txnres) { 
                    console.log('Updated IR Upload Status');
                    // console.log("update IR Upload q2:",q2);
                    let q2=`Update ${AppTables.PROMO_IR_IMAGES} set UN_SESSION_ID='${UnSessionId}' where STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and TEMP_SESSION_ID='${TempSessionId}' `;
                    await txn.executeSql(q2,[],async function (txn2, txnres2) { 
                        console.log('Updated IR Upload Images Status');
                        resolve(true);
                    },function (txnE,txnerr) { console.log(txnerr);resolve(false); },);
                    
                },function (txnE,txnerr) { console.log(txnerr);resolve(false); },);
            });  
        }).catch((Err)=>{
            console.log('Error in UpdateIRUploadStatus:',Err);
            return false;
        })
        
                    
        
    }

    
    async function getImageCount(storeData1,menu1,TempSessionId){
        let {StoreId,ChainId,StateId,StoreTypeId}=storeData1;
        console.log('storeData in getImageCount',storeData1);
        return new Promise((resolve,reject)=>{

            
            db.transaction(async function (txn) {    

                let q=`select DISTINCT TEMP_SESSION_ID,count(IMAGE1) as ImageCount from ${AppTables.PROMO_IR_IMAGES}  where STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and TEMP_SESSION_ID='${TempSessionId}'  group by TEMP_SESSION_ID `;
                console.log('q',q);
                await txn.executeSql(q,[],async function (txn2, txnres) { 
                    console.log('ImageCount rows:',txnres.rows.length);
                    if(txnres.rows.length>0){
                        let data =txnres.rows.item(0);
                        console.log('data:',data)
                        console.log('Image Count for TempSessionId:',data.ImageCount);
                        resolve(data.ImageCount);
                    }
                    else{
                        resolve(0);
                    }
                    
                },function (txnE,txnerr) { console.log(txnerr);resolve(0); },);
            });  
        }).catch((Err)=>{
            console.log('Error in getImageCount:',Err);
            return 0;
        })
        
                    
        
    }

    const _handleAppStateChange = async (nextAppState) => {
       
        if(nextAppState =='background' && hasUnsavedChangesRef.current==true){
          
           let newData = {
               storeBGData:WindowDataRef.current,
               menuName:ScreenNameRef.current,
               StoreId1:StoreIdRef.current,
               visiteDate:d2,
               BGPSAllow:BGPSAllow.current,
               PSGroupData:PSGroupData.current,
           }
           let WindowsStr= JSON.stringify(newData)
          console.log('storedjson',WindowsStr);
           await set_item('storeData',WindowsStr); 
       }
     }

    useEffect(() => {
        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
        return unsubscribe;
    }, [hasUnsavedChanges]); 
    
    useEffect(() => {
        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
        return unsubscribe;
    }, [showCamera]); 

    useEffect(() => {
        const unsubscribe=props.navigation.addListener('beforeRemove', onBeforeRemove);
        return unsubscribe;
    }, [show_zoomImage]); 
    
    function  onBeforeRemove(e){
        if(showCamera==true){
            e.preventDefault();
            setShowCamera(false);
        }
        else if(show_zoomImage==true){
            e.preventDefault();
            setShow_zoomImage(false);
        }
        else{
            if (hasUnsavedChanges==true) {
                e.preventDefault(); // Prevent default behavior of leaving the screen
                onRemoveScreen(e);
            }
            else{
               return;
            }   
        }
    }

    function BgUnsavedChanges(val){
        hasUnsavedChangesRef.current=val
        setHasUnsavedChanges(val);
    }

    function BgWindowData(val){
        WindowDataRef.current=val
        setWindowData(val);
    }

    function onRemoveScreen(e){     
        Alert.alert(
            "",
            ST.Doyoureallywanttoexitthescreen,
            [
              {
                text: ST.Cancel,
                onPress: () => {},
                style: "cancel"
              },
              { text: ST.OK, onPress: async () => {
                // setHasUnsavedChanges(false);
                BgUnsavedChanges(false)
                await clear_item('storeData')
                props.navigation.dispatch(e.data.action);} }
            ]
          );
    }
    

    async function getData(storeData1,menu1,CatData1={},ShowCatWise1=false){        
        try {   
            let {StoreId,ChainId,StateId,StoreTypeId}=storeData1;
            let {PSAllow,PSTableName}=menu1;
            PSTableName=PSTableName!=null?PSTableName:'';
            PSAllow=PSAllow!=null?PSAllow:false;

            let idCol='',nameCol='';
                
            if(PSTableName.toLowerCase()==HierarchyTbls.Master_Category.toLowerCase()){
                idCol='CategoryId',nameCol='CategoryName';
            }
            else if(PSTableName.toLowerCase()==HierarchyTbls.Master_Brand.toLowerCase()){
                idCol='BrandId',nameCol='BrandName';
            }
            else {
                idCol='SubCategoryId',nameCol='SubCategoryName';
            }
            let IdVal=CatData1[idCol];
            let NameVal=CatData1[nameCol];

            let FilteredIds=[];
            if(ShowCatWise1){
                FilteredIds=await getWindowFilterIds(idCol,IdVal,storeData1);
            }
            setFilteredPromoValues(FilteredIds);


            let AllKPIFields=await getKPIFields(menu1);
            console.log("AllKPIFields-----",AllKPIFields)
            setKPIFields(AllKPIFields);

            // set switch camera flag as defined in mapping menu flag (if exists)
            let SwitchingCameraI=AllKPIFields.findIndex(i=>i.KPIFieldName=='SwitchingCamera');
            let SwitchingCameraObj=SwitchingCameraI>=0?AllKPIFields[SwitchingCameraI]:{};
            let SwitchingCamera=SwitchingCameraI>=0?SwitchingCameraObj['KPIFieldEnable']:false;
            setShowSwitchCamera(SwitchingCamera);


            let isPromoImage1=AllKPIFields.findIndex(i=>i.KPIFieldName=='PromoImage1')
            let isPromoImage1KPIObj=isPromoImage1>=0?AllKPIFields[isPromoImage1]:{};
            let isPromoImage1MANDCOUNT=isPromoImage1>=0?isPromoImage1KPIObj['KPIMandatory']:1;
            
            let isPromoImage2=AllKPIFields.findIndex(i=>i.KPIFieldName=='PromoImage2')
            let isPromoImage2KPIObj=isPromoImage2>=0?AllKPIFields[isPromoImage2]:{};
            let isPromoImage2MANDCOUNT=isPromoImage2>=0?isPromoImage2KPIObj['KPIMandatory']:1;

            let HidePresentYesNoIndex=AllKPIFields.findIndex(i=>i.KPIFieldName=='HidePresentYesNo');
            let HidePresentYesNoObj=HidePresentYesNoIndex>=0?AllKPIFields[HidePresentYesNoIndex]:{};
            let HidePresentYesNoEn=HidePresentYesNoIndex>=0?HidePresentYesNoObj['KPIFieldEnable']:false;
            let HidePresentYesNoEnable=HidePresentYesNoEn==1 || HidePresentYesNoEn=="1" || HidePresentYesNoEn==true?true:false;

            let isOPStockEnable=AllKPIFields.findIndex(i=>i.KPIFieldName=='PromoStock_ShowOPStockProduct')
            let isOPStockEnableKPIObj=isOPStockEnable>=0?AllKPIFields[isOPStockEnable]:{};
            let isOPStockEnableFlag=isOPStockEnable>=0?isOPStockEnableKPIObj['KPIFieldEnable']:false;

            let isKPIIREnableI=AllKPIFields.findIndex(i=>i.KPIFieldName=='IR_KPIEnable')
            let isKPIIREnableObj=isKPIIREnableI>=0?AllKPIFields[isKPIIREnableI]:{};
            let isKPIIREnable=isKPIIREnableI>=0?isKPIIREnableObj['KPIFieldEnable']:false;

            let CameraIROnceOnlyIndex=AllKPIFields.findIndex(i=>i.KPIFieldName=='IR_CameraOnceOnly')
            let CameraIROnceOnlyObj=CameraIROnceOnlyIndex>=0?AllKPIFields[CameraIROnceOnlyIndex]:{};
            let CameraIROnceOnly=CameraIROnceOnlyIndex>=0?CameraIROnceOnlyObj['KPIFieldEnable']:true;
          
          

            setImgMadCount({img1:parseInt(isPromoImage1MANDCOUNT),img2:parseInt(isPromoImage2MANDCOUNT)})

            let inputChangeFlag=[],storeBGData1=[],bgStoreJson={},isBgDataExists=false;
            let windData = await get_item('storeData')
            console.log("windData in promo:",windData);
            if(windData!=null && windData!=''){
                let StoreJson = JSON.parse(windData)
                let { storeBGData,menuName,StoreId1,visiteDate }= StoreJson
                if(storeBGData.length>0 && menuName == menu1.ScreenName && StoreId1== StoreId && visiteDate==d2){
                    isBgDataExists=true;
                    storeBGData1=storeBGData;
                    bgStoreJson=StoreJson
                    BgUnsavedChanges(true)
                    BgWindowData(storeBGData)
                    // setWindowData(storeBGData);
                }
            }

            if(PSAllow){
                // if Partial save is allowed then add the currently active category or group in BG var 
                BGPSAllow.current=true;
                PSGroupData.current=CatData1;
            }
            await db.transaction(async function (txn) {        
                

                let q3=`Select PromoReasonId as ReasonId,PromoReason as Reason,IsRemarkTaken From Master_PromotionReason`;
                await txn.executeSql(q3,[],async function (txn2, txnres2) { 
                    if(txnres2.rows.length>0){
                        let arr=[];
                        for(var i=0;i<txnres2.rows.length;i++){
                            let data =txnres2.rows.item(i);
                            arr.push(data);
                            if(i==txnres2.rows.length-1){
                                setReasons_list(arr);
                            }                                
                        }
                    }
                },function (txnE,txnerr) { console.log(txnerr); },);

                //  remove old data
                // await txn.executeSql(`DELETE FROM ${AppTables.PROMO_HDR_DATA} `,[],async function (txn2, txnres) { 
                //     console.log('window hdr data deleted');
                // },function (txnE,txnerr) { console.log(txnerr); },);
                // await txn.executeSql(`DELETE FROM ${AppTables.PROMO_CHILD_DATA}  `,[],async function (txn2, txnres) { 
                //     console.log('window child data deleted');
                // },function (txnE,txnerr) { console.log(txnerr); },);
                // await txn.executeSql(`DELETE FROM ${AppTables.PROMO_IMAGES} `,[],async function (txn2, txnres) { 
                //   console.log('window images data deleted');
                // },function (txnE,txnerr) { console.log(txnerr); },);
                // await txn.executeSql(`DELETE FROM ${AppTables.PROMO_STOCK_DATA}  `,[],async function (txn2, txnres) { 
                //   console.log('window stock data deleted');
                // },function (txnE,txnerr) { console.log(txnerr); },);

                

                // check if data exists
                // let selectlist=` w.STORE_ID as StoreId,w.PROMO_HEADER_ID as PromoHeaderId,wd.PromoDefinitionId,wd.PromoId,wd.PromoName,wd.PromoDefinitionTitleEnable,wd.PromoDefinitionTitle,wd.PromoTable,wd.PromoField,wd.PromoValue,wd.ChildName,wd.PromoRefImage,wd.PromoElementCheckAssortment,wd.PromoElementStockRequired,w.IS_PRESENT as IsPresent,wd.PromoNotExistCamera,w.PROMO_NA_IMAGE as PromoNAImage,wd.PromoExistReasonEnable,wd.PromoNotExistReasonEnable,w.REASON_ID as ReasonId,w.REASON as Reason,w.REMARK as Remark,wd.NoOfSplit,wd.PromoImage1,wd.PromoImage2,wd.PromoImage1Lable,wd.PromoImage2Lable,wd.PromoImage1CameraGrid,wd.PromoImage2CameraGrid,wd.StockQtyRequired,w.SHOW_RSN_REMARK,w.REASON_REMARK`;
                // let join=` inner join Master_PromotionDefinition wd on w.PROMO_DEFINITION_ID=wd.PromoDefinitionId `;
                // let q=` Select ${selectlist} from ${AppTables.PROMO_HDR_DATA} w  ${join} where w.STORE_ID='${StoreId}'  `;
            
                
                // else pick data from masters
                // let selectlist2=` s.StoreId,w.PromoDefinitionId,w.PromoId,w.PromoName,w.PromoDefinitionTitleEnable,w.PromoDefinitionTitle,w.PromoTable,w.PromoField,w.PromoValue,w.ChildName,w.PromoRefImage,w.PromoElementCheckAssortment,w.PromoElementStockRequired,'' as IsPresent,w.PromoNotExistCamera,'' as PromoNAImage,w.PromoExistReasonEnable,w.PromoNotExistReasonEnable,'' as ReasonId,'' as Reason,w.NoOfSplit,w.PromoImage1,w.PromoImage2,w.PromoImage1Lable,w.PromoImage2Lable,w.PromoImage1CameraGrid,w.PromoImage2CameraGrid,w.StockQtyRequired`;
                // let join2=` inner join Mapping_StorePromotion s on w.PromoDefinitionId=s.PromoDefinitionId  `;
                // let q2=` Select ${selectlist2} from Master_PromotionDefinition w  ${join2} where s.StoreId='${StoreId}'  `;
                
               

                // Load All Promo Definitions from masters and get data for it if any
                let FilterIdsJoin=FilteredIds.length>0?FilteredIds.join(','):'';
                let selectlist2=` s.StoreId,wd.PROMO_HEADER_ID as PromoHeaderId,w.PromoRefImage,w.PromoRefImagePopUp,w.PromoDefinitionId,w.PromoId,w.PromoName,w.PromoDefinitionTitleEnable,w.PromoDefinitionTitle,w.PromoTable,w.PromoField,w.PromoValue,w.ChildName,w.PromoRefImage,w.PromoElementCheckAssortment,w.PromoElementStockRequired,IFNULL(wd.IS_PRESENT,'') as IsPresent,w.PromoNotExistCamera,IFNULL(wd.PROMO_NA_IMAGE,'') as PromoNAImage,w.PromoExistReasonEnable,w.PromoNotExistReasonEnable,IFNULL(wd.REASON_ID ,'') as ReasonId,IFNULL(wd.REASON,'') as Reason,w.NoOfSplit,w.PromoImage1,w.PromoImage2,w.PromoImage1Lable,w.PromoImage2Lable,w.PromoImage1CameraGrid,w.PromoImage2CameraGrid,w.StockQtyRequired,wd.SHOW_RSN_REMARK,wd.REASON_REMARK`;
                // let selectlist=` w.STORE_ID as StoreId,w.PROMO_HEADER_ID as PromoHeaderId,wd.PromoDefinitionId,wd.PromoId,wd.PromoName,wd.PromoDefinitionTitleEnable,wd.PromoDefinitionTitle,wd.PromoTable,wd.PromoField,wd.PromoValue,wd.ChildName,wd.PromoRefImage,wd.PromoElementCheckAssortment,wd.PromoElementStockRequired,w.IS_PRESENT as IsPresent,wd.PromoNotExistCamera,w.PROMO_NA_IMAGE as PromoNAImage,wd.PromoExistReasonEnable,wd.PromoNotExistReasonEnable,w.REASON_ID as ReasonId,w.REASON as Reason,w.REMARK as Remark,wd.NoOfSplit,wd.PromoImage1,wd.PromoImage2,wd.PromoImage1Lable,wd.PromoImage2Lable,wd.PromoImage1CameraGrid,wd.PromoImage2CameraGrid,wd.StockQtyRequired,w.SHOW_RSN_REMARK,w.REASON_REMARK`;
                let join3=` Left outer join ${AppTables.PROMO_HDR_DATA} wd on w.PromoDefinitionId=wd.PROMO_DEFINITION_ID and wd.STORE_ID='${StoreId}' and VISIT_DATE='${d2}'  `;
                let join2=` inner join Mapping_StorePromotion s on w.PromoDefinitionId=s.PromoDefinitionId  `;
                let q2=` Select ${selectlist2} from Master_PromotionDefinition w  ${join2} ${join3} where s.StoreId='${StoreId}'  `;
                if(ShowCatWise1==true){
                    q2+=` and  PromoValue in (${FilterIdsJoin}) `;
                }
                q2+=`order by w.PromoDefSequence `;

                console.log('q2:',q2);
                await txn.executeSql(q2,[],async function (txn2, txnres2) { 
                    console.log('Promotion items loaded with added data',txnres2.rows.length);
                    if(txnres2.rows.length>0){
                        let arr=[];let images=[],allWindowsData=[]

                        for(var i=0;i<txnres2.rows.length;i++){
                            let data=txnres2.rows.item(i);
                            // console.log('data:',data.PromoDefinitionId,data.StockQtyRequired);
                            let isPresent=(HidePresentYesNoEnable?1:0);
                            if(isBgDataExists){
                                let storeBgIndex=storeBGData1.findIndex(i=>i.PromoId==data.PromoId && i.PromoDefinitionId==data.PromoDefinitionId)
                                let storeBgObj=storeBgIndex>=0?storeBGData1[storeBgIndex]:{};
                                isPresent=HidePresentYesNoEnable?1:(storeBgObj.isPresent=='1' || storeBgObj.isPresent==1?1:0);
                                let animatedChoice=new Animated.Value(isPresent);
                                data.animatedChoice=animatedChoice;
                            }else{
                                isPresent= (HidePresentYesNoEnable?1:(data.IsPresent=='1' || data.IsPresent==1?1:0));
                                let animatedChoice=new Animated.Value(isPresent);
                                data.animatedChoice=animatedChoice;
                            }
                            let animatedHeight = new Animated.Value(450);
                            data.animatedHeight=animatedHeight
                            
                            data.NoOfSplit=parseInt(data.NoOfSplit);
                            
                            let NoOfSplit=data.NoOfSplit;
                            let isStockReq=data.PromoElementStockRequired=='true' || data.PromoElementStockRequired==1?1:0;
                            
                            let imgObj={imgIndex:(i+1),url: data.PromoRefImage, props: {}}
                            images.push(imgObj);

                            let WindowSplits =  await getWindowSplits(NoOfSplit,data,storeData1,menu1,isPromoImage1MANDCOUNT,isPromoImage2MANDCOUNT);
                            let IRImages=[],IRImages1=[],zoomIRImages=[],zoomIRImages1=[];
                            if(isKPIIREnable && !isBgDataExists){ //perform action only if IRImages flag is enable for this KPI and if bg data does not exists
                                if(CameraIROnceOnly && i==0){// get IR images for all KPI at once if CameraIROnceOnly enabled
                                    let IRImgResObj=await getIRImages({},storeData1,menu1,"2");
                                    IRImages1=IRImgResObj!=null && IRImgResObj["allImages"]!=null?IRImgResObj["allImages"]:[];
                                    zoomIRImages1=IRImgResObj!=null && IRImgResObj["zoomIRImages"]!=null?IRImgResObj["zoomIRImages"]:[];
                                    // setWindowIRImages(IRImages);
                                    WindowIRImages.current=IRImages1;
                                    setZoomImageUrl2(zoomIRImages1);
                                }
                                else if(!CameraIROnceOnly){// get IR images for each window if CameraIROnceOnly is not enabled
                                    let IRImgResObj=await getIRImages(data,storeData1,menu1,"1");
                                    IRImages=IRImgResObj!=null && IRImgResObj["allImages"]!=null?IRImgResObj["allImages"]:[];
                                    zoomIRImages=IRImgResObj!=null && IRImgResObj["zoomIRImages"]!=null?IRImgResObj["zoomIRImages"]:[];
                                }
                            }

                            let WQr =  await getWindowQuestions(data,storeData1,isPresent,menu1);
                            let WindowQuestions = WQr['WindowQuestions'] || [];
                            let WindowQA= WQr['WindowQA'] || {};
                            let WSd= isStockReq==true ? await getWindowStockData(data,storeData1,isPresent,isOPStockEnableFlag) : {'WStocks':[],'WStocksData':[]};
                            let WStocks=WSd['WStocks'] || [];
                            let WStocksData=WSd['WStocksData'] || [];
                            let isAllChecked=WSd['isAllChecked']!=null?WSd['isAllChecked']:0;

                            let isNAImageAvl=data.PromoNotExistCamera=='true' || data.PromoNotExistCamera==1?1:0;
                            let NAImage1=isNAImageAvl==1 && data.PromoNAImage!=null?data.PromoNAImage:'';
                            let NAImage1Path=NAImage1!=''?'file://'+ImageFolderPath+menu1.ScreenName+"/"+NAImage1:'';

                            let showRsnRemark=((data.SHOW_RSN_REMARK=='1' || data.SHOW_RSN_REMARK==1 )?true:false);
                            
                            let windowDataObj={'PromoId':data.PromoId, 'PromoDefinitionId':data.PromoDefinitionId,'WindowSplits':WindowSplits,'WindowQA':WindowQA,'WStocksData':WStocksData,'NAImage1':NAImage1,'NAImage1Path':NAImage1Path,'ReasonId':data.ReasonId,'Reason':data.Reason,'isPresent':isPresent,'isAllSKUChecked':isAllChecked,'remark':(data.Remark!=null?data.Remark:''),'showOtherText':showRsnRemark,'RemarkText':(data.REASON_REMARK || '')};
                            if(isKPIIREnable && !CameraIROnceOnly && !isBgDataExists){ // If IR enable and IR camera is shown for each window and if bg data does not exists
                                windowDataObj['IRImages']=IRImages;
                                windowDataObj['zoomIRImages'] =zoomIRImages;
                                windowDataObj['TempSessionId']=data.TempSessionId;
                                windowDataObj['Sess_StoreCode']=data.Sess_StoreCode;
                                windowDataObj['Sess_TaskName']=data.Sess_TaskName;
                                windowDataObj['Sess_CatName']=data.Sess_CatName;
                                windowDataObj['Sess_PhotoType']=data.Sess_PhotoType;
                                
                                
                                if(data.UploadStatus=='1' && isDataUploaded!='P' && isDataUploaded!='U'){
                                    console.log('cat hdr image upload success: P');
                                    // stop editing if any image is uploaded 
                                    setisDataUploaded("P");
                                }
    
                                if(data.UploadStatus!='1'){
                                    // check if any image is not uploaded then set uploaded status to U
                                    isfullyUploaded=false;
                                }
                                
                            }
    
                            data['WindowQuestions']=WindowQuestions;
                            data['WindowStocks']=WStocks;                


                            let changesFlag = {PromoId:data.PromoId, PromoDefinitionId: data.PromoDefinitionId, Flag:(data.PromoHeaderId!=null?true:false)}
                            inputChangeFlag.push(changesFlag)

                            arr.push(data);
                            allWindowsData.push(windowDataObj);
                            if(i==txnres2.rows.length-1){
                                let { menuName,StoreId1,visiteDate }=bgStoreJson
                                if(!isBgDataExists){
                                    BgWindowData(allWindowsData);
                                }

                                if(isKPIIREnable){// set IR Images Upload Status if KPI IR flag is enabled
                                    if(CameraIROnceOnly){ // Camera for each window is not enabled
                                        let isChecked=await getUploadIRStatus(storeData1,menu1);
                                    }
                                    else if(!CameraIROnceOnly && isfullyUploaded){ // Stop Upload and Editing both when fully uploaded, Case: if Camera for each window is enabled
                                        setisDataUploaded('U');
                                    }
                                }

                                setInputChange(inputChangeFlag)
                                setWindows(arr);
                                setGlobalWindows(arr);
                                setZoomImageUrl(images);
                                setProcessing(false);
                            }                                
                        }
                    }
                    else{
                        setProcessing(false);
                        notify('No Data found');
                    }
                    // else{
                    
                    //     await txn.executeSql(q2,[],async function (txn2, txnres2) { 
                    //     console.log('def data:',txnres2.rows.length);
                    //         if(txnres2.rows.length>0){
                    //             let arr=[],images=[],allWindowsData=[],inputChangeFlag=[],storeBGData1=[],bgStoreJson={};
                    //             let windData = await get_item('storeData')
                    //             if(windData!=null && windData!=''){
                    //                 let StoreJson = JSON.parse(windData)
                    //                 let { storeBGData,menuName,StoreId1,visiteDate }= StoreJson
                    //                 storeBGData1=storeBGData;
                    //                 console.log("storeBGData1 in promo: ",StoreJson)
                    //                 bgStoreJson=StoreJson
                    //                 if(storeBGData.length>0 && menuName == menu1.ScreenName && StoreId1== StoreId && visiteDate==d2){
                    //                     BgUnsavedChanges(true)
                    //                     BgWindowData(storeBGData)
                    //                     // setWindowData(storeBGData);
                    //                 }
                    //             }                            
                    //             // for(var i=0;i<txnres2.rows.length;i++){
                    //             for(var i=0;i<txnres2.rows.length;i++){
                    //                 let data=txnres2.rows.item(i);
                                    
                    //                 let storeBgIndex=storeBGData1.findIndex(i=>i.PromoId==data.PromoId && i.PromoDefinitionId==data.PromoDefinitionId)
                    //                 let storeBgObj=storeBgIndex>=0?storeBGData1[storeBgIndex]:{};

                    //                 let bgisPresent=storeBgObj.isPresent
                                    
                    //                 if(bgisPresent=='1'||bgisPresent==1){
                    //                     let animatedChoice=new Animated.Value(1);
                    //                     data.animatedChoice=animatedChoice;
                    //                 }else{
                    //                     let animatedChoice=new Animated.Value((HidePresentYesNoEnable?1:0));
                    //                     data.animatedChoice=animatedChoice;
                    //                 }

                    //                 data.NoOfSplit=parseInt(data.NoOfSplit);
                    //                 let isStockReq=data.PromoElementStockRequired=='true' || data.PromoElementStockRequired==1?1:0;
                            
                    //                 let imgObj={imgIndex:(i+1),url: data.PromoRefImage, props: {}}
                    //                 let WindowSplits =  [];
                    //                 let img1Req=false;
                    //                 let img2Req=false;
                    //                 for(var s=0;s<data.NoOfSplit;s++){
                    //                     let ci=s+1;
                    //                     if(ci<=isPromoImage1MANDCOUNT){
                    //                         img1Req=true;
                    //                     }else{
                    //                         img1Req=false;
                    //                     }

                    //                     if(ci<=isPromoImage2MANDCOUNT){
                    //                         img2Req=true;
                    //                     }else{
                    //                         img2Req=false;
                    //                     }
                    //                     let obj={'Image1Name':'','Image1':'','Image2Name':'','Image2':'', img1Required:img1Req, img2Required:img2Req };
                    //                     WindowSplits.push(obj);
                    //                 }

                    //                 let WQr =  await getWindowQuestions(data,storeData1,false,menu1);
                    //                 let WindowQuestions = WQr['WindowQuestions'] || [];
                    //                 let WindowQA= WQr['WindowQA'] || {};
                    //                 let WSd= isStockReq==true ? await getWindowStockData(data,storeData1,false,isOPStockEnableFlag) : {'WStocks':[],'WStocksData':[]};
                            
                    //                 let WStocks=WSd['WStocks'] || [];
                    //                 let WStocksData=WSd['WStocksData'] || [];
                    //                 let isAllChecked=WSd['isAllChecked']!=null?WSd['isAllChecked']:0;

                    //                 let windowDataObj={'PromoId':data.PromoId, 'PromoDefinitionId':data.PromoDefinitionId,'WindowSplits':WindowSplits,'WindowQA':WindowQA,'WStocksData':WStocksData,'isAllSKUChecked':isAllChecked,'isPresent':HidePresentYesNoEnable?1:0};
                    //                 data['WindowQuestions']=WindowQuestions;
                    //                 data['WindowStocks']=WStocks;

                                
                    //                 let changesFlag = {PromoId:data.PromoId, PromoDefinitionId: data.PromoDefinitionId, Flag:false}

                    //                 inputChangeFlag.push(changesFlag)

                    //                 arr.push(data);
                    //                 allWindowsData.push(windowDataObj);
                    //                 if(i==txnres2.rows.length-1){
                    //                     let { menuName,StoreId1,visiteDate }=bgStoreJson
                    //                     if(storeBGData1!=null && storeBGData1!='' && menuName == menu1.ScreenName && StoreId1== StoreId && visiteDate==d2){
                    //                         if(storeBGData1.length<=0){
                    //                             // setWindowData(allWindowsData);
                    //                             BgWindowData(allWindowsData);
                    //                         }
                    //                     }else{
                    //                         // setWindowData(allWindowsData);
                    //                         BgWindowData(allWindowsData);   
                    //                     }

                    //                     setInputChange(inputChangeFlag)
                    //                     setWindows(arr);
                    //                     setGlobalWindows(arr);
                    //                     images.push(imgObj);
                    //                     setZoomImageUrl(images);
                    //                     setProcessing(false);
                    //                 }                                
                    //             }
                    //         }
                    //         else{
                    //             setProcessing(false);
                    //         }
                    //     },function (txnE,txnerr) { console.log(txnerr);setProcessing(false); },);
                    // }
                },function (txnE,txnerr) { console.log(txnerr);setProcessing(false); },);

            });          
        } catch (err) {
          console.log(err);          
        }        
    }

    
        // Start Upload for IR images 
        async function UploadIRSessions(){
            setshowUploadAlert(false);
            sessionsToUpload.current=[];
            sessionsReceived.current=0;
            sessionsUploadedCount.current=0;
          
            try{
                let {StoreId}=storeData;
                setLoaderTitle('Uploading Images...');
                setProcessing(true);
    
                // Global Upload function
                // Sync Status for IR images
                // From Infilect SDK 1.3.6 - The Images are uploading on realtime bases i.e. As the images are clicked by user the Images are getting uploaded to infilect server.
                // In this case call below func to check the status of images that is already being uploaded by Real Time processing
                let sync_result=await SyncIRsessionsInKPI(props,storeData,AppTables.PROMO_IRUPLOAD,AppTables.PROMO_IR_IMAGES,true,currentMenu);
                let {isUploadStarted,AllDataUploaded,noDataFound,success,sessionList,sessionListWithDetails}=sync_result;
                console.log("Sync Resp sync_result:",sync_result);
                if(!success){
                    notify('Cannot Upload Data! Something went wrong.');
                    setProcessing(false);
                }
                else{
                    if(noDataFound){
                        notify('No session to upload!');
                        setisDataUploaded('U');
                        setProcessing(false);
                    }
                    else{
                        if(!isUploadStarted && AllDataUploaded){
                            notify('All images synced! No session to upload.');
                            setisDataUploaded('U');
                            setProcessing(false);
                        }else if(isUploadStarted){
                            sessionsToUpload.current=sessionList;
                            sessionsToUploadDetails.current=sessionListWithDetails;
                            console.log("UploadStarted");
                        }
                    }
                }
            }catch(e){
                console.log('Uploading Issue:',e);
                setProcessing(false);
            }
            
            
        }

    async function getIRImages(window,storeData1,menu1,type="1"){
        // let allImages=[];
        let res={allImages:[],zoomIRImages:[]}

        return new Promise((resolve,reject)=>{
            
            db.transaction(async function (txn) {

                let q=`select IMAGE1 as Image1 from ${AppTables.PROMO_IR_IMAGES} where STORE_ID='${storeData1.StoreId}' and MENU_ID='${menu1.MenuId}' and VISIT_DATE='${d2}'`;
                q+=type=='1'?` and PROMO_HEADER_ID='${window.PromoHeaderId}'`:'';
               
                await txn.executeSql(q,[],async function (txn2, txnres2) { 
                    console.log('get IRImages count ',txnres2.rows.length);
                    let arr=[],arr2=[];
                    if(txnres2.rows.length>0){
                        for(var i=0;i<txnres2.rows.length;i++){
                            let data =txnres2.rows.item(i);
                            let obj={'ImagePath':data.Image1};
                            arr.push(obj);
                            
                            let imgObj={imgIndex:(i+1),url: data.Image1, props: {}}
                            arr2.push(imgObj);
                            
                            if(i==txnres2.rows.length-1){
                                res['allImages']=arr
                                res['zoomIRImages']=arr2
                                resolve(res)
                            }                                
                        }
                    }
                    else{
                        resolve(res)
                    }
                },function (txnE,txnerr) { console.log(txnerr); resolve(res) },);
            });  
        }).then((val)=>{
            return val
        }).catch((err)=>{
            console.log(err);
            return res;
        });
    }

    async function getWindowFilterIds(idCol,IdVal,storeData1){
        let AllIds=[];
        let {StoreId}=storeData1
        return new Promise((resolve,reject)=>{
            
            db.transaction(async function (txn) {
                let join=` inner join Mapping_StorePromotion s on w.PromoDefinitionId=s.PromoDefinitionId  `;
                let q=`Select w.* from Master_PromotionDefinition w ${join} where s.StoreId='${StoreId}' `;
                await txn.executeSql(q,[],async function (txn2, txnres) { 
                    if(txnres.rows.length>0){
                        let Wind_data =txnres.rows.item(0);
                        let {PromoValue,PromoTable}=Wind_data;
                        PromoTable=PromoTable!=null?PromoTable:'';

                        let filterIdsCol='',filterNamesCol='';
                        if(PromoTable.toLowerCase()==HierarchyTbls.Master_Category.toLowerCase()){
                            filterIdsCol='CategoryId',filterNamesCol='CategoryName';
                        }
                        else if(PromoTable.toLowerCase()==HierarchyTbls.Master_Brand.toLowerCase()){
                            filterIdsCol='BrandId',filterNamesCol='BrandName';
                        }
                        else if(PromoTable.toLowerCase()==HierarchyTbls.Master_Product.toLowerCase()){
                            filterIdsCol='ProductId',filterNamesCol='ProductName';
                        }
                        else{
                            filterIdsCol='SubCategoryId',filterNamesCol='SubCategoryName';
                        }
                    
                        let FIdsQ=`Select p.${filterIdsCol},p.${filterNamesCol} from Product_Master p where (p.${idCol}='${IdVal}' or p.${idCol}= ${IdVal}) `;
                       
                        await txn.executeSql(FIdsQ,[],async function (txn2, txnres2) {
                            if(txnres.rows.length>0){ 
                                for(var i=0;i<txnres2.rows.length;i++){
                                    let data =txnres2.rows.item(i);
                                    let id_value=data[filterIdsCol];
                                    AllIds.push(id_value);
                                    if(i==txnres2.rows.length-1){
                                        resolve(AllIds)
                                    }                                
                                }
                            }
                            else{
                                resolve([]);
                            }
                        },function (txnE,txnerr) { console.log(txnerr); resolve(AllIds) });

                        
                    }
                    else{
                        resolve(AllIds)
                    }
                },function (txnE,txnerr) { console.log(txnerr); resolve(AllIds) },);
            });  
        }).then((val)=>{
            return val
        }).catch((err)=>{
            console.log(err);
            return AllIds;
        });
    }

    async function focusToNext(WindowStocks,windowIndex,stockProd,index){
        console.log('focusToNext is call');
        
        if(index==WindowStocks.length-1){
            return;
        }
        try{
            console.log('next 1 call','input1_'+WindowStocks[index+1].PromoDefinitionId+'_'+WindowStocks[index+1].PromoStockDefinitionId)
            let refIn2=inputRefs.current['input1_'+WindowStocks[index+1].PromoDefinitionId+'_'+WindowStocks[index+1].PromoStockDefinitionId];
            
            if(refIn2!=null){
                refIn2.focus();
            }
        }
        catch(err){
            console.log(err);
        }

    }

    async function getUploadIRStatus(storeData1,menu1){
        let allImages=[];
        let {StoreId} =storeData1;
        return new Promise((resolve,reject)=>{
            db.transaction(async function (txn) { 

                // For CameraIROnceOnly enabled condition only one TempSessionId will be genrated per KPI
                let q=` SELECT Distinct TEMP_SESSION_ID as TempSessionId,UN_SESSION_ID as UploadSessionId,UPLOAD_STATUS as UploadStatus,SYNC_STATUS as SyncStatus,SESSION_STORECODE as Sess_StoreCode,SESSION_TASKNAME as Sess_TaskName,SESSION_CATNAME as Sess_CatName,SESSION_PHOTOTYPE as Sess_PhotoType FROM ${AppTables.PROMO_IRUPLOAD} where STORE_ID='${StoreId}' and MENU_ID='${menu1.MenuId}' and VISIT_DATE='${d2}'  `;
                await txn.executeSql(q,[],async function (txn2, txnres) { 
                    if(txnres.rows.length>0){
                        let isfullyUploaded=true;
                        //No Loop required, As For CameraIROnceOnly enabled condition only one TempSessionId will be genrated per KPI
                        let data =txnres.rows.item(0);
                        let {Sess_StoreCode,Sess_TaskName,Sess_CatName,Sess_PhotoType}=data;
                        if(data.UploadStatus=='1' && isDataUploaded!='P' && isDataUploaded!='U'){
                            console.log('getUploadIRStatus success: U');
                            // Stop Upload and Editing both when fully uploaded
                            setisDataUploaded("U");
                        }
                        // setGbTempSessionId(data.TempSessionId);
                        GbTempSessionId.current=data.TempSessionId;
                        let obj={Sess_StoreCode,Sess_TaskName,Sess_CatName,Sess_PhotoType};
                        GbTempSessionObj.current=obj;
                        resolve(true);
                    }
                    else{
                        resolve(true);
                    }
                },function (txnE,txnerr) { console.log(txnerr); resolve(false); },);
            });        
        }).catch((err)=>{
            return false;
        })
    }

    async function getWindowSplits(NoOfSplit,window,storeData1,menu1,isPromoImage1MANDCOUNT,isPromoImage2MANDCOUNT){
        let WindowSplits_def=  [];
        // for(var s=0;s<NoOfSplit;s++){
        //     let obj={'Image1Name':'','Image1':'','Image2Name':'','Image2':''};
        //     WindowSplits_def.push(obj);
        // }

        let img1Req=false,img2Req=false;
        for(var s=0;s<NoOfSplit;s++){
            let ci=s+1;
            img1Req=ci<=isPromoImage1MANDCOUNT?true:false;
            img2Req=ci<=isPromoImage2MANDCOUNT?true:false;
            let obj={'Image1Name':'','Image1':'','Image2Name':'','Image2':'', 'img1Required':img1Req, 'img2Required':img2Req };
            WindowSplits_def.push(obj);
        }
        return new Promise((resolve,reject)=>{
            
            db.transaction(async function (txn) {

                let q=`select * from ${AppTables.PROMO_IMAGES} where PROMO_HEADER_ID='${window.PromoHeaderId}' and  STORE_ID='${storeData1.StoreId}' `;
               
                await txn.executeSql(q,[],async function (txn2, txnres2) { 
                    console.log("images saved len:",txnres2.rows.length);
                    if(txnres2.rows.length>0){
                        let arr=[];
                        for(var i=0;i<txnres2.rows.length;i++){
                            let data =txnres2.rows.item(i);
                            console.log(data.PROMO_HEADER_ID)
                            let isImage1=window.PromoImage1=='true' || window.PromoImage1==1?1:0;
                            let isImage2=window.PromoImage2=='true' || window.PromoImage2==1?1:0;
                            img1Req=i<=isPromoImage1MANDCOUNT?true:false;
                            img2Req=i<=isPromoImage2MANDCOUNT?true:false;
                            let Image1=isImage1==1 && data.IMAGE1!=null && data.IMAGE1!=''?'file://'+ImageFolderPath+menu1.ScreenName+"/"+data.IMAGE1:'';
                            let Image2=isImage2==1 && data.IMAGE2!=null && data.IMAGE2!=''?'file://'+ImageFolderPath+menu1.ScreenName+"/"+data.IMAGE2:'';
                            let obj={'Image1Name':data.IMAGE1,'Image1':Image1,'Image2Name':data.IMAGE2,'Image2':Image2, 'img1Required':img1Req, 'img2Required':img2Req};
                            arr.push(obj);

                            if(i==txnres2.rows.length-1){
                                resolve(arr)
                            }                                
                        }
                    }
                    else{
                        resolve(WindowSplits_def)
                    }
                },function (txnE,txnerr) { console.log(txnerr); resolve(WindowSplits_def) },);
            });  
        }).then((val)=>{
            return val
        }).catch((err)=>{
            console.log(err);
            return WindowSplits_def;
        });
    }

    async function getWindowQuestions(window,storeData1,isInserted1=false,menu1){
        let obj={'WindowQA':{},'WindowQuestions':[]}
        return new Promise((resolve,reject)=>{
            
            db.transaction(async function (txn) {
                var q='',selectlist='',join='',join2='',join3='';
                // if(isInserted==true){
                //     selectlist=` DISTINCT  q.QUESTION_ID as PromoQuestionId,q.QUESTION_CODE as PromoQuestionCode,wq.PromoQuestionName,wq.QuestionType,wq.PromoqShowCamera,wq.PromoqCameraMandatory,wq.PromoqLengthValidationRequired,wq.PromoqMinimumChar,wq.PromoqMaximumChar,wq.PromoqDecimalPoint,wq.PromoqDateRangeMin,wq.PromoqDateRangeMax,wq.PromoqVoiceLengthInMinutes,wq.PromoqDefaultQuestionEnable,q.ANSWER as Answer,q.ANSWER_ID as AnswerId,q.MULTI_OPTIONS_IDS as multi_op_ids,q.IMAGE_ALLOW1 as PromoaShowCamera,q.IMAGE1 as Image1,q.IS_DISABLED as IsDisabled  `;
                //     join2=` inner join Mapping_PromotionQuestion mq on mq.PromoQuestionId=wq.PromoQuestionId `;
                //     join=` inner join Master_PromotionQuestion wq on wq.PromoQuestionId=q.QUESTION_ID `;
                //     q=`select ${selectlist} from ${AppTables.PROMO_CHILD_DATA} q ${join} ${join2} where q.STORE_ID='${storeData1.StoreId}' and q.PROMO_DEFINITION_ID='${window.PromoDefinitionId}' and q.PROMO_ID='${window.PromoId}' order by wq.PromoQuestionSequence  `;
                    
                // }
                // else{
                //     selectlist=` DISTINCT  wq.PromoQuestionId,wq.PromoQuestionCode,wq.PromoQuestionName,wq.QuestionType,wq.PromoqShowCamera,wq.PromoqCameraMandatory,wq.PromoqLengthValidationRequired,wq.PromoqMinimumChar,wq.PromoqMaximumChar,wq.PromoqDecimalPoint,wq.PromoqDateRangeMin,wq.PromoqDateRangeMax,wq.PromoqVoiceLengthInMinutes,wq.PromoqDefaultQuestionEnable `;
                //     join=` inner join Mapping_PromotionQuestion mq on mq.PromoQuestionId=wq.PromoQuestionId `;
                //     q=`select ${selectlist} from Master_PromotionQuestion wq  ${join} where mq.PromoDefinitionId='${window.PromoDefinitionId}' order by wq.PromoQuestionSequence  `;
                // }


                //get data from master and filled data for that particular qtn if any 
                // selectlist=` DISTINCT  q.QUESTION_ID as PromoQuestionId,q.QUESTION_CODE as PromoQuestionCode,wq.PromoQuestionName,wq.QuestionType,wq.PromoqShowCamera,wq.PromoqCameraMandatory,wq.PromoqLengthValidationRequired,wq.PromoqMinimumChar,wq.PromoqMaximumChar,wq.PromoqDecimalPoint,wq.PromoqDateRangeMin,wq.PromoqDateRangeMax,wq.PromoqVoiceLengthInMinutes,wq.PromoqDefaultQuestionEnable,q.ANSWER as Answer,q.ANSWER_ID as AnswerId,q.MULTI_OPTIONS_IDS as multi_op_ids,q.IMAGE_ALLOW1 as PromoaShowCamera,q.IMAGE1 as Image1,q.IS_DISABLED as IsDisabled  `;
                selectlist=` DISTINCT  wq.PromoQuestionId,wq.PromoQuestionCode,wq.PromoQuestionName,wq.QuestionType,wq.PromoqShowCamera,wq.PromoqCameraMandatory,wq.PromoqLengthValidationRequired,wq.PromoqMinimumChar,wq.PromoqMaximumChar,wq.PromoqDecimalPoint,wq.PromoqDateRangeMin,wq.PromoqDateRangeMax,wq.PromoqVoiceLengthInMinutes,wq.PromoqDefaultQuestionEnable,(CASE WHEN q.QUESTION_ID is not null THEN 1 ELSE 0 END) isInserted,q.ANSWER as Answer,q.ANSWER_ID as AnswerId,q.MULTI_OPTIONS_IDS as multi_op_ids,q.IMAGE_ALLOW1 as PromoaShowCamera,q.IMAGE1 as Image1,q.IS_DISABLED as IsDisabled   `;
                join3=` left outer join ${AppTables.PROMO_CHILD_DATA} q on q.QUESTION_ID=wq.PromoQuestionId  and q.STORE_ID='${storeData1.StoreId}' and q.PROMO_DEFINITION_ID='${window.PromoDefinitionId}' and q.PROMO_ID='${window.PromoId}'`;
                join=` inner join Mapping_PromotionQuestion mq on mq.PromoQuestionId=wq.PromoQuestionId `;
                q=`select ${selectlist} from Master_PromotionQuestion wq  ${join} ${join3} where mq.PromoDefinitionId='${window.PromoDefinitionId}' order by wq.PromoQuestionSequence  `;

                

                await txn.executeSql(q,[],async function (txn2, txnres2) { 
                    
                    if(txnres2.rows.length>0){
                        let arr=[];
                        let wqa_obj={};
                        for(var i=0;i<txnres2.rows.length;i++){
                            let data =txnres2.rows.item(i);
                            let {isInserted}=data;
                           
                            let answers=[];
                            data.PromoqDefaultQuestionEnable=data.PromoqDefaultQuestionEnable==1 || data.PromoqDefaultQuestionEnable=='true'?true:false;
                            if(isInserted){
                                data['isDisabled']=data.IsDisabled==1 || data.IsDisabled=="1"?true:false;
                            }
                            else{
                                data['isDisabled']=!data.PromoqDefaultQuestionEnable;
                            }
                            
                              if(data.QuestionType=='Multi choice list' || data.QuestionType=='Single choice list' || data.QuestionType=='Rating'){
                                  answers=await getWindowAnswers(data);
                                  if(data.QuestionType=='Rating'){
                                      data.showRating=false;
                                  }
                              }
                              else if(data.QuestionType=='Date'){
                                  data.showDatePicker=false;
                              }
                              data['Answers']=answers;
      
                              let id_key=data.PromoQuestionId+'_AnswerId'; 
                              let ans_key=data.PromoQuestionId+'_Answer'; 
                              let multi_key=data.PromoQuestionId+'_MultiOption';
                              let date_key=data.PromoQuestionId+'_Date';
                              let img_key=data.PromoQuestionId+'_ImagePath1';
                              let imgname_key=data.PromoQuestionId+'_ImageName1';
                              let rating_key=data.PromoQuestionId+'_Rating'; 
                              
      
                              let showImageTag=(data.PromoqShowCamera=='true' || data.PromoqShowCamera==1) ;
      
                              data.AnswerId!=null?wqa_obj[id_key]=data.AnswerId:'';
                              data.Answer!=null?wqa_obj[ans_key]=data.Answer:'';

                              
                              let selansid=data.AnswerId!=null?data.AnswerId:'';
                              if(data.QuestionType=='Multi choice list' && selansid!='' && data.multi_op_ids!=null){
                                  selansid=data.multi_op_ids?data.multi_op_ids.split(','):[];
                                  wqa_obj[multi_key]=data.multi_op_ids;
                              }
      
                              if((data.QuestionType=='Single choice list' || data.QuestionType=='Multi choice list' ) && selansid!='' && selansid!=null){
                                  if (data.Answers && data.Answers.length>0){
                                      for(var k=0;k<data.Answers.length;k++){
                                          let ansss=data.Answers[k];
                                          let isandImgAl=(ansss.PromoaShowCamera==1 || ansss.PromoaShowCamera=='true');
                                          if(data.QuestionType=='Single choice list' && (isandImgAl && ansss.AnswerId==selansid)){
                                              showImageTag=true;
                                          }
                                          else if(data.QuestionType=='Multi choice list' && (isandImgAl && selansid.indexOf(ansss.AnswerId)>=0)){
                                              showImageTag=true;
                                          }
                                      }
                                  }
                              }
      
                              if(showImageTag && data.Answer!=null){
                                  let imgPath=(Platform.OS=='ios'?'file://':'')+ImageFolderPath+menu1.ScreenName+"/"+data.Image1;
                                  console.log('imgPath:',imgPath);
                                  wqa_obj[imgname_key]=data.Image1;
                                  wqa_obj[img_key]=imgPath;
                              }

                             
      
                              if(data.QuestionType=='Date' && data.Answer!=null){
                                  let dayonly=moment().format('DD');
                                  let actual_date=data.Answer?data.Answer.split('/'):[];
                                  let month=actual_date[0],year=actual_date[1];
                                  let fulldate=month+'/'+dayonly+'/'+year;
                                  wqa_obj[date_key]=fulldate;
                                  
                              }

                            arr.push(data);
                            if(i==txnres2.rows.length-1){
                                obj['WindowQuestions']=arr;
                                obj['WindowQA']=wqa_obj;
                                resolve(obj)
                            }                                
                        }
                    }
                    else{
                        resolve(obj)
                    }
                },function (txnE,txnerr) { console.log(txnerr); resolve(obj) },);
            });  
        }).then((val)=>{
            return val
        }).catch((err)=>{
            console.log(err);
            return obj;
        });
    }


    async function getWindowAnswers(qtn){
        
        return new Promise((resolve,reject)=>{
            
            db.transaction(async function (txn) {
                var q='',selectlist='';
                selectlist=` DISTINCT  PromoAnswerId as AnswerId,PromoAnswerName as Answer,PromoaShowCamera,PromoaCameraMandatory,PromoaQuestionEnable,PromoaQuestionDisable `;
                q=`select ${selectlist} from  Master_PromotionQuestion  where PromoQuestionId='${qtn.PromoQuestionId}'  order by PromoaSequence  `;

                await txn.executeSql(q,[],async function (txn2, txnres2) { 
                    if(txnres2.rows.length>0){
                        let arr=[];
                        for(var i=0;i<txnres2.rows.length;i++){
                            let data =txnres2.rows.item(i);
                            arr.push(data);
                            if(i==txnres2.rows.length-1){
                                resolve(arr)
                            }                                
                        }
                    }
                    else{
                        resolve([])
                    }
                },function (txnE,txnerr) { console.log(txnerr); resolve([]) },);
            });  
        }).then((val)=>{
            return val
        }).catch((err)=>{
            console.log(err);
            return [];
        });
    }

    async function getWindowStockData(window,storeData1,isInserted=false,isOPStockEnableFlag=false){
        let obj={'WStocks':[],'WStocksData':[],'isAllChecked':0}
        let {StoreId,StateId,ChainId,StoreTypeId,StoreClassId,StoreCategoryId}=storeData1;
        return new Promise((resolve,reject)=>{
            db.transaction(async function (txn) {
                
                let checkassrt=window.PromoElementCheckAssortment=='true' || window.PromoElementCheckAssortment==1?true:false;
                let join='',join2='',join3='';
                 
                if(isOPStockEnableFlag==true||isOPStockEnableFlag=="true"){
                    join3=`inner join ${AppTables.STOCK_DATA} s2 on s2.PRODUCT_ID=s.PromoStockValue and STORE_ID='${storeData1.StateId}' and VISIT_DATE='${d2}'`;
                } 
                
                // get data from masters with inserted data if any
                if(checkassrt){
                    join2=` inner join Mapping_ProductAssortmentStorewise a on a.ProductId=s.PromoStockValue and a.StoreId='${StoreId}'`;
                }
                let join4=`left outer join ${AppTables.PROMO_STOCK_DATA} st on s.PromoStockDefinitionId=st.PROMO_STOCK_DEFINITION_ID and st.PROMO_DEFINITION_ID='${window.PromoDefinitionId}' and st.STORE_ID='${storeData1.StoreId}'  and st.VISIT_DATE='${d2}'`;
                // let selectlist1=`  s.PROMO_STOCK_DEFINITION_ID as PromoStockDefinitionId, s.PROMO_DEFINITION_ID as PromoDefinitionId,s.PROMO_STOCK_TABLE as PromoStockTable,s.PROMO_STOCK_FIELD as PromoStockField,s.PROMO_STOCK_VALUE as PromoStockValue,s.PROMO_STOCK_MBQ as PromoStockMBQ,s.PRODUCT_NAME as ProductName, s.STOCK as Stock,s.IS_PROMO_PRESENT as isPromoPresent `;
                let selectlist2=`  s.PromoStockDefinitionId, s.PromoDefinitionId,s.PromoStockTable,s.PromoStockField,s.PromoStockValue,s.PromoStockMBQ,s.ProductName,s.PromoStockMBQ,st.STOCK as Stock,st.IS_PROMO_PRESENT as isPromoPresent  `;
                let q2=`select ${selectlist2} from  Master_PromotionStockDefinition s ${join2} ${join3} ${join4} where s.PromoDefinitionId='${window.PromoDefinitionId}'  `;
                if(checkassrt){
                    q2+=` and a.StoreId='${storeData1.StoreId}' `;
                }
                if(isOPStockEnableFlag==true||isOPStockEnableFlag=="true"){
                    q2+=` and s2.OPENING_STOCK>0`;
                }
                q2+=` order by s.ProductName `;
                
                await txn.executeSql(q2,[],async function (txn2, txnres2) { 
                    console.log('products added:',txnres2.rows.length)
                    if(txnres2.rows.length>0){
                        let arr=[],WStocksData=[];
                        let isAllChecked=1;
                        for(var i=0;i<txnres2.rows.length;i++){
                            let data =txnres2.rows.item(i);
                            inputRefs.current['input1_'+data.PromoDefinitionId+"_"+data.PromoStockDefinitionId]='';
                                
                            console.log('data ProductName:',data.ProductName,data)
                            if(data.Stock!=null){
                                let stockData_obj={'ProductId':data.PromoStockValue,'Stock':data.Stock,'isPromoPresent':(data.isPromoPresent!=null ?data.isPromoPresent:0)}
                                WStocksData.push(stockData_obj);
                            }
                            if(data.isPromoPresent==null || data.isPromoPresent==0 || data.isPromoPresent=='0' || data.isPromoPresent==''){
                               
                                isAllChecked=0;
                            }
                            arr.push(data);
                            if(i==txnres2.rows.length-1){
                                obj['WStocks']=arr;
                                obj['WStocksData']=WStocksData;
                                obj['isAllChecked']=isAllChecked;
                                resolve(obj)
                            }                                
                        }
                    }
                    else{
                        resolve(obj) 
                    }
                    // else{
                    //     await txn.executeSql(q2,[],async function (txn2, txnres3) { 
                    //         console.log('products laoded:',txnres3.rows.length,q2)
                    //         if(txnres3.rows.length>0){
                    //             let arr=[],WStocksData=[];
                    //             let isAllChecked=1;
                    //             for(var i=0;i<txnres3.rows.length;i++){
                    //                 let data =txnres3.rows.item(i);
                    //                 console.log('products data:',data)
                    //                 if(isInserted==true && data.Stock!=null){
                    //                     let stockData_obj={'ProductId':data.PromoStockValue,'Stock':data.Stock,'isPromoPresent':(data.isPromoPresent!=null ?data.isPromoPresent:0)}
                    //                     WStocksData.push(stockData_obj);
                    //                 }
                    //                 if(data.isPromoPresent==null || data.isPromoPresent==0 || data.isPromoPresent=='0' || data.isPromoPresent==''){
                                       
                    //                     isAllChecked=0;
                    //                 }
                    //                 arr.push(data);
                    //                 if(i==txnres3.rows.length-1){
                    //                     obj['WStocks']=arr;
                    //                     obj['WStocksData']=WStocksData;
                    //                     obj['isAllChecked']=isAllChecked;
                    //                     resolve(obj)
                    //                 }                                
                    //             }
                    //         }
                    //         else{
                    //             resolve(obj)
                    //         }
                    //     },function (txnE,txnerr) { console.log(txnerr); resolve(obj) },);
                    // }
                },function (txnE,txnerr) { console.log(txnerr); resolve(obj) },);
            });  
        }).then((val)=>{
            return val
        }).catch((err)=>{
            console.log(err);
            return obj;
        });
    }


    async function getImage(imgdata){
        let type=getImageProps.type || '';
        let window=getImageProps.window || {};
        let splitItem=getImageProps.splitItem || {};
        let splitItemIndex=getImageProps.splitItemIndex || 0;
        let qtn=getImageProps.qtn || {};
        let cameraType=getImageProps.cameraType!=null?getImageProps.cameraType:'1';

        console.log('getImage cameraType:',cameraType);
        if(typeof imgdata=='object' && imgdata.errorCode=='camera_unavailable'){
            notify(ST.Cameraunavailable);
        }
        else if(typeof imgdata =='object' && imgdata.uri!=null){
            const img=imgdata;
            const imgurl=img.uri, imgWidth=img.width, imgHeight=img.ExtendedHeight;
            let isImgFromGallery=img.fromGallery!=null?img.fromGallery:false;
            let picture_clickedd=isImgFromGallery==true?img.datetime:new Date();

            let picture_clicked_time=moment(picture_clickedd).format('MM-DD-YYYY HH:mm:ss')
            let picture_clicked_time_for_pic_name=moment(picture_clickedd).format('MMDDYYYY_HHmmss')

           console.log("time", picture_clicked_time);
           console.log("time1", picture_clicked_time_for_pic_name);
           let calculate_tym_date_for_filename = picture_clicked_time_for_pic_name;
           let calculate_tym_date_over_img = picture_clicked_time; 
            let filename=storeData.StoreId+'_'+window.PromoDefinitionId+'_'+window.PromoId+'_'+(props.UserId || '')+'_STImg-'+calculate_tym_date_for_filename+'.jpg';
            
            let allData=WindowData;
            let defData={'PromoId':window.PromoId,'PromoDefinitionId':window.PromoDefinitionId};
            const wind_index=allData.findIndex(i=>i.PromoId==window.PromoId && i.PromoDefinitionId==window.PromoDefinitionId) ;
            let wind=wind_index>=0?allData[wind_index]:defData;

            let camera1Label=window.PromoImage1Lable || '';
            let camera2Label=window.PromoImage2Lable || '';
            let extraLabel='';

            if(cameraType=='2'){
                var QD=wind.WindowQA || {};
                var image_key=qtn.PromoQuestionId+'_ImageName1';
                var image_key_path=qtn.PromoQuestionId+'_ImagePath1';
                QD[image_key]=filename;
                extraLabel='Qtn Id: '+qtn.PromoQuestionId;
            }
            else if(cameraType=='3'){
                var image_key='NAImage1';
                var image_key_path='NAImage1Path';
                wind[image_key]=filename;
                extraLabel='Not Exist';
            }
            else{
                var WindowSplits=wind.WindowSplits || [];
                console.log('WindowSplits:',WindowSplits);
                var image_key=type=='1'?'Image1Name':'Image2Name';
                var image_key_path=type=='1'?'Image1':'Image2';
                splitItem[image_key]=filename;
                extraLabel=type=='1'?camera1Label:camera2Label;
            }

            const mark_text1=calculate_tym_date_over_img;
            const mark_text2='Store Name:'+storeData.StoreName+' | Store Id:'+storeData.StoreId+' | User Id:'+storeData.EmpId+' | PromoDef Id:'+window.PromoDefinitionId+(extraLabel!=''?' ('+extraLabel+')':'')+' | Image Type: '+currentMenu.MenuName+' | Date:'+calculate_tym_date_over_img;
            
            let imagePath=`${ImageFolderPath+currentMenu.ScreenName}/${filename}`;
            RNFS.copyFile(imgurl, imagePath)
            .then(async(resn) => {
                // render data with clicked image
                let uri='file://'+imagePath;
                console.log('image marker:',uri);
                
                if(cameraType=='2'){
                    QD[image_key_path]=uri;
                    if(qtn.QuestionType=="Image"){
                        //set answid - 0 and answer to filename if qtnType is Image
                        let id_key=qtn.PromoQuestionId+'_AnswerId'; 
                        let ans_key=qtn.PromoQuestionId+'_Answer'; 
                        QD[id_key]=0;
                        QD[ans_key]=filename;
                    }
                    wind.WindowQA=QD;
                    wind_index>=0?allData[wind_index]=wind:allData.push(wind);
                    BgWindowData(allData);
                    // setWindowData(allData);
                    // setHasUnsavedChanges(true);
                    BgUnsavedChanges(true)
                    setrerenderdata3(!rerenderdata3);
                }
                else if(cameraType=='3'){
                    wind[image_key_path]=uri;
                    wind_index>=0?allData[wind_index]=wind:allData.push(wind);
                    // setWindowData(allData);
                    BgWindowData(allData);
                    // setHasUnsavedChanges(true);
                    BgUnsavedChanges(true)
                    setrerenderdata(!rerenderdata);
                }
                else{
                    console.log('split image updated');
                    splitItem[image_key_path]=uri;
                    splitItemIndex>=0?WindowSplits[splitItemIndex]=splitItem:WindowSplits.push(splitItem);
                    wind.WindowSplits=WindowSplits;
                    wind_index>=0?allData[wind_index]=wind:allData.push(wind);
                        // setWindowData(allData);
                        BgWindowData(allData);
                        // setHasUnsavedChanges(true);
                        BgUnsavedChanges(true)
                    setrerenderdata2(!rerenderdata2);
                }
                
                let objIndex = InputChange.findIndex(i=>i.PromoId==window.PromoId && i.PromoDefinitionId==window.PromoDefinitionId);
                let winArr=[...InputChange]
                winArr[objIndex].Flag=true

                setSelectedImg(uri)
                setInputChange(winArr);


                // add metdata then resize image and restored back to the imagePath
                let restore_data={"destFilePath":imagePath,"imgurl":imgurl,imgWidth,imgHeight,mark_text1,mark_text2}
                let is_restored=await restore_ImageWithMetaData(restore_data,imgdata);
                console.log("image restored:",is_restored);
                
            })
            .catch(err => {
                console.log('ERROR: image file write failed!!!');
                console.log(err.message, err.code);
            });
                           
        } 
        
    }
  
    async function openCamera(window,splitItem,splitItemIndex,type='1',cameraType='1',qtn={}){  
        setErrorField({});
        setError(false);
        setGetImageProps({'window':window,'splitItem':splitItem,'splitItemIndex':splitItemIndex,'type':type,'cameraType':cameraType,'qtn':qtn}); 
        setShowCamera(true);
    }
   
    async function onSubmitData(){
        let isvalid=await validate();
        if(isvalid){
            Keyboard.dismiss();
            setShowAlert(true);
        }
    }

    async function saveData(){
         // setHasUnsavedChanges(false);
         BgUnsavedChanges(false)
        setShowAlert(false);
        setLoaderTitle(ST.SavingData+'...');
        setProcessing(true);
        let d1n=new Date();
        let d3=moment(d1n).format('MM/DD/YYYY');

        
        
        try {   
            let {StoreId,ChainId,StateId,StoreTypeId}=storeData;

            let isKPIIREnableI=KPIFields.findIndex(i=>i.KPIFieldName=='IR_KPIEnable')
            let isKPIIREnableObj=isKPIIREnableI>=0?KPIFields[isKPIIREnableI]:{};
            let isKPIIREnable=isKPIIREnableI>=0?isKPIIREnableObj['KPIFieldEnable']:false;
    
            let CameraIROnceOnlyIndex=KPIFields.findIndex(i=>i.KPIFieldName=='IR_CameraOnceOnly')
            let CameraIROnceOnlyObj=CameraIROnceOnlyIndex>=0?KPIFields[CameraIROnceOnlyIndex]:{};
            let CameraIROnceOnly=CameraIROnceOnlyIndex>=0?CameraIROnceOnlyObj['KPIFieldEnable']:true;
        

            //  remove old data
            // Delete only filtered data if partail save allowed is true
                    
            let {PSAllow}=currentMenu
            let deletePrevData=false;
            if(ShowCatWise && PSAllow){
                if(FilteredPromoValues.length>0){
                    await removePreviousData();
                }
                else{
                    notify('Something went wrong while deleteing old data!')
                    setProcessing(false);
                    return ;
                }
            }else{
                deletePrevData=true;
            }
            
            await db.transaction(async function (txn) {   

                //  remove old data
                if(deletePrevData){
                    await txn.executeSql(`DELETE FROM ${AppTables.PROMO_HDR_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `,[],async function (txn2, txnres) { 
                        console.log('window hdr data deleted');
                    },function (txnE,txnerr) { console.log(txnerr); },);
                    await txn.executeSql(`DELETE FROM ${AppTables.PROMO_CHILD_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `,[],async function (txn2, txnres) { 
                        console.log('window child data deleted');
                    },function (txnE,txnerr) { console.log(txnerr); },);
                    await txn.executeSql(`DELETE FROM ${AppTables.PROMO_IMAGES} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `,[],async function (txn2, txnres) { 
                        console.log('window images data deleted');
                    },function (txnE,txnerr) { console.log(txnerr); },);
                    await txn.executeSql(`DELETE FROM ${AppTables.PROMO_STOCK_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `,[],async function (txn2, txnres) { 
                        console.log('window stock data deleted');
                    },function (txnE,txnerr) { console.log(txnerr); },);
                    await txn.executeSql(`DELETE FROM ${AppTables.PROMO_IR_IMAGES} WHERE STORE_ID='${StoreId}'  and MENU_ID='${currentMenu.MenuId}' and VISIT_DATE='${d2}' `,[],async function (txn2, txnres) { 
                        console.log('window IR images deleted');
                      },function (txnE,txnerr) { console.log(txnerr); },);
                      await txn.executeSql(`DELETE FROM ${AppTables.PROMO_IRUPLOAD} WHERE STORE_ID='${StoreId}'  and MENU_ID='${currentMenu.MenuId}' and VISIT_DATE='${d2}' `,[],async function (txn2, txnres) { 
                        console.log('window IR upload data deleted');
                      },function (txnE,txnerr) { console.log(txnerr); },);

                }
                // add data
                var values='',childV='',imageV='',stockV='',IRImageV='',IRStatusV='';
              
                for (const wi in globalWindows){
                    const window=globalWindows[wi];
                    let isImage1=window.PromoImage1=='true' || window.PromoImage1==1?1:0;
                    let isImage2=window.PromoImage2=='true' || window.PromoImage2==1?1:0;
                    let isNAImageAvl=window.PromoNotExistCamera=='true' || window.PromoNotExistCamera==1?1:0;
                    let isNAReasonEnable=window.PromoNotExistReasonEnable=='true' || window.PromoNotExistReasonEnable==1? 1:0;
                    let isReasonEnable=window.PromoExistReasonEnable=='true' || window.PromoExistReasonEnable==1? 1:0;
                    let isStockReq=window.PromoElementStockRequired=='true' || window.PromoElementStockRequired==1?1:0;
                    let WindowQuestions=window.WindowQuestions || [];
                    let WindowStocks=window.WindowStocks || [];
    
                   
                    const wind=WindowData.find(i=>i.PromoId==window.PromoId && i.PromoDefinitionId==window.PromoDefinitionId);
                    let isPresent=wind.isPresent!=null && wind.isPresent!=''?wind.isPresent:'0';
                    let ReasonId=wind.ReasonId!=null?wind.ReasonId:0;
                    let Reason=wind.Reason!=null?wind.Reason:'';
                    let NAImage1=wind.NAImage1!=null?wind.NAImage1:'';
                    let NAImage1Path=wind.NAImage1Path!=null?wind.NAImage1Path:'';
                    let remark=wind.remark!=null?wind.remark:'';
                    let WindowSplits=wind.WindowSplits || [];
                    let QD=wind.WindowQA || {};
                    let WStocksData=wind.WStocksData || [];
                    let windIRImages=wind.IRImages!=null?wind.IRImages:[];
                    let TempSessionId=wind.TempSessionId!=null?wind.TempSessionId:'';
                    let Sess_StoreCode=wind.Sess_StoreCode!=null?wind.Sess_StoreCode:'';
                    let Sess_TaskName=wind.Sess_TaskName!=null?wind.Sess_TaskName:'';
                    let Sess_CatName=wind.Sess_CatName!=null?wind.Sess_CatName:'';
                    let Sess_PhotoType=wind.Sess_PhotoType!=null?wind.Sess_PhotoType:'';

                    let PROMO_HEADER_ID='WIND'+wi+(Math.floor(Math.random()*1000)+1);
                    let {PromoDefinitionId,PromoId,PromoName,PromoTable,PromoField,PromoValue,ChildName}=window;
                    let showOtherText=wind.showOtherText==true || wind.showOtherText=='1' ?1:0;
                    let RemarkText=wind.RemarkText!=null?wind.RemarkText:'';
                    
                    values+=values!=''?' , ':'';
                    values+=` ('${PROMO_HEADER_ID}','${StoreId}','${d3}','${PromoDefinitionId}','${PromoId}','${PromoName}','${PromoTable}','${PromoField}','${PromoValue}','${ChildName}','${isPresent}','${NAImage1}','${ReasonId}','${Reason}','${(remark || '')}','${showOtherText}','${RemarkText}','1','${d3}') `;
                    
                    if(isKPIIREnable && !CameraIROnceOnly){ // Add window wise IR Status and Images if IR enabled and IR Camera enabled for each window
                        
                        for(const IRImageIndex in windIRImages){
                            let IRImgObj=windIRImages[IRImageIndex];
                            let Image1=IRImgObj['ImagePath']!=null && IRImgObj['ImagePath']!=''?IRImgObj['ImagePath']:'';
                            
                            IRImageV+=IRImageV!=''?' , ':'';
                            IRImageV+=` ('${PROMO_HEADER_ID}','${StoreId}','${d3}','${PromoDefinitionId}','${PromoId}','${Image1}','','${TempSessionId}','','${currentMenu.MenuId}','${d3}') `;
                        }
                        IRStatusV+=IRStatusV!=''?' , ':'';
                        IRStatusV+=` ('${PROMO_HEADER_ID}','${StoreId}','${d3}','${PromoDefinitionId}','${PromoId}','${TempSessionId}','','0','','${currentMenu.MenuId}','${Sess_StoreCode}','${Sess_TaskName}','${Sess_CatName}','${Sess_PhotoType}','${d3}') `;
                        
                    }

                    if(isPresent==1){
                        for(const qtnIndex in WindowQuestions){
                            const qtn=WindowQuestions[qtnIndex];
                            
                            let selansid='',selanswer='',selimg='',showImageTag=false;
                            let isDisabled=qtn.isDisabled==true?"1":"0";
                            let id_key=qtn.PromoQuestionId+'_AnswerId'; 
                            let ans_key=qtn.PromoQuestionId+'_Answer'; 
                            let multi_key=qtn.PromoQuestionId+'_MultiOption';
                            let date_key=qtn.PromoQuestionId+'_Date';
                            let img_key=qtn.PromoQuestionId+'_ImagePath1';
                            let imgname_key=qtn.PromoQuestionId+'_ImageName1';
                            let rating_key=qtn.PromoQuestionId+'_Rating'; 
                            let list_mcdata=[];

                            let {PromoQuestionId,PromoQuestionCode,QuestionType,PromoqShowCamera}=qtn
                            let answer=QD[ans_key] || 0;
                            let DecimalAnswerVal=''
                            let lastchar=''
                            let DecimalAnswer=answer+"";
                            if( qtn.QuestionType=='Decimal'){
                                if(DecimalAnswer!=null && DecimalAnswer!='' && DecimalAnswer!=0 && DecimalAnswer!="."){
                                    DecimalAnswerVal = parseFloat(DecimalAnswer).toFixed(1)
                                }else{
                                    DecimalAnswerVal="0.0"
                                }
                            }else{
                                DecimalAnswerVal=answer
                            }

                            // let answerId=QD[id_key] || '';
                            let answerId=QD[id_key]==0? 0 :(QD[id_key]|| '');
                        
                            let multi_options_ids=QD[multi_key] || '';

                            if(qtn.QuestionType=='Number' || qtn.QuestionType=='Text' || qtn.QuestionType=='Decimal' || qtn.QuestionType=='Date' || qtn.QuestionType=='Image')
                            {
                                showImageTag=(qtn.PromoqShowCamera==1 || qtn.PromoqShowCamera=='true');
                            }
                            else if((qtn.QuestionType=='Single choice list' || qtn.QuestionType=='Multi choice list' )){
                                if (qtn.Answers && qtn.Answers.length>0){
                                    for(var i=0;i<qtn.Answers.length;i++){
                                        let ansss=qtn.Answers[i];
                                        let isandImgAl=(ansss.PromoaShowCamera=='true' || ansss.PromoaShowCamera==1);
                                        if(qtn.QuestionType=='Single choice list' && (isandImgAl && ansss.AnswerId==answerId)){
                                            showImageTag=true;
                                        }
                                        else if(qtn.QuestionType=='Multi choice list' && (isandImgAl && answerId.indexOf(ansss.AnswerId)>=0)){
                                            showImageTag=true;
                                        }
                                        
                                    }
                                }
                            }

                            let Image1=showImageTag==1?QD[imgname_key]:'';

                            childV+=childV!=''?' , ':'';
                            childV+=` ('${PROMO_HEADER_ID}','${StoreId}','${d3}','${PromoDefinitionId}','${PromoId}','${PromoQuestionId}','${PromoQuestionCode}','${QuestionType}','${DecimalAnswerVal}','${answerId}','${multi_options_ids}','${Image1}','${showImageTag}','${isDisabled}','${d3}') `;
                        }

                        if(!isKPIIREnable){ 
                            for(const splitItemIndex in WindowSplits){
                                const splitItem=WindowSplits[splitItemIndex];
                                let Image1Name=splitItem['Image1Name']!=null && splitItem['Image1Name']!=''?splitItem['Image1Name']:'';
                                let Image2Name=splitItem['Image2Name']!=null && splitItem['Image2Name']!=''?splitItem['Image2Name']:'';
                                Image1Name=isImage1==1?Image1Name:'';
                                Image2Name=isImage2==1?Image2Name:'';
                                
                                imageV+=imageV!=''?' , ':'';
                                imageV+=` ('${PROMO_HEADER_ID}','${StoreId}','${d3}','${PromoDefinitionId}','${PromoId}','${Image1Name}','${Image2Name}','${d3}') `;
                            }
                        }

                        for(const stockProdIndex in WindowStocks){
                            const stockProd=WindowStocks[stockProdIndex];
                            let sd=WStocksData.find(i=> i.ProductId==stockProd.PromoStockValue) || {};
                            let stock=sd.Stock!=null?sd.Stock:(sd.Stock==0?sd.Stock:'');
                            let isPromoPresent=sd.isPromoPresent!=null?sd.isPromoPresent:0;
                            let {PromoStockDefinitionId, PromoDefinitionId,PromoStockTable,PromoStockField,PromoStockValue,PromoStockMBQ,ProductName} =stockProd
                            stockV+=stockV!=''?' , ':'';
                            stockV+=` ('${PROMO_HEADER_ID}','${StoreId}','${d3}','${PromoDefinitionId}','${PromoId}','${PromoStockDefinitionId}','${PromoStockTable}','${PromoStockField}','${PromoStockValue}','${PromoStockMBQ}','${ProductName}','${stock}','${isPromoPresent}','${d3}') `;
                        }

                    }
                }
              
                if(isKPIIREnable && CameraIROnceOnly){// Add window wise IR images if IR enabled and IR Camera enabled for once only
                    for(const IRImageIndex in WindowIRImages.current){
                        let IRImgObj=WindowIRImages.current[IRImageIndex];
                        let Image1=IRImgObj['ImagePath']!=null && IRImgObj['ImagePath']!=''?IRImgObj['ImagePath']:'';
                        
                        IRImageV+=IRImageV!=''?' , ':'';
                        IRImageV+=` ('','${StoreId}','${d3}','','','${Image1}','','${GbTempSessionId.current}','','${currentMenu.MenuId}','${d3}') `;
                    }

                    let {Sess_StoreCode,Sess_TaskName,Sess_CatName,Sess_PhotoType}=GbTempSessionObj.current;
                    Sess_StoreCode=Sess_StoreCode || '';
                    Sess_TaskName=Sess_TaskName || '';
                    Sess_CatName=Sess_CatName || '';
                    Sess_PhotoType=Sess_PhotoType || '';
                    IRStatusV+=IRStatusV!=''?' , ':'';
                    IRStatusV+=` ('','${StoreId}','${d3}','','','${GbTempSessionId.current}','','0','','${currentMenu.MenuId}','${Sess_StoreCode}','${Sess_TaskName}','${Sess_CatName}','${Sess_PhotoType}','${d3}') `;
                   
                }
                
                
                
                let add_hdr_data=`INSERT INTO ${AppTables.PROMO_HDR_DATA} (PROMO_HEADER_ID,STORE_ID,VISIT_DATE,PROMO_DEFINITION_ID,PROMO_ID,PROMO_NAME,PROMO_TABLE,PROMO_FIELD,PROMO_VALUE,CHILD_NAME,IS_PRESENT,PROMO_NA_IMAGE,REASON_ID,REASON,REMARK,SHOW_RSN_REMARK,REASON_REMARK,IS_UPDATED,ADDED_DATE) VALUES ${values} `;
                let add_child_data=`INSERT INTO ${AppTables.PROMO_CHILD_DATA} (PROMO_HEADER_ID,STORE_ID,VISIT_DATE,PROMO_DEFINITION_ID,PROMO_ID,QUESTION_ID,QUESTION_CODE,QUESTION_TYPE,ANSWER,ANSWER_ID,MULTI_OPTIONS_IDS,IMAGE1,IMAGE_ALLOW1,IS_DISABLED,ADDED_DATE) VALUES ${childV} `;
                let add_images_data=`INSERT INTO ${AppTables.PROMO_IMAGES} (PROMO_HEADER_ID,STORE_ID,VISIT_DATE,PROMO_DEFINITION_ID,PROMO_ID,IMAGE1,IMAGE2,ADDED_DATE) VALUES ${imageV} `;
                let add_stock_data=`INSERT INTO ${AppTables.PROMO_STOCK_DATA} (PROMO_HEADER_ID,STORE_ID,VISIT_DATE,PROMO_DEFINITION_ID,PROMO_ID,PROMO_STOCK_DEFINITION_ID,PROMO_STOCK_TABLE,PROMO_STOCK_FIELD,PROMO_STOCK_VALUE,PROMO_STOCK_MBQ,PRODUCT_NAME,STOCK,IS_PROMO_PRESENT,ADDED_DATE) VALUES ${stockV} `;
                let add_IRImage_data=`INSERT INTO ${AppTables.PROMO_IR_IMAGES} (PROMO_HEADER_ID,STORE_ID,VISIT_DATE,PROMO_DEFINITION_ID,PROMO_ID,IMAGE1,IMAGE2,TEMP_SESSION_ID,UN_SESSION_ID,MENU_ID,ADDED_DATE) VALUES ${IRImageV} `;
                let add_IRStatus_data=`INSERT INTO ${AppTables.PROMO_IRUPLOAD} (PROMO_HEADER_ID,STORE_ID,VISIT_DATE,PROMO_DEFINITION_ID,PROMO_ID,TEMP_SESSION_ID,UN_SESSION_ID,UPLOAD_STATUS,SYNC_STATUS,MENU_ID,SESSION_STORECODE,SESSION_TASKNAME,SESSION_CATNAME,SESSION_PHOTOTYPE,ADDED_DATE) VALUES ${IRStatusV} `;
              
                console.log("imageV:",imageV);
                
                
                await txn.executeSql(add_hdr_data,[],async function (txn2, txnres) { 
                    console.log('st header data added');
                    var isSplitImageAdded=true,isStockAdded=true,isChildAdded=true,isIRImageAdded=true,isIRStatusAdded=true;
                    if(imageV!=''){
                        isSplitImageAdded=await executeQuery(add_images_data);
                    }
                    if(stockV!=''){
                        isStockAdded=await executeQuery(add_stock_data);
                    }
                    if(childV!=''){
                        isChildAdded=await executeQuery(add_child_data);
                    }
                    if(IRImageV!=''){
                        isIRImageAdded=await executeQuery(add_IRImage_data);
                    }
                    if(IRStatusV!=''){
                        isIRStatusAdded=await executeQuery(add_IRStatus_data);
                    }

                    if(!isSplitImageAdded){
                        setProcessing(false);notify(ST.Cannotaddpromotionimages);
                    }
                    else if(!isStockAdded){
                        setProcessing(false);notify(ST.Cannotaddpromotionstockdata);
                    }
                    else if(!isChildAdded){
                        setProcessing(false);notify(ST.Cannotaddpromotionquestionsdata);
                    }else if(!isIRImageAdded){
                        setProcessing(false);notify('Cannot add paid promotion IR Images data');
                    }
                    else if(!isIRStatusAdded){
                        setProcessing(false);notify('Cannot add paid promotion IR Status data');
                    }
                    else{
                        // clear store data in local storage to avoiding re-set data for the store  
                        clear_item('storeData')
                        console.log("store is stored")
                        setProcessing(false);notify(ST.Promotiondataupdatedsuccessfully);
                        props.navigation.goBack();
                    }
                       
                },function (txnE,txnerr) { console.log(txnerr);setProcessing(false);notify(ST.Cannotaddpromotiondata); },);
            });          
        } catch (err) {
            console.log(err);          
        } 
    }


    async function removePreviousData(){
        let {StoreId,ChainId,StateId,StoreTypeId}=storeData;
        
        return new Promise((resolve,reject)=>{

            db.transaction(async function (txn) {   
                let FilterIdsJoin=FilteredPromoValues.join(',');
                let q=`SELECT * FROM ${AppTables.PROMO_HDR_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and PROMO_VALUE in (${FilterIdsJoin})   `
                await txn.executeSql(q,[],async function (txn2, txnres) { 
                    console.log("data to delete:",txnres.rows.length);
                    if(txnres.rows.length>0){
                        let arr=[];
                        let isHdrDel=false,isQtnsDel=false,isImagesDel=false,isStockDel=false;
                        for(let i=0;i<txnres.rows.length;i++){
                            let data=txnres.rows.item(i);
                            let {PROMO_HEADER_ID}=data;
                            arr.push(PROMO_HEADER_ID);

                            if(i==txnres.rows.length-1){
                                let AllHdrIds=`'${arr.join("','")}'`;

                                await txn.executeSql(`DELETE FROM ${AppTables.PROMO_HDR_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and PROMO_HEADER_ID in (${AllHdrIds}) `,[],async function (txn2, txnres) { 
                                    console.log('window hdr data deleted');
                                    isHdrDel=true;
                                    if(isHdrDel && isQtnsDel &&  isImagesDel && isStockDel){
                                        resolve(true);
                                    }
                                },function (txnE,txnerr) { console.log(txnerr); },);
                                await txn.executeSql(`DELETE FROM ${AppTables.PROMO_CHILD_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and PROMO_HEADER_ID in (${AllHdrIds}) `,[],async function (txn2, txnres) { 
                                    console.log('window child data deleted');
                                    isQtnsDel=true;
                                    if(isHdrDel && isQtnsDel &&  isImagesDel && isStockDel){
                                        resolve(true);
                                    }
                                },function (txnE,txnerr) { console.log(txnerr); },);
                                await txn.executeSql(`DELETE FROM ${AppTables.PROMO_IMAGES} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and PROMO_HEADER_ID in (${AllHdrIds}) `,[],async function (txn2, txnres) { 
                                    console.log('window images data deleted');
                                    isImagesDel=true;
                                    if(isHdrDel && isQtnsDel &&  isImagesDel && isStockDel){
                                        resolve(true);
                                    }
                                },function (txnE,txnerr) { console.log(txnerr); },);
                                await txn.executeSql(`DELETE FROM ${AppTables.PROMO_STOCK_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' and PROMO_HEADER_ID in (${AllHdrIds}) `,[],async function (txn2, txnres) { 
                                    console.log('window stock data deleted');
                                    isStockDel=true;
                                    if(isHdrDel && isQtnsDel &&  isImagesDel && isStockDel){
                                        resolve(true);
                                    }
                                },function (txnE,txnerr) { console.log(txnerr); },);

                            }
                        }
                    }
                    else{
                        resolve(true);
                    }
                },function (txnE,txnerr) { console.log(txnerr);resolve(false); },);

                
            });    

        }).then((val)=>{
            return val;
        }).catch((err)=>{
            console.log('error:',err);
            return false;
        })
    }

    async function executeQuery(q){
       
        return new Promise((resolve,reject)=>{
          db.transaction(async function (txn) { 
            await txn.executeSql(q,[],async function (txn2, txnres2) {    
              resolve(true);
            },function(Etxn,txnerr){console.log(txnerr);resolve(false) });
          }); 
        }).then((val)=>{
          return val;
        }).catch((err)=>{
            console.log(err);
          return false;
        })
    }

    async function validate(){
        let isValid=true;

        let isPromoImage1=KPIFields.findIndex(i=>i.KPIFieldName=='PromoImage1')
        let isPromoImage1KPIObj=isPromoImage1>=0?KPIFields[isPromoImage1]:{};
        let isPromoImage1MANDCOUNT=isPromoImage1>=0?isPromoImage1KPIObj['KPIMandatory']:1;
        
        let isPromoImage2=KPIFields.findIndex(i=>i.KPIFieldName=='PromoImage2')
        let isPromoImage2KPIObj=isPromoImage2>=0?KPIFields[isPromoImage2]:{};
        let isPromoImage2MANDCOUNT=isPromoImage2>=0?isPromoImage2KPIObj['KPIMandatory']:1;

        let PromotionValidationRequiredI=KPIFields.findIndex(i=>i.KPIFieldName=='PromotionValidationRequired')
        let PromotionValidationRequiredObj=PromotionValidationRequiredI>=0?KPIFields[PromotionValidationRequiredI]:{};
        let PromotionValidationRequired=PromotionValidationRequiredI>=0?PromotionValidationRequiredObj['KPIFieldEnable']:true;
        

        let isListedSKUIndex=KPIFields.findIndex(i=>i.KPIFieldName=='ListedSKUCheckbox');
        let isListedSKUKPIObj=isListedSKUIndex>=0?KPIFields[isListedSKUIndex]:{};
        let isListedSKUEnable=isListedSKUIndex>=0?isListedSKUKPIObj['KPIFieldEnable']:true;

        let isKPIIREnableI=KPIFields.findIndex(i=>i.KPIFieldName=='IR_KPIEnable')
        let isKPIIREnableObj=isKPIIREnableI>=0?KPIFields[isKPIIREnableI]:{};
        let isKPIIREnable=isKPIIREnableI>=0?isKPIIREnableObj['KPIFieldEnable']:false;

        let CameraIROnceOnlyIndex=KPIFields.findIndex(i=>i.KPIFieldName=='IR_CameraOnceOnly')
        let CameraIROnceOnlyObj=CameraIROnceOnlyIndex>=0?KPIFields[CameraIROnceOnlyIndex]:{};
        let CameraIROnceOnly=CameraIROnceOnlyIndex>=0?CameraIROnceOnlyObj['KPIFieldEnable']:true;
        

        function showError(obj,isErr){
            console.log("error obj:",obj);
            setErrorField(obj);
            setError(isErr);
        }

        // validate only if permit
        return new Promise((resolve,reject)=>{
            for (const wi in globalWindows){
                const window=globalWindows[wi];
                let isImage1=window.PromoImage1=='true' || window.PromoImage1==1?1:0;
                let isImage2=window.PromoImage2=='true' || window.PromoImage2==1?1:0;
                let isNAImageAvl=window.PromoNotExistCamera=='true' || window.PromoNotExistCamera==1?1:0;
                let isNAReasonEnable=window.PromoNotExistReasonEnable=='true' || window.PromoNotExistReasonEnable==1? 1:0;
                let isReasonEnable=window.PromoExistReasonEnable=='true' || window.PromoExistReasonEnable==1? 1:0;
                let isStockReq=window.PromoElementStockRequired=='true' || window.PromoElementStockRequired==1?1:0;
                let StockQtyRequired=window.StockQtyRequired=='true' || window.StockQtyRequired==1?1:0;
                let WindowQuestions=window.WindowQuestions || [];
                let WindowStocks=window.WindowStocks || [];

               
                const wind=WindowData.find(i=>i.PromoId==window.PromoId && i.PromoDefinitionId==window.PromoDefinitionId);
                let isPresent=wind.isPresent!=null && wind.isPresent!=''?wind.isPresent:'0';
                let ReasonId=wind.ReasonId!=null?wind.ReasonId:'';
                let Reason=wind.Reason!=null?wind.Reason:'';
                let NAImage1=wind.NAImage1!=null?wind.NAImage1:'';
                let NAImage1Path=wind.NAImage1Path!=null?wind.NAImage1Path:'';
                let remark=wind.remark!=null?wind.remark:'';
                let WindowSplits=wind.WindowSplits || [];
                let QD=wind.WindowQA || {};
                let WStocksData=wind.WStocksData || [];
                let windIRImages=wind.IRImages!=null?wind.IRImages:[];
                let TempSessionId=wind.TempSessionId!=null?wind.TempSessionId:"";
                let showOtherText=wind.showOtherText!=null?wind.showOtherText:false;
                
                let errorobj = {'EF_Window':window};
                // if(isKPIIREnable && StoreCameraAllow && !CameraIROnceOnly && (windIRImages.length<=0 || TempSessionId=='') ){
                //     notify(`Please click Images for ${window.PromoName}`,'SHORT');
                //     resolve(false);return;
                // }
                // else{
                    if(isPresent=='1'){
                        if(PromotionValidationRequired==true && isReasonEnable==true && ReasonId=='' ){
                            errorobj['EF_NExistReason']="NExistReason";
                            showError(errorobj,true);
                            notify(`${ST.Pleaseselectreasonfor} ${window.PromoName} `,'LONG');
                            resolve(false);return;
                        }
                        // else if(PromotionValidationRequired==true && remark==''){
                        //     notify(`Please enter remark for ${window.PromoName} `,'LONG');
                        //     resolve(false);return;
                        // }
                        else{
                            console.log("!isKPIIREnable && StoreCameraAllow--------",!isKPIIREnable, StoreCameraAllow, !isKPIIREnable && StoreCameraAllow)
                            if(!isKPIIREnable && PromotionValidationRequired==true && StoreCameraAllow && window.NoOfSplit>0 &&  WindowSplits.length>0 && (isImage1==1 || isImage2==1))
                            {
                                
                                for(const splitItemIndex in WindowSplits){
                                    const splitItem=WindowSplits[splitItemIndex];
                                    let Image1Name=splitItem['Image1Name']!=null && splitItem['Image1Name']!=''?splitItem['Image1Name']:'';
                                    let Image2Name=splitItem['Image2Name']!=null && splitItem['Image2Name']!=''?splitItem['Image2Name']:'';
                                    // console.log('Image2Name',Image2Name,isImage2);
                                    // console.log('isPromoImage1MAND',isPromoImage1MAND<=window.NoOfSplit)
                                    // console.log('window.NoOfSplit',window.NoOfSplit)
                                    let currentImgIndex=splitItemIndex+1;
                                    
                                
                                    if(isImage1==1 && currentImgIndex<=isPromoImage1MANDCOUNT && Image1Name==''){
                                        errorobj['EF_splitImage1']="splitImage1";
                                        errorobj['EF_splitItemIndex']=splitItemIndex;
                                        showError(errorobj,true);
                                        notify(`${ST.Pleaseclickallimagesfor} ${window.PromoName}`,'LONG');
                                        resolve(false);return;
                                    }
                                    else if(isImage2==1 && currentImgIndex<=isPromoImage2MANDCOUNT && Image2Name==''){
                                        errorobj['EF_splitImage2']="splitImage2";
                                        errorobj['EF_splitItemIndex']=splitItemIndex;
                                        showError(errorobj,true);
                                        notify(`${ST.Pleaseclickallimagesfor} ${window.PromoName}`,'LONG');
                                        resolve(false);return;
                                    }
                                
                            }
                            }

                        

                            
                            if(PromotionValidationRequired==true && isStockReq==1){
                                let isProductSelected=false;
                                for(const stockProdIndex in WindowStocks){
                                    const stockProd=WindowStocks[stockProdIndex];
                                                
                                    let sd=WStocksData.find(i=> i.ProductId==stockProd.PromoStockValue) || {};
                                    let stock=sd.Stock!=null?sd.Stock:(sd.Stock==0?sd.Stock:'');
                                    let isPromoPresent=sd.isPromoPresent!=null?sd.isPromoPresent:0;

                                    if(isPromoPresent==1){
                                        isProductSelected=true;
                                    }

                                    if((isListedSKUEnable==true && isPromoPresent==1 && StockQtyRequired==1 && stock=='') || (isListedSKUEnable!=true && stock!==0 && (stock==null || stock==''))){
                                        errorobj['EF_stock']="input1_";
                                        errorobj['EF_stockProd']=stockProd;
                                        let refIn1=inputRefs.current['input1_'+window.PromoDefinitionId+'_'+stockProd.PromoStockDefinitionId];
                                        if(refIn1!=null){
                                            refIn1.focus();
                                        }
                                        showError(errorobj,true);
                                        notify(`${ST.Pleaseenterstockfor} ${window.PromoName} ( ${stockProd.ProductName} ) `,'LONG');
                                        resolve(false);return;
                                    }

                                    if(isListedSKUEnable==true && stockProdIndex==WindowStocks.length-1){
                                        if(!isProductSelected){
                                            errorobj['EF_isProductSelected']="isProductSelected";
                                            showError(errorobj,true);
                                            notify(`${ST.PleaseselectatleastoneSKUfor} ${window.PromoName} `,'LONG');
                                            resolve(false);return;
                                        }
                                    }
                                    
                                }
                            }

                            if(PromotionValidationRequired==true && WindowQuestions.length>0){
                                for(const qtnIndex in WindowQuestions){
                                    const qtn=WindowQuestions[qtnIndex];
                                    
                                    let selansid='',selanswer='',selimg='',showImageTag=false;
                                    let id_key=qtn.PromoQuestionId+'_AnswerId'; 
                                    let ans_key=qtn.PromoQuestionId+'_Answer'; 
                                    let multi_key=qtn.PromoQuestionId+'_MultiOption';
                                    let date_key=qtn.PromoQuestionId+'_Date';
                                    let img_key=qtn.PromoQuestionId+'_ImagePath1';
                                    let imgname_key=qtn.PromoQuestionId+'_ImageName1';
                                    let rating_key=qtn.PromoQuestionId+'_Rating'; 
                                    let list_mcdata=[];

                                    let isDisabled=qtn.isDisabled!=null?qtn.isDisabled:false
                                    errorobj['EF_qtn']=qtn;

                                    if(!isDisabled){
                                        let isImgAllowed=((qtn.PromoqShowCamera=='true' || qtn.PromoqShowCamera==1) || (qtn.QuestionType=="Image"));
                                        let checkForAnsKey=(qtn.QuestionType=='Decimal' || qtn.QuestionType=='Number' || qtn.QuestionType=='Text' ||  qtn.QuestionType=='Date' ||  qtn.QuestionType=='Rating') ;
                                        if(qtn.QuestionType=='Single choice list')
                                        {
                                            selansid=QD[id_key];
                                        }
                                        else if(qtn.QuestionType=='Multi choice list')
                                        {
                                            selansid=QD[multi_key]!=null && QD[multi_key]!=''?QD[multi_key].split(','):[];
                                        }
                                        
                                        let err_type='';
                                        //show error type based on qtn type
                                        if(qtn.QuestionType=='Single choice list'){
                                            err_type='Qtn_Select';
                                        }
                                        else if(qtn.QuestionType=='Decimal' || qtn.QuestionType=='Number' || qtn.QuestionType=='Text' ){
                                            err_type='Qtn_Input';
                                        }
                                        else if(qtn.QuestionType=='Date' ){
                                            err_type='Qtn_Date';
                                        }

                                    
                                        if(qtn.QuestionType=='Multi choice list' && selansid.length<=0){
                                            errorobj['EF_Qtn_MultiChoice']='Qtn_MultiChoice';
                                            showError(errorobj,true);
                                            notify(`${Pleaseselectoptionsfortherequiredfield} ${ST.In} ${window.PromoName}`,'SHORT');
                                            resolve(false);return;
                                        }
                                        else if( checkForAnsKey && (Object.keys(QD).indexOf(ans_key)<0 || (Object.keys(QD).indexOf(ans_key)>=0 && QD[ans_key]===''))){
                                            // console.log("checkForAnsKey--------1")
                                            errorobj['EF_Qtn_Input']=err_type;
                                            showError(errorobj,true);
                                            let msg=( qtn.QuestionType=='Date'?`${ST.Pleasepickadatefortherequiredfield} ${ST.In} ${window.PromoName}`:(qtn.QuestionType=='Rating'?`${Pleaseselectratingfortherequiredfield} ${ST.In} ${window.PromoName}`:`${ST.Pleasefillalltherequiredfield} ${ST.In} ${window.PromoName}`));
                                            notify(msg,'SHORT');
                                            resolve(false);return;
                                        }
                                        else if(Object.keys(QD).indexOf(id_key)<0 || (Object.keys(QD).indexOf(id_key)>=0 && (QD[id_key]===''))){
                                                // Object.keys(QD).indexOf(id_key)<0 || (Object.keys(QD).indexOf(id_key)>=0 && (QD[id_key]===''))
                                            // console.log("checkForAnsKey--------2",Object.keys(QD).indexOf(id_key)<0 ," ||(",Object.keys(QD).indexOf(id_key)>=0," &&", (QD[id_key]===''),")",Object.keys(QD).indexOf(id_key),id_key,"--",QD[id_key],"---",QD)
                                            errorobj['EF_Qtn_Input']=err_type;
                                            showError(errorobj,true);
                                            notify(`${ST.Pleasefillalltherequiredfield} ${ST.In} ${window.PromoName}`,'SHORT');
                                            resolve(false);return;
                                        }
                                        else if(!isKPIIREnable && StoreCameraAllow && isImgAllowed && (Object.keys(QD).indexOf(img_key)<0 || (Object.keys(QD).indexOf(img_key)>=0 && QD[img_key]===''))){
                                            errorobj['EF_Qtn_Image']='Qtn_Image';
                                            showError(errorobj,true);
                                            notify(`${ST.Pleaseaddimages} ${ST.In} ${window.PromoName}`,'SHORT');
                                            resolve(false);return;
                                        }else{
                                            console.log('no condition found');
                                        }

                                        if((qtn.QuestionType=='Single choice list' || qtn.QuestionType=='Multi choice list' )){
                                            if (qtn.Answers && qtn.Answers.length>0){
                                                for(var j=0;j<qtn.Answers.length;j++){
                                                    let ansss=qtn.Answers[j];
                                                    let isandImgAl=(ansss.PromoaShowCamera=='true' || ansss.PromoaShowCamera==1);
                                                    if(qtn.QuestionType=='Single choice list' && (isandImgAl && ansss.AnswerId==selansid)){
                                                        showImageTag=true;
                                                    }
                                                    else if(qtn.QuestionType=='Multi choice list' && (isandImgAl && selansid.indexOf(ansss.AnswerId)>=0)){
                                                        showImageTag=true;
                                                    }
                                                }
                                            }
                                        }

                                        if(!isKPIIREnable && StoreCameraAllow && showImageTag && (Object.keys(QD).indexOf(img_key)<0 || (Object.keys(QD).indexOf(img_key)>=0 && QD[img_key]===''))){
                                            errorobj['EF_Qtn_Image']='Qtn_Image';
                                            showError(errorobj,true);
                                            notify(`${ST.Pleaseaddimages} ${ST.In} ${window.PromoName}`,'SHORT');
                                            resolve(false);return;
                                        }
                                    }
                                    else{
                                        // Don't validate field when disabled 
                                    }
                                }
                            }

                        }
                    }
                    else{
                        if(PromotionValidationRequired==true && isNAReasonEnable==true && ReasonId=='' ){
                            errorobj['EF_NExistReason']="NExistReason";
                            showError(errorobj,true);
                            notify(`${ST.Pleaseselectreasonfor} ${window.PromoName} `,'LONG');
                            resolve(false);return;
                        }
                        else if(isNAReasonEnable==true && showOtherText==true && (wind.RemarkText==null || wind.RemarkText=='')){
                            errorobj['EF_NExistRemark']="NExistRemark";
                            showError(errorobj,true);
                            notify(`${ST.PleaseEnterRemarkFor} ${window.PromoName} `,'LONG');
                            resolve(false);return;
                        }
                        else if(!isKPIIREnable && StoreCameraAllow && PromotionValidationRequired==true && isNAImageAvl==true && NAImage1=='' ){
                            errorobj['EF_NExistImage']="NExistImage";
                            showError(errorobj,true);
                            notify(`${ST.Pleaseclickimagefor} ${window.PromoName}`,'LONG');
                            resolve(false);return;
                        }
                    }
                // }
                if(wi==(Windows.length-1)){
                    if( isKPIIREnable && StoreCameraAllow && CameraIROnceOnly && !isAllNotPresent && ( WindowIRImages.current.length<=0  || GbTempSessionId.current=='') ){
                        notify(`Please click Images for ${currentMenu.MenuName}`,'SHORT');
                        resolve(false);return;
                    }
                    else{
                        resolve(true);return;
                    }
                    
                    // resolve(true);return;
                }
                
            }
            
        }).then((val)=>{return val})
        .catch((err)=>{console.log(err); return false});
    
    }


    function onselectionChange(option,keyLbl,keyVal,otherData){
        setErrorField({});
        setError(false);
        let item=otherData.window;
        let allData=WindowData;
        let defData={'PromoId':item.PromoId,'PromoDefinitionId':item.PromoDefinitionId};
        const win_index=allData.findIndex(i=>i.PromoId==item.PromoId && i.PromoDefinitionId==item.PromoDefinitionId);
        let wind=win_index>=0?(allData[win_index] || defData) : defData;
        wind[keyVal]=option.value;
        wind[keyLbl]=option.label;

      
        if(keyLbl=='Reason'){
            let rsn_Index=reasons_list.findIndex(i=>i.ReasonId==option.value);
           
            if(rsn_Index>=0){
                let rsn=reasons_list[rsn_Index];
                let IsRemarkTaken=rsn.IsRemarkTaken==1 || rsn.IsRemarkTaken=='1'?true:false;
                
                if(IsRemarkTaken==true){
                    wind['showOtherText']=true;
                }
                else{
                    wind['showOtherText']=false;
                }
            }
        }
        
        win_index>=0?allData[win_index]=wind:allData.push(wind);
       
        
        let objIndex = InputChange.findIndex(i=>i.PromoId==item.PromoId && i.PromoDefinitionId==item.PromoDefinitionId);
        let winArr=[...InputChange]
        winArr[objIndex].Flag=true

        setInputChange(winArr)
        // setWindowData(allData);
        BgWindowData(allData);
        // setHasUnsavedChanges(true);
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);
    }

    function onselectionChange2(option,qtn,window){
        setErrorField({});
        setError(false);
        let allData=WindowData;
        let defData={'PromoId':window.PromoId,'PromoDefinitionId':window.PromoDefinitionId};
        const wind_index=allData.findIndex(i=>i.PromoId==window.PromoId && i.PromoDefinitionId==window.PromoDefinitionId);
        console.log('onselectionChange2 wind_index:',wind_index);
        let wind=wind_index>=0?allData[wind_index]:defData;
        let data=wind.WindowQA || {};
        let id_key=qtn.PromoQuestionId+'_AnswerId'; 
        let ans_key=qtn.PromoQuestionId+'_Answer'; 
        data[id_key]=option.value;
        data[ans_key]=option.label;
        

        wind['WindowQA']=data;
        wind_index>=0?allData[wind_index]=wind:allData.push(wind);
      
        let objIndex = InputChange.findIndex(i=>i.PromoId==window.PromoId && i.PromoDefinitionId==window.PromoDefinitionId);
        let winArr=[...InputChange]
        winArr[objIndex].Flag=true

        setInputChange(winArr)
        // setWindowData(allData);
        BgWindowData(allData);

        let aq_ans=qtn.Answers!=null?qtn.Answers:[];
        let ans_obj=aq_ans.find(i=>i.AnswerId==option.value) || {};
        let EQtns=ans_obj.PromoaQuestionEnable!=null && ans_obj.PromoaQuestionEnable!=''?ans_obj.PromoaQuestionEnable.replace(' ','').split(','):[];
        let DQtns=ans_obj.PromoaQuestionDisable!=null && ans_obj.PromoaQuestionDisable!=''?ans_obj.PromoaQuestionDisable.replace(' ','').split(','):[];
      
        let sqtns=window.WindowQuestions || []

        if(EQtns.length>0){
            enableQtns(sqtns,EQtns,DQtns,data,wind,wind_index,allData,window)
        }
        else if(DQtns.length>0){
            disableQtns(sqtns,DQtns,data,wind,wind_index,allData,window)
        }
        else{
            // setHasUnsavedChanges(true);
            BgUnsavedChanges(true)
            setrerenderdata(!rerenderdata);
        }
        BgUnsavedChanges(true)
       
    }

    async function disableQtns(sqtns,DQtns,data,wind={},wind_index=-1,allData=[],window={}){
       
        if(DQtns.length>0){
            new Promise.all(
                DQtns.map((qid,q_index)=>{
                    let s_qtnindex=sqtns.findIndex(i=>i.PromoQuestionId==qid) || {};
                    if(s_qtnindex>=0)
                    {
                        let s_qtn=sqtns[s_qtnindex];
                        s_qtn['isDisabled']=true
                        sqtns[s_qtnindex]=s_qtn;
                        let id_key=s_qtn.PromoQuestionId+'_AnswerId'; 
                        let ans_key=s_qtn.PromoQuestionId+'_Answer'; 
                        data[id_key]=0;
                        data[ans_key]='';

                        wind['WindowQA']=data;
                        wind_index>=0?allData[wind_index]=wind:allData.push(wind);
                    }
                    return false
                })
            ).then(async (val)=>{

                let allwindows=Windows;
                let windowIndex=allwindows.findIndex(i=>i.PromoDefinitionId==window.PromoDefinitionId && i.PromoId==window.PromoId)
                if(windowIndex>0){
                    window['WindowQuestions']=sqtns;
                    allwindows[windowIndex]=window;
                    // setWindowData(allData);
                    BgWindowData(allData);
                    setWindows(allwindows);
                    setGlobalWindows(allwindows);
                    // setHasUnsavedChanges(true);
                    BgUnsavedChanges(true)
                    setrerenderdata(!rerenderdata);
                }
                else{
                    setrerenderdata(!rerenderdata);
                }
                
            })
        }
    }

    async function enableQtns(sqtns,EQtns,DQtns,data,wind={},wind_index=-1,allData=[],window={}){
        new Promise.all(
            EQtns.map((qid,q_index)=>{
                let s_qtnindex=sqtns.findIndex(i=>i.PromoQuestionId==qid) || {};
                if(s_qtnindex>=0){
                    let s_qtn=sqtns[s_qtnindex];
                    s_qtn['isDisabled']=false
                    sqtns[s_qtnindex]=s_qtn;
                }
                return false
            })
        ).then(async (val)=>{
            if(DQtns.length>0){
                disableQtns(sqtns,DQtns,data,wind,wind_index,allData,window)
            }
            else{
                let allwindows=Windows;
                let windowIndex=allwindows.findIndex(i=>i.PromoDefinitionId==window.PromoDefinitionId && i.PromoId==window.PromoId)
                if(windowIndex>0){
                    window['WindowQuestions']=sqtns;
                    allwindows[windowIndex]=window;
                    setWindows(allwindows);
                    setGlobalWindows(allwindows);
                    // setHasUnsavedChanges(true);
                    BgUnsavedChanges(true)
                    setrerenderdata(!rerenderdata);
                }
                else{
                    setrerenderdata(!rerenderdata);
                }
            }
        })
    }

    async function setMultiSelectValue(selectedItems=[],qtn={},window={}) {  
        setErrorField({});
        setError(false);
        console.log('setMultiSelectValue',selectedItems);      
        let id_key=qtn.PromoQuestionId+'_AnswerId'; 
        let ans_key=qtn.PromoQuestionId+'_Answer'; 
        let multi_key=qtn.PromoQuestionId+'_MultiOption';
       
        let allData=WindowData;
        let defData={'PromoId':window.PromoId,'PromoDefinitionId':window.PromoDefinitionId};
        const wind_index=allData.findIndex(i=>i.PromoId==window.PromoId && i.PromoDefinitionId==window.PromoDefinitionId);
        let wind=wind_index>=0?allData[wind_index]:defData;
        let obj=wind.WindowQA || {};
        obj[id_key]=0;
        obj[multi_key]=selectedItems.join(',');
        let anss=[];
        selectedItems.map((itemValue)=>{
            let ans = qtn.Answers.find(c1 => c1.AnswerId == itemValue); 
            if(ans.Answer){anss.push(ans.Answer)}
        });
        obj[ans_key]=anss.join(',');
        console.log('obj:',obj);
        
        wind['WindowQA']=obj;
        wind_index>=0?allData[wind_index]=wind:allData.push(wind);

        
        let objIndex = InputChange.findIndex(i=>i.PromoId==window.PromoId && i.PromoDefinitionId==window.PromoDefinitionId);
        let winArr=[...InputChange]
        winArr[objIndex].Flag=true

        setInputChange(winArr)
        // setWindowData(allData);
        BgWindowData(allData);
        // setHasUnsavedChanges(true);
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);
    }

    function setTextValue(value,qtn,window,type='') {   
        setErrorField({});
        setError(false);
        if(value!=''){
            let isValid=validateNumber(value,type);
            if(!isValid){
                return;
            }
        }

        let id_key=qtn.PromoQuestionId+'_AnswerId'; 
        let ans_key=qtn.PromoQuestionId+'_Answer'; 
        
        let allData=WindowData;
        let defData={'PromoId':window.PromoId,'PromoDefinitionId':window.PromoDefinitionId};
        const wind_index=allData.findIndex(i=>i.PromoId==window.PromoId && i.PromoDefinitionId==window.PromoDefinitionId);
        let wind=wind_index>=0?allData[wind_index]:defData;
        let obj=wind.WindowQA || {};

        if(qtn.QuestionType=='Date' ){
            let date_key=qtn.PromoQuestionId+'_Date'; 
            let d=value!=null?new Date(value):new Date();
            let mfdate=moment(d).format('MM/YYYY');
            showQtnDatePicker(qtn,window,false);
            obj[id_key]=0;
            obj[ans_key]=mfdate;
            obj[date_key]=moment(d).format('MM/DD/YYYY');
        }
        else{
            obj[id_key]=0;
            obj[ans_key]=value;
        }
        
        console.log(value,obj);
        wind['WindowQA']=obj;
        wind_index>=0?allData[wind_index]=wind:allData.push(wind);

         // setWindowData(allData);
         BgWindowData(allData);
         // setHasUnsavedChanges(true);
         BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);
    }

    function showQtnDatePicker(qtn,window,show=false){
        let allQtns=window.WindowQuestions || [];
        let newqtnIndex=allQtns.findIndex(q=>q.PromoQuestionId==qtn.PromoQuestionId);
       
        if(newqtnIndex>=0){
            let newqtn=allQtns[newqtnIndex];
            newqtn.showDatePicker=show;
            allQtns[newqtnIndex]=newqtn;
            window['WindowQuestions']=allQtns;
            let allWindows=Windows;
            const winIndex=allWindows.findIndex(i=>i.PromoId==window.PromoId && i.PromoDefinitionId==window.PromoDefinitionId) || {};
            allWindows[winIndex]=window;
            setWindows(allWindows);
            setGlobalWindows(allwindows);
            if(show==true) setrerenderdata(!rerenderdata);
        }
    }

    function setRatingValue(data){
        setRatingOrder(data);
    }

    function onRatingCancel(){ 
        setShowRating(false);
    }

    function onRatingSave(){
        setShowRating(false);
        let qtn=RatingQtn;
        let window=RatingWindow;
        let id_key=qtn.PromoQuestionId+'_AnswerId'; 
        let ans_key=qtn.PromoQuestionId+'_Answer'; 
        let rating_key=qtn.PromoQuestionId+'_Rating'; 
        let ids=[],anss=[];
        RatingOrder.map((item,index)=>{
            ids.push(item.AnswerId);
            anss.push(item.Answer);
        })

        let allData=WindowData;
        let defData={'PromoId':window.PromoId,'PromoDefinitionId':window.PromoDefinitionId};
        const wind_index=allData.findIndex(i=>i.PromoId==window.PromoId && i.PromoDefinitionId==window.PromoDefinitionId);
        let wind=wind_index>=0?allData[wind_index]:defData;
        let obj=wind.WindowQA || {};

        obj[rating_key]=ids.join(',');
        obj[id_key]=0;
        obj[ans_key]=anss.join(',');
        
        wind['WindowQA']=obj;
        wind_index>=0?allData[wind_index]=wind:allData.push(wind);

        let objIndex = InputChange.findIndex(i=>i.PromoId==window.PromoId && i.PromoDefinitionId==window.PromoDefinitionId);
        let winArr=[...InputChange]
        winArr[objIndex].Flag=true

        setInputChange(winArr)
        // setWindowData(allData);
        BgWindowData(allData);
        // setHasUnsavedChanges(true);
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);
    }

    function UpdateShow_zoomImageRef2(val){
        Show_zoomImageRef2.current=val
        setShow_zoomImage2(val);
    }
    
   
    function onChoiceSelect(item,val,key,animatedChoice){

        let win_index=InputChange.find(i=>i.PromoId==item.PromoId && i.PromoDefinitionId==item.PromoDefinitionId)
        let changeValue=win_index.Flag;
   
        if(changeValue){
            setIsPresentClean(val)
            setDataCleanAnim(animatedChoice)
            setDataCleanItem(item)
            setDataCleanModal(true)
            return
        }
        
        var val1=0;
        val==1?val1=1:'';
        
        if(animatedChoice!=null){
            Animated.timing(animatedChoice, {
                toValue: val1,
                duration:400,
                useNativeDriver:false,
            }).start();
        }
        onWindowDataChange(item,val,key)
    }

    function onWindowDataChange(item,val,key){
        let allData=WindowData;
        let defData={'PromoId':item.PromoId,'PromoDefinitionId':item.PromoDefinitionId};
        const win_index=allData.findIndex(i=>i.PromoId==item.PromoId && i.PromoDefinitionId==item.PromoDefinitionId);
        let wind=win_index>=0?(allData[win_index] || defData) : defData;
        wind[key]=val;

        if(key=='ReasonId'){
            let rsn=reasons_list.find(r=>r.ReasonId==val) || {};
            wind['Reason']=rsn.Reason || '';
        }

        win_index>=0?allData[win_index]=wind:allData.push(wind);
        
        if(key!="isPresent"){
            let objIndex = InputChange.findIndex(i=>i.PromoId==item.PromoId && i.PromoDefinitionId==item.PromoDefinitionId);
            let winArr=[...InputChange]
            winArr[objIndex].Flag=true
            setInputChange(winArr)
        }
        // setWindowData(allData);
        BgWindowData(allData);
        // setHasUnsavedChanges(true);
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);
    }

    function onWindowDataClean(){
        if(DataCleanAnim!=null){
            console.log("anim---")
            let anim=isPresentClean==1?1:'';
            Animated.timing(DataCleanAnim, {
                toValue:anim,
                duration:400,
                useNativeDriver:false,
            }).start();
        }
        let isPromoImage1=KPIFields.findIndex(i=>i.KPIFieldName=='PromoImage1')
        let isPromoImage1KPIObj=isPromoImage1>=0?KPIFields[isPromoImage1]:{};
        let isPromoImage1MANDCOUNT=isPromoImage1>=0?isPromoImage1KPIObj['KPIMandatory']:1;
        
        let isPromoImage2=KPIFields.findIndex(i=>i.KPIFieldName=='PromoImage2')
        let isPromoImage2KPIObj=isPromoImage2>=0?KPIFields[isPromoImage2]:{};
        let isPromoImage2MANDCOUNT=isPromoImage2>=0?isPromoImage2KPIObj['KPIMandatory']:1;

        let allData=WindowData;
        let WindowSplits =  [];
        for(var s=0;s<DataCleanItem.NoOfSplit;s++){
            let img1Req=s<=isPromoImage1MANDCOUNT?true:false;
            let img2Req=s<=isPromoImage2MANDCOUNT?true:false;
            let obj={'Image1Name':'','Image1':'','Image2Name':'','Image2':'', 'img1Required':img1Req, 'img2Required':img2Req};
            WindowSplits.push(obj);
        }
        i=>i.PromoId==item.PromoId && i.PromoDefinitionId==item.PromoDefinitionId
      
        // let WindowQuestions = WQr['WindowQuestions'] || [];
        // let WindowQA= WQr['WindowQA'] || {};
        // let WSd= isStockReq==true ? await getWindowStockData(data,storeData1,isPresent) : {'WStocks':[],'WStocksData':[]};
        // let WStocks=WSd['WStocks'] || [];
        // let WStocksData=WSd['WStocksData'] || [];
        // let isAllChecked=WSd['isAllChecked']!=null?WSd['isAllChecked']:0;

        // ,'WindowSplits':WindowSplits,'WindowQA':WindowQA,'WStocksData':WStocksData,'isAllSKUChecked':isAllChecked

        let defData={'PromoId':DataCleanItem.PromoId,'PromoDefinitionId':DataCleanItem.PromoDefinitionId,'WindowSplits':WindowSplits,'WindowQA':{},'WStocksData':[],isPresent:isPresentClean,'isAllSKUChecked':0};
        const win_index=allData.findIndex(i=>i.PromoId==DataCleanItem.PromoId && i.PromoDefinitionId==DataCleanItem.PromoDefinitionId);
        allData[win_index]=defData

        let objIndex = InputChange.findIndex((obj => obj.PromoId == DataCleanItem.PromoId && obj.PromoDefinitionId==DataCleanItem.PromoDefinitionId));
        let winArr=[...InputChange]
        winArr[objIndex].Flag=false
    
        setInputChange(winArr)
        // setWindowData(allData);
        BgWindowData(allData);
        // setHasUnsavedChanges(true);
        BgUnsavedChanges(true)
        setDataCleanModal(false)
        setrerenderdata(!rerenderdata);
    }
    
    const onCancelClean = () =>{
        setDataCleanModal(false)
    }
    const onclear = () => {
        onWindowDataClean(DataCleanItem)
    }
  
    async function setWindowStockVal(val,window,stockProd,key,type=''){
        setErrorField({});
        setError(false);
        if(val!=''){
            let isValid=validateNumber(val,type);
            if(!isValid){
                return;
            }
        }
        
        let allData=WindowData;
        let defData={'PromoId':window.PromoId,'PromoDefinitionId':window.PromoDefinitionId};
        const win_index=allData.findIndex(i=>i.PromoId==window.PromoId && i.PromoDefinitionId==window.PromoDefinitionId);
        let wind=win_index>=0?(allData[win_index] || defData) : defData;
        let WStocksData=wind['WStocksData'] || [];
        let sdIndex=WStocksData.findIndex(i=> i.ProductId==stockProd.PromoStockValue);
        let sd=sdIndex>=0?WStocksData[sdIndex]:{'ProductId':stockProd.PromoStockValue,'Stock':''};
        sd[key]=val;
        sdIndex>=0?WStocksData[sdIndex]=sd:WStocksData.push(sd);
        wind['WStocksData']=WStocksData;
        win_index>=0?allData[win_index]=wind:allData.push(wind);
        if(key=='isPromoPresent'){
            let isAllChecked = await verifyAllChecked(val,window,stockProd,key);
            wind['isAllSKUChecked']=isAllChecked;
        }
        
        // setWindowData(allData);
        BgWindowData(allData);
        // setHasUnsavedChanges(true);
        BgUnsavedChanges(true)
        setrerenderdata4(!rerenderdata4);
    }

    async function onCatTextChange(window,key,val,type=''){
        setErrorField({});
        setError(false);
        if(val!=''){
            let isValid=validateNumber(val,type);
            if(!isValid){
                return;
            }
        }

        let item=window;
        let allData=WindowData;
        let defData={'PromoId':item.PromoId,'PromoDefinitionId':item.PromoDefinitionId};
        const win_index=allData.findIndex(i=>i.PromoId==item.PromoId && i.PromoDefinitionId==item.PromoDefinitionId);
        let wind=win_index>=0?(allData[win_index] || defData) : defData;
        wind[key]=val;

        win_index>=0?allData[win_index]=wind:allData.push(wind);
        // setWindowData(allData);
        BgWindowData(allData);
        // setHasUnsavedChanges(true);
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);
    }


    async function verifyAllChecked(val,window,stockProd,key){
        return await new Promise((resolve,reject)=>{
            let WindowStocks=window.WindowStocks || [];
            let allData=WindowData;
            const win_index=allData.findIndex(i=>i.PromoId==window.PromoId && i.PromoDefinitionId==window.PromoDefinitionId);
            let wind=win_index>=0?(allData[win_index] || defData) : defData;
            let WStocksData=wind['WStocksData'] || [];
            if(WindowStocks.length>0){
                let isAllChecked=1;
                for(var i=0;i<WindowStocks.length;i++){
                    let stockProd=WindowStocks[i];
                    
                    let sdIndex1=WStocksData.findIndex(a=> a.ProductId==stockProd.PromoStockValue);
                    let sd1=sdIndex1>=0?WStocksData[sdIndex1]:{};
                    let isPromoPresent=sd1.isPromoPresent;
                    if(isPromoPresent==null || isPromoPresent=='' || isPromoPresent==0 || isPromoPresent=='0'){
                        isAllChecked=0
                    }

                    if(i==WindowStocks.length-1){
                        resolve(isAllChecked);
                    }
                }
            }
            else{
                resolve(0);
            }
            
        }).catch((err)=>{
            console.log(err);
            return 0;
        });
    }

    function checkAllSKUs(val,window){
        
        let WindowStocks=window.WindowStocks || [];
        let allData=WindowData;
        let defData={'PromoId':window.PromoId,'PromoDefinitionId':window.PromoDefinitionId};
        const win_index=allData.findIndex(i=>i.PromoId==window.PromoId && i.PromoDefinitionId==window.PromoDefinitionId);
        let wind=win_index>=0?(allData[win_index] || defData) : defData;
        let WStocksData=wind['WStocksData'] || [];
        console.log('WStocksData before:',WStocksData)
        for(var i=0;i<WindowStocks.length;i++){
            let stockProd=WindowStocks[i];
            
            let sdIndex=WStocksData.findIndex(a=> a.ProductId==stockProd.PromoStockValue);
            let sd=sdIndex>=0?WStocksData[sdIndex]:{'ProductId':stockProd.PromoStockValue,'Stock':''};
            let isPromoPresent=(val==1 || val=='1')?1:0;
            sd['isPromoPresent']=isPromoPresent;
            
            sdIndex>=0?(WStocksData[sdIndex]=sd):(WStocksData.push(sd));
        }

        
        wind['WStocksData']=WStocksData;
        wind['isAllSKUChecked']=val==1?1:0;
        console.log('wind updated');
        win_index>=0?allData[win_index]=wind:allData.push(wind);
        
        // setWindowData(allData);
        BgWindowData(allData);
        // setHasUnsavedChanges(true);
        BgUnsavedChanges(true)
        setrerenderdata(!rerenderdata);
    }

    function onSaveCancel(){
        setShowAlert(false);
    }

  

    function openImageRefView(windowIndex=0){
        setrefImageIndex(windowIndex);
        setShow_zoomImage(true);
    }

    function openImageRefView2(ImageIndex=0,wind_index,Type='2'){
        if(Type=='1'){
            let wind=Windows[wind_index];
            const windDataIndex=WindowData.findIndex(i=>i.PromoId==wind.PromoId && i.PromoDefinitionId==wind.PromoDefinitionId) ;
            const windData=windDataIndex>=0?windData[windDataIndex]:{};
            let zoomIRImages=windData.zoomIRImages!=null && windData.zoomIRImages!=""? windData.zoomIRImages:[];
            setZoomImageUrl2(zoomIRImages);
        }
        setrefImageIndex2(ImageIndex);
        UpdateShow_zoomImageRef2(true);
    }

    function FilterStores(searchedQry){
        searchedQry=searchedQry.toLowerCase();
        console.log('searchedQry',searchedQry);
        let arr=[];
        let newWindows=[];
        if(searchedQry!=null && searchedQry!=''){
            
            for(let i=0;i<globalWindows.length;i++){
                let item=globalWindows[i];
                let {PromoName}=item;
                if(PromoName.toLowerCase().includes(searchedQry)){
                    newWindows.push(item);
                }

                if(i==globalWindows.length-1){
                    arr=newWindows;
                }
            }
        }
        else{
          arr=globalWindows;
        }

        setWindows(arr);
        setrerenderdata(!rerenderdata)
        setrerenderdata2(!rerenderdata2)
    }

    function renderRatingView(){
        let qtn=RatingQtn;
        let Answers=qtn.Answers;
        let id_key=qtn.PromoQuestionId+'_AnswerId'; 
        let ans_key=qtn.PromoQuestionId+'_Answer'; 
        let rating_key=qtn.PromoQuestionId+'_Rating'; 
        
        let newarr=RatingOrder;
        if(RatingOrder.length<=0){
            newarr=Answers;
        }

        return (
        <View style={customStyle.RatingModal}>
            <View style={customStyle.RatingModalCon}>
                <Text style={customStyle.VRModalHeding}>{ST.DragItemsInOrder}</Text>
                <Text style={customStyle.VRSubHeding}>{ST.Pressandholdtodrag}</Text>
                <DraggableFlatList
                    data={newarr}
                    style={customStyle.RModal_list}
                    contentContainerStyle={customStyle.RModal_listInner}
                    onDragEnd={({ data }) =>{setRatingValue(data)}}
                    keyExtractor={(item) => item.AnswerId}
                    renderItem={renderItem}
                />
                <View style={customStyle.RModal_Btns}>
                    <TouchableOpacity style={customStyle.RModal_BtnCancel} onPress={()=>{onRatingCancel()}}>
                        <Text style={customStyle.RModal_BtnTextCancel}>{ST.Cancel}</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={customStyle.RModal_Btnsave} onPress={()=>{onRatingSave()}}>
                        <Text style={customStyle.RModal_BtnTextsave}>{ST.Save}</Text>
                    </TouchableOpacity>
                </View>
            </View>
        </View>
        )
    }

    function render_Picker(label_key,value_key,onChange=()=>{},selected_data={},errorStyle={}){
        var data=[];
        let qtn=selected_data.qtn || {};
        let window=selected_data.window || {};
        let isQtnDisabled=qtn.isDisabled!=null || qtn.isDisabled!=''?false:true;
        let allAnswers=qtn.Answers || [];
        
        allAnswers.map((item,index)=>{
            let obj={ key: index, label: item[label_key],value:item[value_key] };
            if(selected_data.value==item[label_key])
                obj['component']= <View style={customStyle.addvis_selectedOpStyle}><Text style={customStyle.addvis_selectedOpTextStyle}>{item[label_key]}</Text></View>;
            data.push(obj);
        });
        
        return (
            <ModalSelector
            data={data}
            
            touchableActiveOpacity={0.8}
            
            style={customStyle.addVisPickerStyle}
            onChange={(option)=>{onChange(option,qtn,window) }}
            overlayStyle={customStyle.addVisPickerOverlay}
            cancelContainerStyle={customStyle.addVisPicker_OptionContainerStyle}
            optionStyle={customStyle.addvis_opStyle}
            optionTextStyle={customStyle.addvis_opTextStyle}
            optionContainerStyle={customStyle.addVisPicker_OptionContainerStyle}
            selectedKey={'1'}
            disabled={isQtnDisabled}
            >
            <Text style={[customStyle.WQPicker_InputStyle,(isQtnDisabled?customStyle.addVisPicker_Dis_InputStyle:{}),errorStyle]}>{(selected_data.value!=null && selected_data.value!=''?selected_data.value: '-'+ST.select+'-')}</Text>
            </ModalSelector>
        )
    }

    function renderDatePicker(qtn,window){
        let qtnn=qtn;
        let DateRange=qtn.DateRange;
        let maxDate=moment().add(10,'years').format('MM/DD/YYYY');
        let minDate=moment().subtract(10,'years').format('MM/DD/YYYY');
        if(DateRange=='RFD'){
            maxDate=moment().format('MM/DD/YYYY');
        }
        else if(DateRange=='RPD'){
            minDate=moment().format('MM/DD/YYYY');
        }
        
        return (
            <DateTimePicker
            testID="dateTimePicker"
            value={(dateValue!=null && dateValue!=''?new Date(dateValue):new Date())}
            mode={'date'}
            display="default"  
            onChange={(event, selectedDate)=>{setTextValue(selectedDate,qtnn,window)}}
            maximumDate={new Date(maxDate)}
            minimumDate={new Date(minDate)}
            />    
        );
    }

    async function OpenImgModal(imgPath,window,splitItem,splitItemIndex,cameraType){
        setSelectedImg(imgPath)
        setShowModal(true);
        if((imgPath!='' && imgPath!=null)){
            setShowImageSaveOp(false);
        }
        else{
            setShowImageSaveOp(true);
        }
        setReCapImgModalObj({window,splitItem,splitItemIndex,cameraType})
        // _OpenCaptureImage_Modal(imgPath,window,splitItem,splitItemIndex,cameraType)
        
      }

      function cancelImage(){
        // setImage1('');
        setSelectedImg('');
        setReCapImgModalObj({})
        setShowModal(false);
      }

      async function getIRZoomImages(IRCamImages){
        return new Promise((resolve,reject)=>{
            let z_images=[];
            for(let ci in IRCamImages){
                let img=IRCamImages[ci];
                let img_obj={imgIndex:(ci+1),url: img.ImagePath, props: {}}
                
                z_images.push(img_obj);
                if(ci==IRCamImages.length-1){
                    resolve(z_images)
                }
            }
        }).catch((err)=>{
            console.log(err);
            return [];
        })
    }

      async function StartCameraSession(wind,type='1'){
        // type: 1 or 2 , 1: Camera enabled for each window header ,2 : Camera enabled for once in KPI
        let IR_Creds=props.IR_Creds!=null && props.IR_Creds!=""?JSON.parse(props.IR_Creds):[];
        let IR_CredsObj=IR_Creds.length>0?IR_Creds[0]:{};

        wind=wind!=null?wind:{};
        let newStdata=storeData;
        if(IR_CredsObj.UseStoreCode!=1){
            newStdata.StoreCode=newStdata.StoreId;
        }
        let obj={"StoreData":newStdata};
         
        // Option values for Perfetti paid visibility if IR shown in header only
        // obj["category_name"]="multi";
        // obj["task_name"]="paid-visibility-displays";
        // obj["photo_type"]="paid-visibility";
        let task_name=windIRParams.task_name+" "+currentMenu.MenuId+" "+wind?.PromoDefinitionId;
        obj["category_name"]=windIRParams.category_name || '';
        obj["task_name"]=task_name;
        obj["photo_type"]=windIRParams.photo_type || '';

        let st1=JSON.stringify(obj);
        let TempSessionId= await IRLogin.StartIRSession(st1);
        console.log(' StartCameraSession TempSessionId,task_name:',TempSessionId,",",task_name);
        if(TempSessionId!=null){
            setLoaderTitle('Processing Image...');
            setProcessing(true);
            let IRCamImages=await IRLogin.getImageURIFromIRSession(TempSessionId);
            console.log('Images from session :',IRCamImages);

            if(type=='2'){ //set global IR images and session id if Camera is shown only once in header for KPI Screen
                // setGbTempSessionId(TempSessionId);
                GbTempSessionId.current=TempSessionId;
                let sessObj={}
                sessObj['Sess_StoreCode'] =newStdata.StoreCode;
                sessObj['Sess_TaskName'] =obj["task_name"];
                sessObj['Sess_CatName'] =obj["category_name"];
                sessObj['Sess_PhotoType'] =obj["photo_type"];
                GbTempSessionObj.current=sessObj;
                WindowIRImages.current=IRCamImages;
                setIRZoomImages(IRCamImages);
            }
            else{ //set category wise IR images and session id if Camera is shown for each window
                let zoomIRImages=await getIRZoomImages(IRCamImages)

                let allData=WindowData;
                let defData={'PromoId':wind.PromoId,'PromoDefinitionId':wind.PromoDefinitionId};
                const win_index=allData.findIndex(i=>i.PromoId==wind.PromoId && i.PromoDefinitionId==wind.PromoDefinitionId);
                let windData=win_index>=0?(allData[win_index] || defData) : defData;
                windData['IRImages'] =IRCamImages;
                windData['zoomIRImages'] =zoomIRImages;
                windData['TempSessionId'] =TempSessionId;
                windData['Sess_StoreCode'] =newStdata.StoreCode;
                windData['Sess_TaskName'] =obj["task_name"];
                windData['Sess_CatName'] =obj["category_name"];
                windData['Sess_PhotoType'] =obj["photo_type"];
                win_index>=0?allData[win_index]=windData:allData.push(windData);
                WindowIRImages.current=IRCamImages;
                
                // setWindowData(allData);
                BgWindowData(allData);
            }

            // setHasUnsavedChanges(true);
            BgUnsavedChanges(true);
            setrerenderdata(!rerenderdata);
            
            // stop image processing loader after all images get from sessionID
            setProcessing(false);
            setLoaderTitle('loading...');
            
        }
        else{
            notify('Cannot capture images as getting Session Null.');
        }
        
    }


    async function ResumeCameraSession(wind,type='1'){
        // type: 1 or 2 , 1: Camera enabled for each window header ,2 : Camera enabled for once in KPI
        wind=wind!=null?wind:{};
        let allData=WindowData;
        let defData={'PromoId':wind.PromoId,'PromoDefinitionId':wind.PromoDefinitionId};
        const win_index=allData.findIndex(i=>i.PromoId==wind.PromoId && i.PromoDefinitionId==wind.PromoDefinitionId);
        let windData=win_index>=0?(allData[win_index] || defData) : defData;
        
        // Resume Temp Session Id
        let TempSessionId="";
        if(type=='2'){
            TempSessionId= GbTempSessionId.current;
        }
        else{
            TempSessionId= windData.TempSessionId;
        }
        console.log('TempSessionId of wind :',TempSessionId);
        if(TempSessionId!=null){
            setLoaderTitle('Processing Image...');
            setProcessing(true);
            let retTempSessionId=await IRLogin.ResumeIRSession(TempSessionId);
            console.log('retTempSessionId :',retTempSessionId);
            if(retTempSessionId!=null){
                // start fetching images after capturing photos

                let IRCamImages=await IRLogin.getImageURIFromIRSession(TempSessionId);
                console.log('Images from session :',IRCamImages);

                if(type=='2'){
                    // setWindowIRImages(IRCamImages);
                    WindowIRImages.current=IRCamImages
                    setIRZoomImages(IRCamImages);
                }
                else{
                    let zoomIRImages=await getIRZoomImages(IRCamImages)
                    windData['IRImages'] =IRCamImages;
                    windData['zoomIRImages'] =zoomIRImages;
                    win_index>=0?allData[win_index]=windData:allData.push(windData);
                    // setWindowData(allData);
                    BgWindowData(allData);
                }
                // setHasUnsavedChanges(true);
                BgUnsavedChanges(true);
                setrerenderdata(!rerenderdata);
                
                // stop image processing loader after all images get from sessionID
                setProcessing(false);
                setLoaderTitle('loading...');
            }
            else{
                notify('Cannot capture images as getting Session Null.');
            }
            
        }
        else{
            notify('Cannot capture images as getting Session Null.');
        }
        
    }

      function _OpenCaptureImage_Modal(img){
       
        const isImageCap=(img!='' || img!=null)?true:false;
       
        let {window,splitItem,splitItemIndex,cameraType}=reCapImgModalObj
        let camera2Label=window!=null && window.PromoImage1Lable!=null?window.PromoImage1Lable:'';
        return (
          <CustomModal 
            style={customStyle.PromoImgModal}
            title={"Promotion Image"}
            message={camera2Label}
            titleStyle={customStyle.PromoImgModal_title}
            messageStyle={customStyle.PromoImgModal_subtitle}
            showModal={showModal}
          >
            { 
            isImageCap && 
            <View style={customStyle.PromoImgModalCon}>
              <View style={customStyle.PromoImgModal_ImgWrap}>
              
                <Image  style={[customStyle.PromoImgModal_Img,(Platform.OS=='ios' ?customStyle.android_flipIMageView:{})]} source={{uri:SelectedImg}} />
              </View>
              <TouchableOpacity style={customStyle.PromoImgModal_CameraSmall} onPress={()=>{openCamera(window,splitItem,splitItemIndex,cameraType)}}>
                <MaterialCommunityIcons name='camera-retake' size={30} color={PageTheme.$primary_color}/>
              </TouchableOpacity>
              
              {!showImageSaveOp &&
                <TouchableOpacity style={customStyle.PromoImgModal_Cancel_btn} onPress={()=>{cancelImage()}}>
               
                  <Text style={customStyle.PromoImgModal_Cancel_btnText}>{ST.Close}</Text>
                </TouchableOpacity>
              }
            </View>
            }
          </CustomModal>
        )
      }

      async function DeleteIRPhoto(){
        console.log('DeleteIRPhoto called');
        setshowRetakeModal(false);
        let {wind,type,IRImgIndex,IRimgPath}= retakeMData;
        // type: 1 or 2 , 1: Camera enabled for each window header ,2 : Camera enabled for once in KPI
        
        wind=wind!=null?wind:{},
        type=type!=null?type:'1';
        IRImgIndex=IRImgIndex!=null?IRImgIndex:'';
        IRimgPath=IRimgPath!=null?IRimgPath:'';
        

        let allData=WindowData;
        let defData={'PromoId':wind.PromoId,'PromoDefinitionId':wind.PromoDefinitionId};
        const win_index=allData.findIndex(i=>i.PromoId==wind.PromoId && i.PromoDefinitionId==wind.PromoDefinitionId);
        let windData=win_index>=0?(allData[win_index] || defData) : defData;
       
        let TempSessionId="";
        if(type=='2'){
            TempSessionId=GbTempSessionId.current;
        }
        else{
            TempSessionId=windData['TempSessionId'];
        }

        console.log('DeleteIRPhoto sessionID :',TempSessionId);
        if(TempSessionId!=null || TempSessionId!=''){
            setLoaderTitle('Removing Image...');
            setProcessing(true);
            let isDeleted= await IRLogin.DeleteIRSessionPhoto(TempSessionId,IRimgPath);//"8099b819-0979-40d2-950e-489566041484";//
            console.log('DeleteIRPhoto isDeleted :',isDeleted);
            if(isDeleted){
                setLoaderTitle('Processing Image...');
                
                let IRCamImages=await IRLogin.getImageURIFromIRSession(TempSessionId);
                console.log('Deleted, Images from session :',IRCamImages);
                if(type=='2'){
                    // setWindowIRImages(IRCamImages);
                    WindowIRImages.current=IRCamImages;
                    setIRZoomImages(IRCamImages);
                }
                else{
                    let zoomIRImages=await getIRZoomImages(IRCamImages)
                    windData['IRImages'] =IRCamImages;
                    windData['zoomIRImages'] =zoomIRImages;
                    win_index>=0?allData[win_index]=windData:allData.push(windData);
                    // setWindowData(allData);
                    BgWindowData(allData);
                }
                
                // setHasUnsavedChanges(true);
                BgUnsavedChanges(true);
                setrerenderdata(!rerenderdata);
                
                // stop image processing loader after all images get from sessionID
                setProcessing(false);
                setLoaderTitle('loading...');
                
            }
            else{
                notify('Cannot delete photo!.');
            }

        }
        else{
            notify('Cannot delete photo! Found Null Session.');
        }
        
    }

      async function RetakeIRPhoto(){
        setshowRetakeModal(false);
        let {wind,type,IRImgIndex,IRimgPath}= retakeMData;
        // type: 1 or 2 , 1: Camera enabled for each window header ,2 : Camera enabled for once in KPI
        
        wind=wind!=null?wind:{},
        type=type!=null?type:'1';
        IRImgIndex=IRImgIndex!=null?IRImgIndex:'';
        IRimgPath=IRimgPath!=null?IRimgPath:'';
        

        let allData=WindowData;
        let defData={'PromoId':wind.PromoId,'PromoDefinitionId':wind.PromoDefinitionId};
        const win_index=allData.findIndex(i=>i.PromoId==wind.PromoId && i.PromoDefinitionId==wind.PromoDefinitionId);
        let windData=win_index>=0?(allData[win_index] || defData) : defData;
       
        let TempSessionId="";
        if(type=='2'){
            TempSessionId=GbTempSessionId.current;
        }
        else{
            TempSessionId=windData['TempSessionId'];
        }

        console.log('Retake sessionID :',TempSessionId);
        if(TempSessionId!=null || TempSessionId!=''){
            setLoaderTitle('Processing Image...');
            setProcessing(true);
            let isRetakeDone= await IRLogin.RetakeIRSessionPhoto(TempSessionId,IRimgPath);
            console.log('Retake isRetakeDone :',isRetakeDone);
            if(isRetakeDone){
                setTimeout(async ()=>{
                    let IRCamImages=await IRLogin.getImageURIFromIRSession(TempSessionId);
                    console.log('Retake Images from session :',IRCamImages);
                    if(type=='2'){
                        // setWindowIRImages(IRCamImages);
                        WindowIRImages.current=IRCamImages;
                        setIRZoomImages(IRCamImages);
                    }
                    else{
                        let zoomIRImages=await getIRZoomImages(IRCamImages)
                        windData['IRImages'] =IRCamImages;
                        windData['zoomIRImages'] =zoomIRImages;
                        win_index>=0?allData[win_index]=windData:allData.push(windData);
                        // setWindowData(allData);
                        BgWindowData(allData);
                    }
                    // setHasUnsavedChanges(true);
                    BgUnsavedChanges(true);
                    setrerenderdata(!rerenderdata);
                    
                    // stop image processing loader after all images get from sessionID
                    setProcessing(false);
                    setLoaderTitle('loading...');
                },1000);

            }
            else{
                notify('Error occur while retaking photo!.');
            }

        }
        else{
            notify('Cannot start camera! Found Null Session.');
        }
        
    }
 //start IR functions 
 function openRetakeOp(wind, type='1',IRImgIndex,IRimgPath){
    let data={'wind':wind,'type':type,'IRImgIndex':IRImgIndex,'IRimgPath':IRimgPath};
    setretakeMData(data);
    setshowRetakeModal(true);
}

    function closeRetakeOp(){
        setretakeMData({})
        setshowRetakeModal(false);
    }

      function _render_RetakePopup(){
        return (
          <CustomModal 
            style={customStyle.storelVisitM_Style}
            titleStyle={customStyle.storelVisitM_titleStyle}
            title={'If any image is blurred you can "Retake" or "Delete" the Image?'}
            showModal={showRetakeModal}
          >
            <View style={customStyle.IRretakeM_options}>
              <TouchableOpacity style={customStyle.IRretakeM_optionsBtn} onPress={()=>{RetakeIRPhoto()}}>
                <View style={customStyle.IRretakeM_optionsInn}>
                    <MaterialCommunityIcons name='camera-retake' size={20} color={PageTheme.$primary_color}/>    
                    <Text style={customStyle.IRretakeM_optionsBtnText}>Retake</Text>
                </View>
              </TouchableOpacity>
              <TouchableOpacity style={customStyle.IRretakeM_optionsBtn} onPress={()=>{DeleteIRPhoto()}}>
                <View style={customStyle.IRretakeM_optionsInn}>
                    <FontAwesome name='trash' size={20} color={PageTheme.$red}/>     
                    <Text style={customStyle.IRretakeM_optionsBtnText}>Delete</Text>
                </View>
              </TouchableOpacity>
              <TouchableOpacity style={customStyle.IRretakeM_optionsBtn} onPress={()=>{closeRetakeOp()}}>
                <View style={customStyle.IRretakeM_optionsInn}>
                    <Entypo name='cross' size={20} color={PageTheme.$red}/> 
                    <Text style={customStyle.IRretakeM_optionsBtnText}>Cancel</Text>
                </View>
              </TouchableOpacity>
             
            
              
            </View>
          </CustomModal>
        )
      }

      function _render_UploadAlert(){
        return (
          <CustomModal 
            style={customStyle.storelVisitM_Style}
            titleStyle={customStyle.storelVisitM_titleStyle}
            title={'Upload IR Images! You cannot edit after images uploaded to the server!'}
            showModal={showUploadAlert}
          >
            <View style={customStyle.storelVisitM_options}>
             <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={()=>{setshowUploadAlert(false)}}>
                <Text style={customStyle.storelVisitM_op_btnText}>Cancel</Text>
              </TouchableOpacity>
              <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={()=>{UploadIRSessions()}}>
                <Text style={customStyle.storelVisitM_op_btnText}>Yes</Text>
              </TouchableOpacity>
            </View>
          </CustomModal>
        )
    }
  
      function _renderIRCamera(wind,IRImages,TempSessionId,type='1',wind_index=''){
        
        let isSaveDisabled=(isDataUploaded=='U' || isDataUploaded=='P');
        let isResumeDisabled=(TempSessionId==null || TempSessionId=='' || TempSessionId=='undefined' || isSaveDisabled==true);
                
        return (
            <View style={(type=='2'?customStyle.IRCamOnceWrap:[customStyle.openStk_prd_borderT,customStyle.pt10])}>
                <View style={customStyle.SOSheadingsCon}>
                    <Text style={customStyle.SOSheadingsText}>{`Capture ${currentMenu.MenuName} Images`}</Text>
                </View>
                <View style={[customStyle.IRCamWrapper]}>
                    <View style={customStyle.IRCamImgWrap}>
                    { (IRImages!=null && IRImages.length>0) && 
                        IRImages.map((IRImg,IRImgIndex)=>{
                            let IRimgPath=IRImg.ImagePath;
                            return(
                                <TouchableOpacity style={customStyle.IRCamImageView} key={IRImgIndex} onPress={()=>{openImageRefView2(IRImgIndex,wind_index,type)}}>
                                    {(IRimgPath!=null && IRimgPath!='') && <Image style={customStyle.IRCamImage} source={{uri:IRimgPath}}/>}
                                    {(IRimgPath==null || IRimgPath=='') && <View style={customStyle.IRCamImage}></View>}
                                    <TouchableOpacity style={[customStyle.IRCamImage_OpBtn,isSaveDisabled?{backgroundColor:PageTheme.$text_color_light}:{}]} disabled={isSaveDisabled} onPress={()=>{openRetakeOp(wind,type,IRImgIndex,IRimgPath)}}>
                                        <MaterialCommunityIcons name='camera-retake' size={15} color={PageTheme.$accent_color}/>                                   
                                    </TouchableOpacity>
                                </TouchableOpacity>  
                            );
                        })
                                                        
                    } 
                    </View>     
                    <View style={[customStyle.IRCamCon,(type=='2'?customStyle.IRCamConBG:{})]}>
                        <TouchableOpacity style={[customStyle.IRCamBtns,customStyle.IRCamStartSess]} disabled={isSaveDisabled} onPress={()=>{StartCameraSession(wind,type)}}>   
                            <AntDesign name='play' size={30} color={(isSaveDisabled?PageTheme.$text_color_light:PageTheme.$primary_color)}/>
                            <Text style={[customStyle.IRCamBtnsText,(isSaveDisabled?{color:PageTheme.$text_color_light}:{})]}>Start Session</Text>
                        </TouchableOpacity> 
                        <TouchableOpacity style={[customStyle.IRCamBtns,customStyle.IRCamStartSess]} disabled={isResumeDisabled} onPress={()=>{ResumeCameraSession(wind,type)}} >   
                            <AntDesign name='pausecircle' size={30} color={(isResumeDisabled?PageTheme.$text_color_light:PageTheme.$primary_color)}/>
                            <Text style={[customStyle.IRCamBtnsText,(isResumeDisabled?{color:PageTheme.$text_color_light}:{})]}>Resume Session</Text>
                        </TouchableOpacity>   
                    </View>      
                </View>
            </View>
        )
      }

    function _renderWindow(){
        let RemarkEnableIndex=KPIFields.findIndex(i=>i.KPIFieldName=='RemarkEnable')
        let RemarkEnableKPIObj=RemarkEnableIndex>=0?KPIFields[RemarkEnableIndex]:{};
        let RemarkEnable=RemarkEnableIndex>=0?RemarkEnableKPIObj['KPIFieldEnable']:false;

        let isListedSKUIndex=KPIFields.findIndex(i=>i.KPIFieldName=='ListedSKUCheckbox');
        let isListedSKUKPIObj=isListedSKUIndex>=0?KPIFields[isListedSKUIndex]:{};
        let isListedSKUEnable=isListedSKUIndex>=0?isListedSKUKPIObj['KPIFieldEnable']:true;

        let HidePresentYesNoIndex=KPIFields.findIndex(i=>i.KPIFieldName=='HidePresentYesNo');
        let HidePresentYesNoObj=HidePresentYesNoIndex>=0?KPIFields[HidePresentYesNoIndex]:{};
        let HidePresentYesNoEn=HidePresentYesNoIndex>=0?HidePresentYesNoObj['KPIFieldEnable']:false;
        let HidePresentYesNoEnable=HidePresentYesNoEn==1 || HidePresentYesNoEn=="1" || HidePresentYesNoEn==true?true:false;

        let isKPIIREnableI=KPIFields.findIndex(i=>i.KPIFieldName=='IR_KPIEnable')
        let isKPIIREnableObj=isKPIIREnableI>=0?KPIFields[isKPIIREnableI]:{};
        let isKPIIREnable=isKPIIREnableI>=0?isKPIIREnableObj['KPIFieldEnable']:false;

        let CameraIROnceOnlyIndex=KPIFields.findIndex(i=>i.KPIFieldName=='IR_CameraOnceOnly')
        let CameraIROnceOnlyObj=CameraIROnceOnlyIndex>=0?KPIFields[CameraIROnceOnlyIndex]:{};
        let CameraIROnceOnly=CameraIROnceOnlyIndex>=0?CameraIROnceOnlyObj['KPIFieldEnable']:true;
        
        
        return (
            <FlatList 
            data={Windows}
            extraData={rerenderdata}
            contentContainerStyle={customStyle.Win_scroll} 
            style={customStyle.Win_scrollO}
            initialNumToRender={5}
            viewabilityConfigCallbackPairs={
                FlatLConfCallbackPairs.current
            }
            listKey={(item, index) => `window_${index.toString()}`}
            renderItem={({item,index})=>{
                const window=item;
                let windowIndex=index;
                
                let isImage1=window.PromoImage1=='true' || window.PromoImage1==1?1:0;
                let isImage2=window.PromoImage2=='true' || window.PromoImage2==1?1:0;
                let isNAImageAvl=window.PromoNotExistCamera=='true' || window.PromoNotExistCamera==1?1:0;
                let isNAReasonEnable=window.PromoNotExistReasonEnable=='true' || window.PromoNotExistReasonEnable==1? 1:0;
                let isReasonEnable=window.PromoExistReasonEnable=='true' || window.PromoExistReasonEnable==1? 1:0;
                let isStockReq=window.PromoElementStockRequired=='true' || window.PromoElementStockRequired==1?1:0;
                let StockQtyRequired=window.StockQtyRequired=='true' || window.StockQtyRequired==1?1:0;
                let PromoTitleEnable=window.PromoDefinitionTitleEnable=='true' || window.PromoDefinitionTitleEnable==1? 1:0;
                let PromoTitle=window.PromoDefinitionTitle!=null && window.PromoDefinitionTitle!='undefined'? window.PromoDefinitionTitle:"";
                let PromoRefImagePopUp=window.PromoRefImagePopUp=='true' || window.PromoRefImagePopUp==true? true:false;

                // let isStock_CheckAssrt=window.PromoElementCheckAssortment=='true' || window.PromoElementCheckAssortment==1?1:0;
                let RefImage=window.PromoRefImage;
                let camera1Label=window.PromoImage1Lable || '';
                let camera2Label=window.PromoImage2Lable || '';
                let WindowQuestions=window.WindowQuestions || [];
                let WindowStocks=window.WindowStocks || [];
                
                let isVisible=Boolean(ItemsInView.find(({item:i,isViewable}) => i.PromoId==window.PromoId && i.PromoDefinitionId==window.PromoDefinitionId && isViewable))

                // const wind=WindowData.find(i=>i.PromoId==window.PromoId && i.PromoDefinitionId==window.PromoDefinitionId);
                const wind_I=WindowData.findIndex(i=>i.PromoId==window.PromoId && i.PromoDefinitionId==window.PromoDefinitionId);
                const wind=wind_I!=null && wind_I>=0?WindowData[wind_I]:{};
                let isPresent=wind.isPresent!=null && wind.isPresent!=''?wind.isPresent:'0';
                let ReasonId=wind.ReasonId!=null?wind.ReasonId:'';
                let Reason=wind.Reason!=null?wind.Reason:'';
                let showOtherText=wind.showOtherText!=null?wind.showOtherText:false;
                let RemarkText=wind.RemarkText!=null?wind.RemarkText:'';
                let NAImage1=wind.NAImage1!=null?wind.NAImage1:'';
                let NAImage1Path=wind.NAImage1Path!=null?wind.NAImage1Path:'';
                let remark=wind.remark!=null?wind.remark:'';
                let WindowSplits=wind.WindowSplits || [];
                let QuestionsData=wind.WindowQA || {};
                let WStocksData=wind.WStocksData || [];
                let isAllSKUChecked=wind.isAllSKUChecked==1 || wind.isAllSKUChecked=="1";

                let windIRImages=wind['IRImages']!=null?wind['IRImages'] : [] ;
                let TempSessionId= wind.TempSessionId!=null?wind.TempSessionId:'';
                
                // console.log('camera2Label:',window.PromoId,window.PromoDefinitionId,camera2Label);\
                var xpos=(isPresent=='1'||isPresent==1)?-75:0;
                if(window.animatedChoice!=null ){
                    xpos=window.animatedChoice.interpolate({
                        inputRange:[0,1],
                        outputRange:[0,-75],
                    });
                }

                if(isVisible && window.animatedHeight!=null){
                    setTimeout(()=>{
                    Animated.timing(window.animatedHeight, {
                        toValue: 0,
                        duration: 800,
                        useNativeDriver: false,
                        }).start();
                    },(props.RefImagePopUpTime||0)*1000)
                }
                let EF_Window=errorfield.EF_Window!=null ?errorfield.EF_Window:{};
                let show_errorhere=error==true && EF_Window.PromoId==window.PromoId && EF_Window.PromoDefinitionId==window.PromoDefinitionId;
                // if not Present fields

                // this will show error field in red (if window is present and exist reason is enabled and not filled ) or (if window is not present and Not exist reason is enabled and not filled ) 
                let EF_NExistReason=errorfield.EF_NExistReason || '';
                let EStyle_NExistReason=show_errorhere && EF_NExistReason=='NExistReason'?customStyle.stk_inptSTyle_error:{};
                
                let EF_NExistRemark=errorfield.EF_NExistRemark || '';
                let EStyle_NExistRemark=show_errorhere && EF_NExistRemark=='NExistRemark'?customStyle.stk_inptSTyle_error:{};
                
                let EF_NExistImage=errorfield.EF_NExistImage || '';
                let EStyle_NExistImage=show_errorhere && EF_NExistImage=='NExistImage'?customStyle.error_CatImage2:{};
                
                

                return(
                    <View style={customStyle.WItem_wrap} key={'window_'+index}>
                        <View style={customStyle.WItem_Hdr}>                            
                            <View style={customStyle.WItem_Hdrbg}>
                                <Text style={customStyle.WItem_HdrText}>{window.PromoName}</Text>
                                {
                                    window && window.ChildName !="" && <Text style={[customStyle.WItem_Hdrname2]}>{window.ChildName}</Text>
                                }
                                
                                {(PromoTitleEnable==1 && PromoTitle!=null && PromoTitle!='') && <Text style={customStyle.WItem_HdrSubTitleText}>{PromoTitle}</Text>}
                                <TouchableOpacity style={customStyle.WItem_RefImgBtn} onPress={()=>{openImageRefView(index)}}>
                                    <Entypo name='image-inverted' size={24} color={PageTheme.$accent_color} />    
                                </TouchableOpacity>
                            </View>
                        </View>
                        { PromoRefImagePopUp && <Animated.View
                                style={[{
                                        backgroundColor: "#fff",
                                        width: "100%",
                                        height: window.animatedHeight,
                                        paddingBottom:10
                                    }]}
                                >
                                <Image  style={[{width:"100%",height:'100%'}]} resizeMode='contain' source={{uri:RefImage}} />
                                
                            </Animated.View>}
                        <View style={customStyle.WForm}>
                            <View style={[customStyle.openStk_prd_cols,customStyle.mt10]}>
                                
                                {!HidePresentYesNoEnable && 
                                <View style={[customStyle.openStk_prd_colflex,customStyle.mb10]}>
                                    <Text style={[customStyle.openStk_prd_label,customStyle.openStk_prd_flexlabel]}>{ST.IsPresent}</Text>
                                    <View style={customStyle.openStk_prd_choiceBoxCon}>
                                        <View style={customStyle.openStk_prd_choiceBox}>
                                        <Animated.View style={[customStyle.openStkCh_absolutebg,customStyle.openStkCh_con_active,((isPresent=='1'||isPresent==1)?customStyle.openStkCh_con_green:customStyle.openStkCh_con_red),
                                            {   transform: [{   translateX:xpos }],  }]}></Animated.View>
                                            <TouchableOpacity style={customStyle.openStkCh_con1} onPress={()=>{onChoiceSelect(window,1,'isPresent',window.animatedChoice)}}>
                                                <Text style={[customStyle.openStkCh_text,((isPresent=='1'||isPresent==1)?customStyle.openStkCh_textactive:{})]}>{ST.Yes}</Text>
                                            </TouchableOpacity>
                                            <TouchableOpacity style={[customStyle.openStkCh_con1]} onPress={()=>{onChoiceSelect(window,0,'isPresent',window.animatedChoice)}}>
                                                <Text style={[customStyle.openStkCh_text,((isPresent=='0'||isPresent==0)?customStyle.openStkCh_textactive:{})]}>{ST.No}</Text>
                                            </TouchableOpacity>
                                        </View>
                                    </View>
                                </View>
                                }
                                {((isPresent!='1' && isNAReasonEnable==true) || (isPresent=='1' && isReasonEnable==true)) &&
                                    <View style={[customStyle.openStk_prd_colflex,(!HidePresentYesNoEnable?customStyle.openStk_prd_borderT3:{}),customStyle.mb10]}>
                                        <Text style={[customStyle.openStk_prd_label,customStyle.openStk_prd_flexlabel]}>{ST.SelectReason}</Text>
                                        {<CustomPicker2 {...props} Pickerdata={reasons_list} label_key={'Reason'} value_key={'ReasonId'} onchangeKeyLbl={'Reason'} onchangeKey={'ReasonId'} onChange={onselectionChange} selected_data={{value:Reason,otherData:{window:window}}} InputStyle={customStyle.PV_selectInputStyle} selectStyle={customStyle.PV_selectStyle} ErrorStyle={EStyle_NExistReason} ShowError={error} />}
                                    </View>
                                }
                                {isPresent!='1' && showOtherText==true && 
                                    <View style={[customStyle.openStk_prd_colflex,customStyle.openStk_prd_borderT,customStyle.pt10]}>
                                        <Text style={[customStyle.openStk_prd_label,customStyle.openStk_prd_flexlabel]}>{ST.EnterRemark}</Text>
                                        <TextInput 
                                            style={[customStyle.openStk_prd_inputStyle,customStyle.openStk_prd_flex_inputStyle,EStyle_NExistRemark]}              
                                            placeholder=""  
                                            autoComplete='off'          
                                            placeholderTextColor={PageTheme.$placeholder_color} 
                                            value={RemarkText}
                                            onChangeText={(val)=>{onCatTextChange(window,'RemarkText',val,'text')}}
                                        />
                                    </View>
                                }


                                {(isPresent!='1' && isNAImageAvl==true) && 
                                <View>
                                    <View style={[customStyle.openStk_prd_borderT,customStyle.pt10,customStyle.mb10]}>
                                    <LinearGradient colors={[PageTheme.$secondary_color_light,PageTheme.$fourth_color,PageTheme.$secondary_color_light]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.windhdrTextCon}>
                                        <Text style={customStyle.windhdrText}>{ST.CaptureImage}</Text>
                                    </LinearGradient>
                                   
                                    {/* { _renderIRCamera(window,windIRImages,TempSessionId,'1',windowIndex)} */}

                                    <View style={[customStyle.openStk_prdCameras,customStyle.WSCameraWrap]}>
                                        <View style={[customStyle.openStkCameraCon,customStyle.WSCameraCon]}>
                                        { (NAImage1Path=='' || NAImage1Path==null) && 
                                            <TouchableOpacity style={[customStyle.osCat_action_openCam,customStyle.osCat_actn_margin,EStyle_NExistImage]} onPress={()=>{openCamera(window,{},0,'1','3')}}>
                                                <CameraImg width={80} height={80} />                                     
                                            </TouchableOpacity>
                                        }
                                        { (NAImage1Path!='' && NAImage1Path!=null) && 
                                            <View style={customStyle.osCatImageView}>
                                                <Image style={customStyle.osCatImage} source={{uri:NAImage1Path}}/>
                                                <TouchableOpacity style={[customStyle.osCat_action_reCap]} onPress={()=>{openCamera(window,{},0,'1','3')}}>
                                                    <MaterialCommunityIcons name='camera-retake' size={20} color={PageTheme.$accent_color}/>                                   
                                                </TouchableOpacity>
                                            </View>                                    
                                        }   
                                        </View>
                                    </View>
                                    </View>
                                    
                                </View>
                                }

                                {(isPresent=='1') && 
                                <View>
                                    
                                { isKPIIREnable && !CameraIROnceOnly && 
                                _renderIRCamera(window,windIRImages,TempSessionId,'1',windowIndex)}

                                    {(isStockReq==true && WindowStocks.length>0) &&
                                    <View style={[(!HidePresentYesNoEnable?customStyle.openStk_prd_borderT3:{})]}>
                                    <LinearGradient colors={[PageTheme.$secondary_color_light,PageTheme.$fourth_color,PageTheme.$secondary_color_light]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.windhdrTextCon}>
                                        <Text style={customStyle.windhdrText}>{(isListedSKUEnable==true?ST.SelectProducts:'Enter Stocks')}</Text>
                                        
                                    </LinearGradient>
                                    {isListedSKUEnable==true && 
                                    <View style={customStyle.windhdr_checkAllBtnCon}>
                                    <TouchableOpacity style={customStyle.windhdr_checkAllBtn} onPress={()=>{checkAllSKUs((isAllSKUChecked==1?0:1),window)}}>
                                        <CheckBox
                                            boxType='square'
                                            value={isAllSKUChecked}
                                            onValueChange={(val)=>{let val1=(val==true)?1:0; checkAllSKUs(val1,window) }}
                                            style={[customStyle.WStkHdr_checkbox,(Platform.OS=='ios'?{height:20,width:20,marginLeft:5}:{})]}
                                            tintColors={{ true:PageTheme.$primary_color, false:PageTheme.$text_color_light }}
                                        />
                                        <Text style={customStyle.windhdr_checkAllBtnText}>{ST.SelectAll}</Text>
                                    </TouchableOpacity>
                                    </View>}
                                    <FlatList 
                                        data={WindowStocks}
                                        extraData={rerenderdata4}
                                        listKey={(item, index) => `wstock_${index.toString()}`}
                                        renderItem={({item,index})=>{
                                            let stockProd=item;
                                            let stockProdIndex=index;
                                            let sd=WStocksData.find(i=> i.ProductId==stockProd.PromoStockValue) || {};
                                            let stock=sd.Stock!=null?sd.Stock:'';
                                            let isPromoPresent=sd.isPromoPresent!=null?sd.isPromoPresent:0;
                                           
                                            // highlight prd errors 
                                            let EF_stockProd=errorfield.EF_stockProd!=null?errorfield.EF_stockProd:{};
                                            let showPrdErrHere=EF_stockProd.PromoStockDefinitionId==stockProd.PromoStockDefinitionId;
                                            
                                            let EF_stock=errorfield.EF_stock || '';
                                            let EStyle_StockInput=show_errorhere && showPrdErrHere && EF_stock=='input1_'?customStyle.stk_inptSTyle_error:{};
                
               

                                            return(
                                                <View style={[customStyle.WStkWrap]} key={'WSTock+'+stockProdIndex}>
                                                    {isListedSKUEnable!=true &&  <Text style={[customStyle.WStkHdrText3]}>{stockProd.ProductName}</Text> }
                                                    {isListedSKUEnable==true && <View style={customStyle.WStkHdr_checkboxWrap}>
                                                        <View style={customStyle.WStkHdr_checkboxCon}>
                                                        <CheckBox
                                                        boxType='square'
                                                        value={(isPromoPresent==1 || isPromoPresent=='1')}
                                                        onValueChange={(val)=>{let val1=(val==true)?1:0; setWindowStockVal(val1,window,stockProd,'isPromoPresent') }}
                                                        style={[customStyle.WStkHdr_checkbox,(Platform.OS=='ios'?{height:20,width:20,marginTop:5,marginLeft:5,}:{})]}
                                                        tintColors={{ true:PageTheme.$primary_color, false:PageTheme.$text_color_light }}
                                                        />
                                                        </View>
                                                        <Text style={[customStyle.WStkHdrText2,customStyle.WStkHdr_checkboxpName]}>{stockProd.ProductName}</Text>
                                                    </View>}
                                                    {((isListedSKUEnable==true && StockQtyRequired==1 && isPromoPresent==1 ) || isListedSKUEnable!=true) &&

                                                        <View style={[customStyle.openStk_prd_colflex,customStyle.WStkHdr_PrdcontentWrap]} >
                                                        <View style={[customStyle.openStk_prd_col50,customStyle.openStk_prd_col50_1]}>
                                                            <Text style={customStyle.openStk_prd_flexlabel}>Stock</Text>
                                                        </View>
                                                        
                                                        <View style={[customStyle.openStk_prd_col50,customStyle.openStk_prd_col50_2]}>
                                                            <TextInput 
                                                                ref={(reff)=>{inputRefs.current['input1_'+stockProd.PromoDefinitionId+'_'+stockProd.PromoStockDefinitionId]=reff;}}    
                                                                style={[customStyle.WStkInputStyle,EStyle_StockInput]}
                                                                placeholder=""
                                                                autoComplete='off'
                                                                placeholderTextColor={PageTheme.$placeholder_color} 
                                                                keyboardType={'number-pad'}
                                                                returnKeyType={(Platform.OS==='ios')?'done':'next'} 
                                                                blurOnSubmit={false}
                                                                value={stock+''}
                                                                onSubmitEditing={()=>{focusToNext(WindowStocks,windowIndex,stockProd,index)}}
                                                                onChangeText={(val)=>{setWindowStockVal(val,window,stockProd,'Stock','numeric')}}
                                                            />
                                                        </View>
                                                    
                                                        </View>
                                                    }
                                                </View>
                                            );
                                        }}
                                    /> 
                                    </View>
                                    }
                                    {(!isKPIIREnable &&( window.NoOfSplit>0 &&  WindowSplits.length>0 && (isImage1==1 || isImage2==1))) && 
                                    <View style={[((!HidePresentYesNoEnable || isStockReq==true)?customStyle.openStk_prd_borderT3:{}),customStyle.mb10]}>
                                    <LinearGradient colors={[PageTheme.$secondary_color_light,PageTheme.$fourth_color,PageTheme.$secondary_color_light]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.windhdrTextCon}>
                                        <Text style={customStyle.windhdrText}>{ST.CapturePromotionImages}</Text>
                                    </LinearGradient>
                                    <FlatList 
                                        data={WindowSplits}
                                        extraData={rerenderdata2}
                                        listKey={(item, index) => `spliItem_${index.toString()}`}
                                        renderItem={({item,index})=>{
                                            let splitItem=item;
                                            let splitItemIndex=index;
                                            let Image1Name=splitItem['Image1Name']!=null && splitItem['Image1Name']!=''?splitItem['Image1Name']:'';
                                            let Image2Name=splitItem['Image2Name']!=null && splitItem['Image2Name']!=''?splitItem['Image2Name']:'';
                                            let Image1=splitItem['Image1']!=null && splitItem['Image1']!=''?splitItem['Image1']:'';
                                            let Image2=splitItem['Image2']!=null && splitItem['Image2']!=''?splitItem['Image2']:'';
                                            let isImg1mad=splitItem['img1Required'] || false;
                                            let isImg2mad=splitItem['img2Required'] || false;

                                           
                                            // highlight split image box 
                                            let EF_splitItemIndex=errorfield.EF_splitItemIndex || '';
                                            let showSplitItemErrHere=EF_splitItemIndex==splitItemIndex;
                                            
                                            let EF_splitImage1=errorfield.EF_splitImage1 || '';
                                            let EStyle_splitImage1=show_errorhere && showSplitItemErrHere && EF_splitImage1=='splitImage1'?customStyle.error_CatImage2:{};
                
                                            let EF_splitImage2=errorfield.EF_splitImage2 || '';
                                            let EStyle_splitImage2=show_errorhere && showSplitItemErrHere && EF_splitImage2=='splitImage2'?customStyle.error_CatImage2:{};
                

                                            return(
                                                <View style={[customStyle.openStk_prdCameras,customStyle.WSCameraWrap]} key={'SplitItem+'+splitItemIndex}>
                                                    
                                                    {isImage1==1 && 
                                                    <View style={customStyle.openStkCameraCon2}>
          
                                                    {((Image1=='' || Image1==null) && isImg1mad)  ?
                                                        <TouchableOpacity style={[EStyle_splitImage1]} onPress={()=>{openCamera(window,splitItem,splitItemIndex,'1')}}>
                                                            <CameraImg5 width={50} height={50}  />
                                                        </TouchableOpacity> : (Image1=='' || Image1==null ) ? 
                                                        <TouchableOpacity style={[EStyle_splitImage1]} onPress={()=>{openCamera(window,splitItem,splitItemIndex,'1')}}>
                                                            <CameraImg2 width={50} height={50}  />
                                                        </TouchableOpacity> :(Image1!='' || Image1!=null ) ? 
                                                        <TouchableOpacity onPress={()=>{OpenImgModal(Image1,window,splitItem,splitItemIndex,'1')}}>
                                                            <CameraImg3 width={50} height={50} />
                                                        </TouchableOpacity> : null
                                                    }
                                                    
                                                    <Text style={customStyle.WSCameraLabel}>{camera1Label}</Text> 
                                                    </View>  
                                                    }   

                                                    {isImage2==1 && 
                                                    <View style={customStyle.openStkCameraCon2}>
                                                  
                                                    {((Image2=='' || Image2==null) && isImg2mad)  ?
                                                        <TouchableOpacity style={[EStyle_splitImage2]} onPress={()=>{openCamera(window,splitItem,splitItemIndex,'2')}}>
                                                            <CameraImg5 width={50} height={50} />
                                                        </TouchableOpacity> : (Image2=='' || Image2==null ) ? 
                                                        <TouchableOpacity style={[EStyle_splitImage2]} onPress={()=>{openCamera(window,splitItem,splitItemIndex,'2')}}>
                                                            <CameraImg2 width={50} height={50}  />
                                                        </TouchableOpacity> :(Image2!='' || Image2!=null ) ? 
                                                        <TouchableOpacity onPress={()=>{OpenImgModal(Image2,window,splitItem,splitItemIndex,'2')}}>
                                                            <CameraImg3 width={50} height={50} />
                                                        </TouchableOpacity> : null
                                                    }
                                                    <Text style={customStyle.WSCameraLabel}>{camera2Label}</Text> 
                                                    </View>  
                                                    }         
                                                </View>
                                            );
                                        }}
                                    />
                                    </View>
                                    }
                                    
                                    {(WindowQuestions.length>0) && 
                                    <View style={[((!HidePresentYesNoEnable || isStockReq==true || ( window.NoOfSplit>0 &&  WindowSplits.length>0 && (isImage1==1 || isImage2==1)))?customStyle.openStk_prd_borderT3:{}),customStyle.mb10]}>
                                    <LinearGradient colors={[PageTheme.$secondary_color_light,PageTheme.$fourth_color,PageTheme.$secondary_color_light]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.windhdrTextCon}>
                                        <Text style={customStyle.windhdrText}>{ST.PromotionQuestions}</Text>
                                    </LinearGradient>
                                    {WindowQuestions.map((item,index)=>{
                                        
                                        let qtn=item;  
                                        let qtnIndex=index;
                                        let selansid='',selanswer='',selimg='',showImageTag=false;
                                        let id_key=qtn.PromoQuestionId+'_AnswerId'; 
                                        let ans_key=qtn.PromoQuestionId+'_Answer'; 
                                        let multi_key=qtn.PromoQuestionId+'_MultiOption';
                                        let date_key=qtn.PromoQuestionId+'_Date';
                                        let img_key=qtn.PromoQuestionId+'_ImagePath1';
                                        let imgname_key=qtn.PromoQuestionId+'_ImageName1';
                                        let rating_key=qtn.PromoQuestionId+'_Rating'; 
                                        
                                        let list_mcdata=[];

                                        if(qtn.QuestionType=='Single choice list')
                                        {
                                            selansid=QuestionsData[id_key]!=null ?QuestionsData[id_key] :'';
                                            selanswer=QuestionsData[ans_key]!=null ?QuestionsData[ans_key] :'';
                                        }
                                        else if(qtn.QuestionType=='Multi choice list')
                                        {
                                            if(qtn.Answers!=null){
                                                for(var i=0;i<qtn.Answers.length;i++){
                                                    let obj={'AnswerId':parseInt(qtn.Answers[i].AnswerId),'Answer':qtn.Answers[i].Answer};
                                                    list_mcdata.push(obj);
                                                }
                                            }
                                            selansid=QuestionsData[multi_key]!=null && QuestionsData[multi_key]!=''?QuestionsData[multi_key].split(','):[];
                                            // if(selansid!=null && selansid.length>0){
                                            //     let arr=[];
                                            //     for(var i=0;i<selansid.length;i++){
                                            //         arr.push(parseInt(selansid[i]));
                                            //     }
                                            //     selansid=arr;
                                            // }
                                        }
                                        else if(qtn.QuestionType=='Number' || qtn.QuestionType=='Text' || qtn.QuestionType=='Decimal' || qtn.QuestionType=='Date')
                                        {
                                            selansid=QuestionsData[ans_key];
                                            selanswer=(qtn.QuestionType=='Date'  )?(QuestionsData[date_key] || moment().format('MM/DD/YYYY')):'';
                                            showImageTag=(qtn.PromoqShowCamera==1 || qtn.PromoqShowCamera=='true');
                                        }else if(qtn.QuestionType=='Image' ){
                                            selansid=QuestionsData[id_key]!=null ?QuestionsData[id_key] :'';
                                            selanswer=QuestionsData[ans_key]!=null ?QuestionsData[ans_key] :''; // this is the image file name
                                            {/* filePath=`${ImageFolderPath+currentMenu.ScreenName}/${selanswer}`; */}
                                            showImageTag=true;
                                        }
                                        else if(qtn.QuestionType=='Rating'){
                                            selanswer=QuestionsData[ans_key]?QuestionsData[ans_key]:'';
                                        }
                                        

                                        if((qtn.QuestionType=='Single choice list' || qtn.QuestionType=='Multi choice list' )){
                                            if (qtn.Answers && qtn.Answers.length>0){
                                                for(var i=0;i<qtn.Answers.length;i++){
                                                    let ansss=qtn.Answers[i];
                                                    let isandImgAl=(ansss.PromoaShowCamera=='true' || ansss.PromoaShowCamera==1);
                                                    
                                                    if(qtn.QuestionType=='Single choice list' && (isandImgAl && ansss.AnswerId==selansid)){
                                                        showImageTag=true;
                                                    }
                                                    else if(qtn.QuestionType=='Multi choice list' && (isandImgAl && selansid.indexOf(ansss.AnswerId)>=0)){
                                                        showImageTag=true;
                                                    }
                                                    
                                                }
                                            }
                                        }
                                        
                                        if(showImageTag){
                                            selimg=QuestionsData[img_key]!=null && QuestionsData[img_key]!=''?'file://'+QuestionsData[img_key]:'';                    
                                        }
                                        let isDisabled=qtn.isDisabled!=null?qtn.isDisabled:false

                                        let EF_qtn=errorfield.EF_qtn!=null?errorfield.EF_qtn:{};
                                        let showQtnErrHere=EF_qtn.PromoQuestionId==qtn.PromoQuestionId;
                                        
                                        let EF_Qtn_MultiChoice=errorfield.EF_Qtn_MultiChoice || '';
                                        let EStyle_Qtn_MultiChoice=show_errorhere && showQtnErrHere && EF_Qtn_MultiChoice=='Qtn_MultiChoice'?customStyle.stk_MultiSSTyle_error:customStyle.wind_MultiSearchInputStyle;
                                        
                                        
                                        // let EF_Qtn_Date=errorfield.EF_Qtn_Date || '';
                                        // let EStyle_Qtn_Date=show_errorhere && showQtnErrHere && EF_Qtn_Date=='Qtn_Date'?customStyle.stk_inptSTyle_error:{};
                                        
                                        let EF_Qtn_Input=errorfield.EF_Qtn_Input || '';
                                        let EStyle_Qtn_Input=show_errorhere && showQtnErrHere && EF_Qtn_Input=='Qtn_Input'?customStyle.stk_inptSTyle_error:{};
                                        let EStyle_Qtn_Select=show_errorhere && showQtnErrHere && EF_Qtn_Input=='Qtn_Select'?customStyle.stk_inptSTyle_error:{};
                                        let EStyle_Qtn_Date=show_errorhere && showQtnErrHere && EF_Qtn_Input=='Qtn_Date'?customStyle.stk_inptSTyle_error:{};
                                        
                                        let EF_Qtn_Image=errorfield.EF_Qtn_Image || '';
                                        let EStyle_Qtn_Image=show_errorhere && showQtnErrHere && EF_Qtn_Image=='Qtn_Image'?customStyle.stk_inptSTyle_error:{};
                                        
                                        
                                        if(isDisabled==true){
                                            return (
                                                <View></View> 
                                            )
                                        }
                                        else{
                                            return(
                                                <View style={[customStyle.sform_group2,]} key={'Qtn_'+qtnIndex} >
                                                    <Text style={[customStyle.sform_label3]}>{qtn.PromoQuestionName}</Text>                     
                                                    {qtn.QuestionType=='Single choice list' && qtn.Answers && 
                                                        render_Picker('Answer','AnswerId',onselectionChange2,{value:selanswer,qtn:qtn,window:window},EStyle_Qtn_Select)
                                                    }
                                                    {qtn.QuestionType=='Multi choice list' && qtn.Answers &&
                                                        <MultiSelect
                                                            items={list_mcdata}
                                                            uniqueKey="AnswerId"
                                                            onSelectedItemsChange={(selectedItems)=>{ setMultiSelectValue(selectedItems,qtn,window) }} //setMultiSelectValue(selectedItems,qtn)
                                                            selectedItems={selansid}
                                                            selectText="Pick Items"
                                                            searchInputPlaceholderText={ST.SearchItems+"..."}
                                                            // onChangeInput={ (text)=> console.log(text)}
                                                            tagRemoveIconColor={PageTheme.$primary_color}
                                                            tagBorderColor={PageTheme.$primary_color}
                                                            tagTextColor={PageTheme.$primary_color}
                                                            selectedItemTextColor={PageTheme.$primary_color}
                                                            selectedItemIconColor={PageTheme.$primary_color}
                                                            itemTextColor={PageTheme.$text_color}
                                                            displayKey="Answer"
                                                            searchInputStyle={EStyle_Qtn_MultiChoice}
                                                            submitButtonColor={PageTheme.$primary_color}
                                                            submitButtonText={ST.Submit}
                                                        />
                                                    }
                                                    { (qtn.QuestionType=='Number' || qtn.QuestionType=='Decimal'  || qtn.QuestionType=='Text') &&  
                                                        <TextInput 
                                                            style={[customStyle.WQ_InputStyle,EStyle_Qtn_Input]}
                                                            placeholder=""
                                                            autoComplete='off'
                                                            placeholderTextColor={PageTheme.$placeholder_color} 
                                                            // keyboardType={'ascii-capable'}
                                                            keyboardType={(qtn.QuestionType=='Decimal'?'decimal-pad':(qtn.QuestionType=='Text'?'default':'number-pad'))}
                                                            value={selansid}
                                                            onChangeText={(val)=>{setTextValue(val,qtn,window,(qtn.QuestionType=='Decimal'?'decimal':(qtn.QuestionType=='Text'?'text':'numeric')))}}
                                                        />
                                                    }
                                                    {
                                                        (qtn.QuestionType=='Date') && 
                                                        <View style={[customStyle.surveyQtn_datePicker_con,EStyle_Qtn_Date]}>
                                                            <Text style={customStyle.WQ_datePicker_text}>{selansid!=''?selansid:'MM/YYYY'}</Text>
                                                            <TouchableOpacity style={[customStyle.surveyQtn_datePicker]} onPress={()=>{setDateValue(selanswer);showQtnDatePicker(qtn,window,true)}}>
                                                                <Fontisto size={20} color={PageTheme.$accent_color} name="date"/>
                                                            </TouchableOpacity> 
                                                        </View>     
                                                    }
                                                    {   ((qtn.showDatePicker==true || qtn.showDatePicker=='true') && (qtn.QuestionType=='Date') ) && 
                                                        renderDatePicker(qtn,window)
                                                    }  
                                                    {
                                                        (qtn.QuestionType=='Rating') && 
                                                        <View style={customStyle.surveyQtn_datePicker_con}>
                                                            <Text style={customStyle.surveyQtn_datePicker_text}>{selanswer}</Text>
                                                            <TouchableOpacity style={[customStyle.surveyQtnRatingIcon]} onPress={()=>{setRatingQtn(qtn);setRatingWindow(window);setShowRating(true);}}>
                                                                <MaterialCommunityIcons size={25} color={PageTheme.$accent_color} name="drag"/>
                                                            </TouchableOpacity> 
                                                        </View>    
                                                    }

                                                    {
                                                        // (qtn.QuestionType=='Audio') && 
                                                        // <View style={customStyle.surveyQtn_datePicker_con}>
                                                        //     <Text style={customStyle.surveyQtn_datePicker_text}>{selanswer}</Text>
                                                        //     <TouchableOpacity style={[customStyle.surveyQtnRatingIcon]} onPress={()=>{show_recorder(qtn);}}>
                                                        //         <FontAwesome size={25} color={PageTheme.$accent_color} name="microphone"/>
                                                        //     </TouchableOpacity> 
                                                        // </View>    
                                                    }
                                                    
                                                    {
                                                        showImageTag &&
                                                        <View style={[customStyle.store_audit_img_con,EStyle_Qtn_Image]}>                    
                                                            <Image source={(selimg!='' && selimg!=null )?{uri:selimg}:require('../assets/image/greybg.jpg')} style={[customStyle.store_audit_image,((selimg!='' && selimg!=null )?{resizeMode:'contain'}:{width:100,height:150,resizeMode:'stretch',alignSelf:'center'})]}/>
                                                            <TouchableOpacity  style={customStyle.store_audit_pickimg_btn} onPress={()=>{openCamera(window,{},0,'1','2',qtn)}}>
                                                                <Entypo name="camera" color={PageTheme.$text_color} size={28}/>
                                                            </TouchableOpacity>
                                                        </View>
                                                    }

                                                
                                                </View> 
                                            )
                                        }
                                    })}
                                    </View>
                                    }
                                    { RemarkEnable==true &&
                                    <View style={[customStyle.openStk_prd_borderT,customStyle.pt10,customStyle.mb10]}>
                                        <Text style={[customStyle.openStk_prd_label,customStyle.st_TextLbl]}>{ST.Remark}</Text>
                                        <TextInput 
                                            style={[customStyle.WQ_InputStyle]}
                                            value={remark}
                                            autoComplete='off'
                                            onChangeText={(val)=>{onCatTextChange(window,'remark',val,'text')}}
                                        />
                                    </View>
                                    }
                                    
                                </View>
                                }
                                
                                                    
                                                    
                            </View>
                        </View>
                    </View>
                );
            }}
            />
        )
    }

    function _renderHeader(currentIndex){        
        return(
            <View style={customStyle.album_ZOOM_topBar}>
                <Text style={customStyle.album_ZOOM_indicator}>{`${(currentIndex+1)}/${zoomImageUrl.length}`}</Text>
                <TouchableOpacity style={customStyle.album_ZOOM_backBtn} onPress={()=>{setShow_zoomImage(false) }}>
                    <Entypo name='chevron-left' color={'#fff'} size={24}/>
                </TouchableOpacity>            
            </View> 
        )
    }
  
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader fullHeight={true} title={loaderTitle}/>}
        <CustomHeader {...props} showaddstore={true} title={currentMenu.MenuName} projectCode={`${storeData.StoreId}: ${storeData.StoreName}`}/>        
        {_OpenCaptureImage_Modal()}
        {ConfirmSaveAlert(props,showAlert,onSaveCancel,saveData)}
        {ConfirmSaveAlert(props,DataCleanModal,onCancelClean,onclear,'Your data will be clean',)}
        {_render_RetakePopup()} 
        {_render_UploadAlert()} 
        <CustomCamera cameraType={'back'} BottomText={'Store Name:'+storeData.StoreName+' | Store Id:'+storeData.StoreId+' | User Id:'+storeData.EmpId+' | Image Type: '+currentMenu.MenuName} enableCameraFlip={showSwitchCamera} onImageCaptured={(imgData)=>{setShowCamera(false);getImage(imgData)}} showCamera={showCamera} onHideCamera={()=>{setShowCamera(false);}}/>   
        
        <LinearGradient colors={[PageTheme.$gradient1,PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={[customStyle.roundScrollWrapper,customStyle.zIndex0]}>
          <View style={[customStyle.pageContentWrapper]}>
          <View style={customStyle.storel_searchbar}>
              <TextInput 
                style={[customStyle.storel_searchInput]}
                placeholder={ST.Searchby+' '+currentMenu.MenuName}
                autoComplete='off'
                placeholderTextColor={PageTheme.$placeholder_color} 
                value={searchedItem}
                onChangeText={(val)=>{setSearchedItem(val); FilterStores(val)}}
              />
              <TouchableOpacity style={customStyle.storel_searchBtn} onPress={()=>{FilterStores(searchedItem)}}>
                <AntDesign style={customStyle.storel_searchBtnIcon} name='search1' size={20} color={PageTheme.$accent_color}/>
              </TouchableOpacity>
          </View>
          { Object.keys(storeData).length>0 && 
            <View style={customStyle.Windows_Wrap}>
                {_renderWindow()}
            </View>    
          }
            <View style={[customStyle.opening_Stock_btnWrap]}>
                <GradientButton {...props} title={ST.Save} onPress={()=>{onSubmitData()}}/> 
            </View>  
         </View>    
         
       </LinearGradient> 
        {   showRating==true && 
            renderRatingView()
        }
       {show_zoomImage && 
        <View style={customStyle.album_ZOOM_wrap}>
            <ImageViewer ref={zoomView} style={customStyle.album_ZOOM} imageUrls={zoomImageUrl} index={refImageIndex}
            renderHeader={_renderHeader} renderIndicator={()=>null}
            />
        </View>        
        }  
      </Container>   
    ); 
}
  

export default connect(mapStateToProps, mapDispatchToProps)(PromotionOneAppIR);