import React, { useState, useEffect, useRef } from 'react';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
import { customStyles, GetPageTheme, WP } from "../styles/Global";
import { StatusBar, Image, TextInput, View, Text, ScrollView, TouchableOpacity, Platform, PermissionsAndroid, Modal, Animated, FlatList, Alert, DeviceEventEmitter, StyleSheet, Button, Linking } 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 { getDownloadJson, DownloadData, getDownloadJson1, UpdateStoreStatus, getKPIS, getProjectInfo, CreateDirKPIimg, getAllFolderImages, UploadData2, getIRPendingSessionCount, getDataPendingStores, uploadContractData, getAllFileForAFolder, uploadContractFormFiles, AlertForServerDT, get_rowColSettings, UploadAddStoreInfoData, getNotificationList, getKPIFields, openLink, openWebBrowser, createContact } from '../controller/functions';
import { get_item, set_item, clear_item } from '../components/localStorage';
import { db, ContractFormImagePath, loaderTimeOut, loaderTimeOut_longer, AddStoreImagePath, Production } from '../constants/constants';
import SplashScreen from 'react-native-splash-screen';
import { WebView } from 'react-native-webview';
import CustomLoader from '../components/CustomLoader';
import DownloadDataModal from '../components/downloadDataModal';
import DrawerHeader from '../components/drawerHeader';
import LinearGradient from 'react-native-linear-gradient';
import { devDownloadKeys, getDownloadDataTask, getPostData } from '../components/downloadTasks';
import { getMethodName, METHODS } from '../constants/methodNames';
import { SyncIRsessions, getPendingIRImages, uploadAllData, uploadAllImages, uploadAllVisitors, uploadAll_DBData, uploadDBStatus, uploadStoreStatus } from '../constants/uploadData';
import { AppTables } from '../constants/tableConstants';
import { Q_DBMenuList, Q_MenuList } from '../constants/ConstantQueries';
import { Q_getpaidvisibility } from '../constants/ConstantQueries';
import Geolocation from 'react-native-geolocation-service';
//import Carousel, { Pagination } from 'react-native-snap-carousel';
import Carousel from 'react-native-reanimated-carousel';
import Store_plannedIcon from '../assets/performics/Planned.svg';
import Store_coveredIcon from '../assets/performics/Covered.svg';
import { getDashBoardConstData } from '../constants/DashboardData';
import IRLogin from '../components/IRLogin';
import { Feather } from '../components/icons';
import { AppName, PerformicsIRAppName } from '../../../AppSpecificContant';
import CustomModal from '../components/CustomModal';
import messaging from '@react-native-firebase/messaging';
// webview survey
import { useIsFocused } from "@react-navigation/native";
import PushNotification from "react-native-push-notification";
import TrainingPromptModal from '../components/TrainingPromptModal'
import BadgeModal from '../components/BadgeModal';

function NoticeBoard(props) {
  const route = useRoute();
  let d2 = moment().format('MM/DD/YYYY');
  let d3 = moment().format('DD/MM/YYYY');
  const ST = props.StaticText || {};
  ///Badge
  const [showBadge, setShowBadge] = useState(false);
  const [finalImage, setFinalImage] = useState(null);
  const [webHeight, setWebHeight] = useState(400);

  useEffect(() => {
    console.log("Updated groomingObj -->", props.GroomingObj, props.pPAYObj);
  }, [props.GroomingObj]);

  useEffect(() => {
    const unsubscribeBackground = messaging().onNotificationOpenedApp(remoteMessage => {
      // Navigate to NotificationList when app is opened from background
      props.navigation.navigate('NotificationList');
    });

    const handleInitialNotification = async () => {
      const initialNotification = await messaging().getInitialNotification();
      if (initialNotification) {
        // Navigate to NotificationList when app is opened from quit state
        props.navigation.navigate('NotificationList');
      }
    };

    handleInitialNotification();
    if (props?.badgeCount && props?.badgeCount > 0) {
      PushNotification.setApplicationIconBadgeNumber(props?.badgeCount);
    }
    return () => {
      unsubscribeBackground();
    };
  }, []);


  const handleSaveBadge = async (uri) => {
    setFinalImage(uri);
    setProcessing(true);
    let loginInfo = await get_item('loginInfo');
    const loginDetails = JSON.parse(loginInfo);
    const today = moment(new Date()).format('MM/DD/YYYY');
    let user_answers = [];
    let ans_obj = { "Visit_Date": today, "UserId": loginDetails.UserId, "Project_code": projectCode };
    user_answers.push(ans_obj);
    let post_data = {
      "MID": "0",
      "Keys": "RetailDay_Data",
      "JsonData": JSON.stringify(user_answers),
      "UserId": loginDetails.UserId
    }
    const url = props.baseurl + getMethodName(METHODS.UPLOADJSON_METHOD);
    console.log('RetailDay upload ', url, post_data);
    await UploadData2(url, post_data)
      .then(async (res) => {
        setProcessing(false);
        console.log(res);
        if (res.success == false) {
          return
        }
      })
      .catch(err => {
        console.log('onPage Team error', err);
      });
  };

  // get all theme styles acc to current theme set 
  const PageTheme = GetPageTheme(props.DarkMode, route.name);
  const customStyle = customStyles(props.DarkMode, route.name);

  const [state, setState] = useState({ webviewurl: '' });
  const [processing, setProcessing] = useState(true);
  const [loaderTitle, setLoaderTitle] = useState();

  // download data state
  const [isDataDownloaded, setisDataDownloaded] = useState(false);
  const [TaskResponse, setTaskResponse] = useState([]);
  const [downloadingText, setDownloadingText] = useState('');
  const [dowloadedCount, setDowloadedCount] = useState(-1);
  const [onDownloadCountChange, setOnDownloadCountChange] = useState(1);
  const [totalCount, setTotalCount] = useState(0);
  const [AllTableQueries, setAllTableQueries] = useState([]);
  const [DownloadTasks, setDownloadTasks] = useState([]);
  const [IsPJPMandatory, setIsPJPMandatory] = useState(true);
  const projectCode = props.projectCode;

  const [uploadedCount, setUploadedCount] = useState(0);
  const [TotalUpCount, setTotalUpCount] = useState(0);
  const [startUploading, setStartUploading] = useState(false);
  const [showOkButtonOnUpload, setShowOkButtonOnUpload] = useState(false);

  const [UploadingSubText, setUploadingSubText] = useState("");
  const [UploadingText, setUploadingText] = useState("Uploading Data...");
  const [showProgresssBar, setshowProgresssBar] = useState(false);
  const [IRSessionPendingCount, setIRSessionPendingCount] = useState(0);
  const [StartDafterPrevUpload, setStartDafterPrevUpload] = useState(false);
  const [subTextStyle, setSubTextStyle] = useState('');
  const [DErrorMsg, setDErrorMsg] = useState({});
  const [showDErrAlert, setshowDErrAlert] = useState(false);
  const sessionsToUpload = useRef([]);
  const sessionsUploadedCount = useRef(0);
  const sessionsReceived = useRef(0);

  //dashboard states
  const imageSlider = useRef(null);
  const [bannerdetail, setBannerDetail] = useState([]);
  const [activeSlide, setActiveSlide] = useState(0);
  const [DashboardCovdata, setDashboardCovdata] = useState({});

  const [QuickLinks, setQuickLinks] = useState([]);
  const [StorePerformanceText, setStorePerformanceText] = useState([]);
  const processingTimeOut = useRef(null);
  const [AppDashReportsSec, setAppDashReportsSec] = useState([]);
  ///gyancast
  const [TrainingOrg, setTrainingOrg] = useState({});
  const [showTrainingModal, setShowTrainingModal] = useState(false);
  const [TrainingOrg2, setTrainingOrg2] = useState([]);
  const [bannerRefresh, setBannerRefresh] = useState(false);

  const handleDoIt = async (item) => {
    // await clear_item('GyanCast');
    setGyanCast(item)
    props.navigation.navigate('Gyancasts', { Popup: true, PopupId: item?.PopupId });
  };

  const handleNotNow = async (item) => {
    setGyanCast(item)
  };

  const setGyanCast = async (item) => {
    console.log("GyanCast-------1213", item?.PopupId)
    if (item?.PopupId != 1) {
      let d2 = moment().format('MM/DD/YYYY');
      let newData = {
        Show: true,
        visiteDate: d2
      }
      let WindowsStr = JSON.stringify(newData)
      console.log("GyanCast-----", WindowsStr)
      await set_item('GyanCast', WindowsStr);
    }
    setShowTrainingModal(false);
  }

  useEffect(() => {
    setLoaderTitle(ST.Loading + '...')
    dashboardview();
    const removeIRListener = DeviceEventEmitter.addListener('onGlobalIRImageUpload_NB', (data) => { onIRImageUpload(data) });
    const willFocusSubscription = props.navigation.addListener('focus', () => {
      dashboardview('reload');
      getIRSessionStatus();
    });

    return function cleanup() {
      if (AppName == PerformicsIRAppName && props.IR_CameraEnableOnApp == true) {
        IRLogin?.deRegisterReceiver();
      }
      removeIRListener.remove();
      return willFocusSubscription;
    };
  }, []);



  useEffect(() => {
    // console.log('on props.startDownload change:',props.startDownload);
    if (props.startDownload == true) {
      // start previous day uploading if any exists
      // if not exists then it will automatically start download by calling beforeExecuteTasks
      uploadPrevDayData();
    }
  }, [props.startDownload]);

  ///gyancast
  useEffect(() => {
    console.log('startDownload changed:', props.startDownload);
    getData();
    getData2();
  }, [props.startDownload]);

  async function getData2() {
    try {
      let List = [];
      await db.transaction(async function (txn) {
        let q = `Select TrainingId,Topic,Description,MediaType,TrainingContentId,Thumnail,TrainingUrl,Status,StartTime,PublishDate,ExpiryDate,DefaultLang,TrainingNo from Gyancast_TrainingContent where (DefaultLang="true" or DefaultLang=1 or DefaultLang='1') and Status="Pending" and ExpiryDate>='${d3}' order by ExpiryDate`;
        console.log("dummy-q", q)
        await txn.executeSql(
          q,
          [],
          async function (txn2, txnres2) {
            console.log("txnres2.rows.length43434:", txnres2.rows.length);
            if (txnres2.rows.length > 0) {
              for (let i = 0; i < txnres2.rows.length; i++) {
                let data = txnres2.rows.item(i);
                List.push(data);
              }

              setTrainingOrg2(List);

            }
          },
          function (txnE, txnerr) {
            console.log(txnerr);
          }
        );
      });
    } catch (err) {
      console.log(err);
    }
  }

  async function getData() {
    try {
      // await clear_item('GyanCast');
      let GyanCast = await get_item('GyanCast');
      let GyanCastVal = GyanCast && JSON.parse(GyanCast)
      console.log("GyanCast-------", GyanCastVal, d2, (GyanCastVal == undefined), ((d2 != GyanCastVal?.visiteDate) && GyanCast?.Show != true), (GyanCastVal == undefined) || ((d2 != GyanCastVal?.visiteDate) && GyanCast?.Show != true))
      if ((GyanCastVal == undefined) || ((d2 != GyanCastVal?.visiteDate) && (GyanCast?.Show != true))) {
        await db.transaction(async function (txn) {
          let q = `Select * from Gyancast_PopupMessage`;
          await txn.executeSql(
            q,
            [],
            async function (txn2, txnres2) {
              console.log("txnres2.rows.length:-setTrainingOrg", txnres2.rows.length);
              if (txnres2.rows.length > 0) {
                for (let i = 0; i < txnres2.rows.length; i++) {
                  let data = txnres2.rows.item(i);
                  setTrainingOrg(data);
                  console.log("setTrainingOrg---", data)
                  setShowTrainingModal(true)
                }
              }
            },
            function (txnE, txnerr) {
              console.log(txnerr);
            }
          );
        });
      }
    } catch (err) {
      console.log(err);
    }
  }

  useEffect(() => {
    console.log('on StartDafterPrevUpload change:', StartDafterPrevUpload, props.startDownload);
    if (props.startDownload == true) {
      beforeExecuteTasks();
    }
  }, [StartDafterPrevUpload]);

  useEffect(() => {
    console.log('on totalCount change:', totalCount, props.startDownload);
    if (props.startDownload == true) {
      startDownload();
    }
  }, [totalCount]);

  useEffect(() => {
    if (props.startUpload == true) {
      startUpload();
    }
  }, [props.startUpload]);



  useEffect(() => {
    if (props.startDownload && TaskResponse != null) {
      console.log('increment dowloadedCount changed');
      let count = dowloadedCount + 1;
      setDowloadedCount(count);
      setOnDownloadCountChange(!onDownloadCountChange);
    }
  }, [TaskResponse]);


  useEffect(() => {
    if (dowloadedCount <= totalCount) {
      executeTasks();
    } else {
      props.set_startDownload({ startDownload: false });
      notify(ST.DataDownloaded, 'SHORT');
      CreateDirKPIimg();
    }
  }, [onDownloadCountChange]);

  function setProcessTimeOut(time = loaderTimeOut) {
    processingTimeOut.current = setTimeout(() => {
      setProcessing(false);
      props.set_startDownload({ startDownload: false });
      setStartUploading(false);
    }, time);
  }

  function clearProcessTimeOut() {
    processingTimeOut.current ? clearTimeout(processingTimeOut.current) : '';
  }

  async function checkData() {
    let projectInfo = await get_item('projectInfo');
    let projectCode = await get_item('projectCode');
    let projectDetails = JSON.parse(projectInfo);
    let isPJPMand = projectDetails.PJPMandatory != null ? projectDetails.PJPMandatory : true;
    setIsPJPMandatory(isPJPMand);

    if (props.baseurl == '' || props.baseurl == null || props.baseurl == undefined) {
      //set project info in global redux state
      let imgurl = projectDetails.imageUploadURL != null ? projectDetails.imageUploadURL + '/' : '';
      // const pdata={pid:projectCode,pname:projectDetails.projectName,pcode:projectCode,alldata:projectDetails,baseurl:projectDetails.baseURL,imageUploadUrl:imgurl,GeoFenceEnable:(projectDetails.GeoFenceEnable_checkin!=null && projectDetails.GeoFenceEnable_checkin==1),GeoFenceRadius:(projectDetails.GeoFenceRadius_checkin || 0),GFEnable_checkout:(res.GeoFenceEnable_checkout!=null && res.GeoFenceEnable_checkout==1),GFRadius_checkout:(res.GeoFenceRadius_checkout || 0),CheckOut_PhotoReq:res.PhotoRequired_Checkout };
      const pdata = getProjectInfo(projectDetails, projectCode);
      props.set_project(pdata);
    }
  }

  async function checkIfData_Downloaded() {
    // console.log('checkIfData_Downloaded');
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    const isDataStorageCleared = await get_item('DataStorageCleared');
    let dateWiseDataDownload = await get_item('dateWiseDataDownload');
    let dateWiseDataDownload1 = dateWiseDataDownload != null ? JSON.parse(dateWiseDataDownload) : {};
    let todayDate = moment(new Date()).format('DD/MM/YYYY');
    if (isDataStorageCleared != '1') {

      if (dateWiseDataDownload1[todayDate] != null) {
        let d = dateWiseDataDownload1[todayDate];
        console.log('isdtatdownloaded:', d);
        props.setTodayDataExists(d);
        props.setGlobalData({ isDataDownloaded: d })
        return d;
      } else {
        let lods = {};
        lods[todayDate] = false;
        console.log('lods:', lods);
        await set_item('dateWiseDataDownload', JSON.stringify(lods));
        props.setTodayDataExists(false);
        return false;
      }
    }
    else {
      return false;
    }

  }

  //Dashboard get data functions start 
  function NB_start_Download() {
    clearProcessTimeOut();
    props.set_startDownload({ startDownload: true });
  }

  function NB_AskForDownload() {
    Alert.alert(
      "Performics",
      ST.Doyouwanttodownloaddata,
      [
        {
          text: ST.Cancel,
          onPress: () => { },
          style: "cancel"
        },
        { text: ST.OK, onPress: () => { NB_start_Download(); } }
      ],
    );
  }

  function NB_RetailDay() {
    setShowBadge(true)
  }

  function NB_start_Upload() {
    props.set_startUpload({ startUpload: true });
  }

  function NB_AskForUpload() {
    Alert.alert(
      "Performics",
      ST.Doyouwanttouploaddata,
      [
        {
          text: ST.Cancel,
          onPress: () => { },
          style: "cancel"
        },
        { text: ST.OK, onPress: () => { NB_start_Upload(); } }
      ],
    );
  }

  async function NB_pPAYLink(Ppay_ExternalLink) {
    if (Ppay_ExternalLink !== null && Ppay_ExternalLink !== undefined && Ppay_ExternalLink !== "") {
      let modifyPpay_link = Ppay_ExternalLink + "?ProjectCode=" + props.projectCode + "&UserId=" + props.UserId
      console.log("ppay_link", modifyPpay_link)
      const supported = await Linking.canOpenURL(modifyPpay_link);
      if (supported) {
        await Linking.openURL(modifyPpay_link);
      } else {
        console.log("Don't know how to open URI: " + modifyPpay_link);
      }
    }
  }

  async function getFTDData() {
    console.log("getFTDData called");
    let alldata = DashboardCovdata;
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');

    await db.transaction(async function (txn) {

      //get FTD planned Count
      let q = `Select * from Mapping_JourneyPlan where VisitDate='${d2}'`;
      await txn.executeSql(q, [], async function (txn2, txnres2) {
        console.log('FTD Planned count:', txnres2.rows.length);
        alldata['FTDPlanned'] = txnres2.rows.length;
        setDashboardCovdata(alldata)
      }, function (txn2, txnerr) { console.log(txnerr); });

      //get FTD Covered Count
      let q2 = `Select Distinct STORE_ID from DR_COVERAGE  where VISIT_DATE='${d2}'`;
      await txn.executeSql(q2, [], async function (txn2, txnres2) {
        console.log('FTDCovered count:', txnres2.rows.length);
        alldata['FTDCovered'] = txnres2.rows.length;
        setDashboardCovdata(alldata)
      }, function (txn2, txnerr) { console.log(txnerr); });

      //get FTD Merchandised Count
      let q3 = `Select Distinct STORE_ID from DR_COVERAGE where VISIT_DATE='${d2}' and REASON_ID=0 `;
      await txn.executeSql(q3, [], async function (txn2, txnres2) {
        console.log('FTDMerchandised count:', txnres2.rows.length);
        alldata['FTDMerchandised'] = txnres2.rows.length;
        setDashboardCovdata(alldata)
      }, function (txn2, txnerr) { console.log(txnerr); });
    });
  }

  async function loadConstDashBData() {
    let allDashBData = getDashBoardConstData(props, customStyle, PageTheme, NB_AskForDownload, NB_AskForUpload, (link) => NB_pPAYLink(link));
    const cleanedQuickLinks = allDashBData?.QuickLinks?.filter(
      item => !(Array.isArray(item) && item.length === 0)
    );
    const updatedDashBData = {
      ...allDashBData,
      QuickLinks: cleanedQuickLinks,
    };
    console.log("allDashBData", cleanedQuickLinks)
    setQuickLinks(updatedDashBData.QuickLinks);
    setStorePerformanceText(updatedDashBData.StorePerformanceText);
    // download below data on flag basis only
    if (props.Show_OldMTDReports && !props.WebViewDashboard && props.AppDashboardWebViewObj == "") {
      await getFTDData();
    }
  }

  ///download Banner with some reports Info
  async function getMTDData() {
    let loginInfo = await get_item('loginInfo');
    const loginDetails = JSON.parse(loginInfo);
    const url = props.baseurl + getMethodName(METHODS.DOWNLOADJSON_METHOD);
    let allData = DashboardCovdata;
    //get Banner Detail 
    const data = { Downloadtype: "Mer_NoticeBoard", username: loginDetails.UserId, empid: '', };
    console.log('dashboardurl', url, data);
    await getDownloadJson(url, data)
      .then(async (res) => {
        console.log('Mer_NoticeBoard_data', res);
        setBannerRefresh(true)
        if (res.Mer_NoticeBoard != null) {
          let NB_data = res.Mer_NoticeBoard ? res.Mer_NoticeBoard : [];
          console.log("banner_info", NB_data)
          setBannerDetail(NB_data);
        }
      }).catch(err => {
        console.log('onPage Team error', err);
      });

    // download below data on flag basis only
    if (props.Show_OldMTDReports && !props.WebViewDashboard && props.AppDashboardWebViewObj === "") {
      //get Dashboard_Coverage : MTD Planned, covered, and merchandised count
      const data1 = { Downloadtype: "Dashboard_Coverage", username: loginDetails.UserId, empid: '', };
      console.log('dashboardurl', url, data1);
      await getDownloadJson(url, data1)
        .then(async (res) => {
          console.log('OQAD', res);
          if (res.Dashboard_Coverage != null) {
            let QAD_arr = res.Dashboard_Coverage || [];
            let data = QAD_arr[0];
            allData['MTDPlanned'] = data.MTDPlanned != null ? data.MTDPlanned : 0;
            allData['MTDCovered'] = data.MTDCovered != null ? data.MTDCovered : 0;
            allData['MTDMerchandised'] = data.MTDMerchandised != null ? data.MTDMerchandised : 0;
            setDashboardCovdata(allData);
          }
        })
        .catch(err => {
          console.log('onPage Team error', err);
        });
      //get OQAD count
      const data2 = { Downloadtype: "Dashboard_OQAD", username: loginDetails.UserId, empid: '', };
      await getDownloadJson(url, data2)
        .then(async (res) => {
          if (res.Dashboard_OQAD != null) {
            let QAD_arr = res.Dashboard_OQAD || [];
            let data = QAD_arr[0];
            allData['MTD_OQAD'] = data.MTDOQAD_Per != null ? data.MTDOQAD_Per : 0;
            setDashboardCovdata(allData);
          }
        })
        .catch(err => {
          console.log('onPage Team error', err);
        });

      //get Attendace count
      const data3 = { Downloadtype: "Dashboard_Attendance", username: loginDetails.UserId, empid: '', };
      await getDownloadJson(url, data3)
        .then(async (res) => {
          if (res.Dashboard_Attendance != null) {
            let QAD_arr = res.Dashboard_Attendance || [];
            let data = QAD_arr[0];
            allData['MTDManday'] = data.MTDManday != null ? data.MTDManday : 0;
            setDashboardCovdata(allData);
          }
        }).catch(err => {
          console.log('onPage Team error', err);
        });
    }

    console.log('all dashboard Data:', allData);
  }

  async function getAppDashBReports() {
    console.log("getAppDashBReports called");
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    let arr = [];
    await db.transaction(async function (txn) {
      //get MenuAppDashboard Reports sections to show
      // only those report will be shown which parent id is either null or 0
      let q = `Select * from Master_MenuAppDashboard where ParentId is null or ParentId='0' order by DisplayOrder`;
      await txn.executeSql(q, [], async function (txn2, txnres2) {
        console.log('Master_MenuAppDashboard count:', txnres2.rows.length);
        if (txnres2.rows.length > 0) {
          for (let i = 0; i < txnres2.rows.length; i++) {
            let data = txnres2.rows.item(i);
            arr.push(data);
            if (i == txnres2.rows.length - 1) {
              setAppDashReportsSec(arr)
            }
          }
        } else {
          setAppDashReportsSec([])
        }
      }, function (txn2, txnerr) { console.log(txnerr); setAppDashReportsSec([]) });
    });
  }

  async function dashboardview(type = '') {
    setLoaderTitle("loading...");
    clearProcessTimeOut();
    setProcessing(true);
    setProcessTimeOut();
    await checkData();
    await getDTasks();
    await loadConstDashBData();
    await getMTDData();
    // do not execute below tasks if dashboard is reloaded from back press
    if (type == 'reload') {
      clearProcessTimeOut();
      setProcessing(false);
      return;
    }
    let token = await get_item('loginToken');
    let loginInfo = await get_item('loginInfo');
    const loginDetails = JSON.parse(loginInfo);
    const todate = new Date();
    const today = moment(todate).format("HH:mm:ss");
    const data = { Downloadtype: "Notice_Board", username: loginDetails.UserId, empid: '', };
    const url = props.baseurl + getMethodName(METHODS.DOWNLOADJSON_METHOD);
    clearProcessTimeOut();
    setProcessing(true);
    setProcessTimeOut();
    await getDownloadJson(url, data)
      .then(async (res) => {
        clearProcessTimeOut();
        if (res.Notice_Board) {
          let obj = res.Notice_Board.length > 0 ? res.Notice_Board[0] : {};
          setState({ ...state, webviewurl: obj.NOTICE_BOARD });
          setProcessing(false);
          let isAlreadyDownl = await checkIfData_Downloaded();
          let params = props.route.params ? props.route.params : {};
          // let isTodayLogin=params.TodayLogin!=null?params.TodayLogin:true;
          let isTodayLogin = props.isTodayLoginExists != null ? props.isTodayLoginExists : true;

          // check for autodownload 
          // console.log('check for auto download',isTodayLogin,isAlreadyDownl,props.startDownload);
          if (Platform.OS == 'android' && isAlreadyDownl == false && props.startDownload == false) {//isTodayLogin==false
            await clear_item('storeData');
            console.log('start auto download');
            // start auto download
            clearProcessTimeOut();
            props.set_startDownload({ startDownload: true });
          }
          else if (Platform.OS == 'ios' && isAlreadyDownl == false && props.startDownload == false && isTodayLogin == false) {//isTodayLogin==false
            await clear_item('storeData');
            console.log('start auto download');
            // start auto download
            clearProcessTimeOut();
            props.set_startDownload({ startDownload: true });
          }
          else {
            // get dashboards reports 
            getAppDashBReports();
          }
        }
        else {
          setProcessing(false);
          notify("Cannot load dashboard data!")
        }
      })
      .catch((err) => {
        clearProcessTimeOut();
        console.log('onPage Login error1', err);
        notify("Please Connect to the internet! " + err)
        setProcessing(false);
      });

    SplashScreen.hide();
  }

  async function getIRSessionStatus() {
    // console.log("getIRSessionStatus");
    let count = await getIRPendingSessionCount(props);
    setIRSessionPendingCount(count);
    return true;
  }

  async function getDTasks() {
    return new Promise(async (resolve, reject) => {
      var DownloadTasks1 = [];
      if (props.DownloadKey != null && props.DownloadKey != '') {
        let prop_dk = JSON.parse(props.DownloadKey);
        // console.log('set server d keys');
        let AllDTs = prop_dk['DownloadKey'] || [];
        // console.log("kkkkkk--", AllDTs)
        await new Promise.all(AllDTs.sort((a, b) => {
          if (a.DownloadSequence < b.DownloadSequence) {
            return -1;
          }
          if (a.DownloadSequence > b.DownloadSequence) {
            return 1;
          }
          // a must be equal to b
          return 0;
        })).then((val) => {
          DownloadTasks1 = AllDTs
        });

        if (Production != true) {
          let tableStructureObj = AllDTs.find(item => item.DownloadKey === 'Table_Structure');
          let availableTables = [];
          if (tableStructureObj && tableStructureObj.ResponseData) {
            try {
              availableTables = typeof tableStructureObj.ResponseData === 'string'
                ? JSON.parse(tableStructureObj.ResponseData)
                : tableStructureObj.ResponseData;
            } catch (e) {
              console.warn("❌ Error parsing Table_Structure data", e);
            }
          }

          let listKys = devDownloadKeys(availableTables);
          console.log("✅ Dev keys after table check:", listKys.map(i => i.DownloadKey));
          const existingKeys = new Set(DownloadTasks1.map(item => item.DownloadKey));
          const finalDevKeys = listKys.filter(devItem => !existingKeys.has(devItem.DownloadKey));
          DownloadTasks1 = [...DownloadTasks1, ...finalDevKeys];
          console.log("DownloadTasks1----", DownloadTasks1);
        }
        setDownloadTasks(DownloadTasks1);
        resolve(true);
      }
      else {
        DownloadTasks1 = getDownloadDataTask();
        setDownloadTasks(DownloadTasks1);
        resolve(true);
      }
    }).catch((Err) => {
      return false;
    })

  }

  // download functionality start
  async function startDownload() {
    console.log('startDownload');
    clearProcessTimeOut();
    props.set_startDownload({ startDownload: true });
    setDowloadedCount(0);
    setOnDownloadCountChange(!onDownloadCountChange);
  }

  async function uploadPrevDayData() {
    // check if any store pending for which data exists and not uploaded
    setLoaderTitle('Loading...');
    clearProcessTimeOut();
    setProcessing(true);
    setProcessTimeOut();
    // if previous day data exists then upload data
    let isuploaded = await getLocOnCheckout(true);
    console.log("is prev day data uploaded:", isuploaded);
  }

  async function beforeExecuteTasks() {
    console.log('beforeExecuteTasks:');
    // ----------------- Clear DB ---------------------
    let ddata = { isDataDownloaded: false };
    await DownloadData(props, ddata).then((res) => {
      console.log('isAllTablesCreates:', res, DownloadTasks)
      if (totalCount == (DownloadTasks.length - 1) && totalCount > 0 && props.startDownload == true) {
        startDownload();
      } else {
        setTotalCount((DownloadTasks.length - 1));
      }
    });
  }


  async function onNoData(data = [], shouldStop = false, tbname = '', res = '', servertimealert = false) {
    console.log("res on no data:", res);
    if (tbname != '' && !tbname.includes('Master_MenuAppDashboard - ')) {
      db.transaction(function (txn) {
        // delete all today data
        txn.executeSql(`delete from ${tbname} where 1=1`, [], function (txn1, txnres) {
          console.log('deleted all data for ' + tbname);
        }, function (Etxn, err) {
          console.log('err:', err);
        });
      });
    }

    if (shouldStop == true) {
      let msg = '';
      // res should be set only when there is network or other related issue
      if (res == '') {
        msg = ST.Nodatafoundfor + tbname + '';
        if (tbname == 'Mapping_JourneyPlan') {
          msg = ST.Youhavenojourneyplanfortoday;
        }
      } else {
        msg = res + " Please ensure you are connected to the internet and retry downloading! ";
      }

      console.log("msg :", msg);
      // set is Data downloaded to false so that no other parts of app can be accessed if data is not downloaded
      // update download status on local async storage
      let dateWiseDataDownload = await get_item('dateWiseDataDownload');
      let dateWiseDataDownload1 = dateWiseDataDownload != null ? JSON.parse(dateWiseDataDownload) : {};
      let todayDate = moment(new Date()).format('DD/MM/YYYY');
      dateWiseDataDownload1[todayDate] = false;
      set_item('dateWiseDataDownload', JSON.stringify(dateWiseDataDownload1));
      // update downloaed status on redux props
      props.setTodayDataExists(false);
      props.setGlobalData({ isDataDownloaded: false })
      // notify(msg); 
      // show error msg
      if (servertimealert) {
        AlertForServerDT("", "");
        props.set_startDownload({ startDownload: false });
      } else {
        let obj = { "ErrorMsg": "!! Error in downloading data !!", "ErrorSubMsg": tbname, "ErrorDetail": msg }
        setDErrorMsg(obj);
        props.set_startDownload({ startDownload: false });
        setshowDErrAlert(true);
      }
    }
    else {
      setTaskResponse(data);
    }
  }

  async function executeTasks() {
    // var DownloadTasks=getDownloadDataTask();
    let loginInfo = await get_item('loginInfo');
    const loginDetails = JSON.parse(loginInfo);
    var currentIndex = dowloadedCount;
    console.log('currentIndex:', currentIndex);
    if (currentIndex >= 0) {
      let dk_data = DownloadTasks[currentIndex];
      console.log('dk_data', dk_data);
      let key = dk_data.DownloadKey || '';
      setDownloadingText(key);
      var data = await getPostData(DownloadTasks, currentIndex);
      var url = props.baseurl + getMethodName(METHODS.DOWNLOADJSON_METHOD);
      console.log(url, data);
      clearProcessTimeOut();
      setProcessTimeOut();
      await getDownloadJson1(url, data)
        .then(async (res) => {
          clearProcessTimeOut();
          if (key === 'Mapping_MenuConfiguration') {
            console.log("res-object", res)
          }
          let isAdded = await updateTaskRes(res, currentIndex, 1);
          console.log('res retuurn from updateTaskRes for ' + key);
          if (isAdded == true) {
            if (currentIndex == DownloadTasks.length - 1) {
              console.log('last found all downloaded');
              onDownloadComplete();
            }
            else {
              console.log('all downloaded but last not found ');
            }
          }
          else {
            console.log('Cannot download all Data');
            notify("Cannot download all Data!");
            props.set_startDownload({ startDownload: false });
          }
        })
        .catch(err => {
          notify("Please retry downloading! There is some error while downloading data");
          clearProcessTimeOut();
          props.set_startDownload({ startDownload: false });
          console.log('onPage Team error', err);
        });
    }

  }

  async function onDownloadComplete() {
    clearProcessTimeOut();
    let dateWiseDataDownload = await get_item('dateWiseDataDownload');
    let dateWiseDataDownload1 = dateWiseDataDownload != null ? JSON.parse(dateWiseDataDownload) : {};
    let todayDate = moment(new Date()).format('DD/MM/YYYY');
    dateWiseDataDownload1[todayDate] = true;
    set_item('dateWiseDataDownload', JSON.stringify(dateWiseDataDownload1));
    await CreateDirKPIimg();
    ///jp change avoid image upload if any coverage working
    let countPrevCovrage = await getPrevCoverageData(true);
    if (countPrevCovrage > 0) {
      await UploadAllPrevImages();
    }
    countPrevCovrage = await getPrevCoverageData(false);
    if (countPrevCovrage == 0) {
      await UploadAllPrevImages();
    }
    setisDataDownloaded(true);
    let count = dowloadedCount + 1;
    props.set_startDownload({ startDownload: false });
    props.setTodayDataExists(true);
    props.setGlobalData({ isDataDownloaded: true })
    clear_item('DataStorageCleared');
    setDowloadedCount(count);
    notify(ST.DataDownloaded, 'SHORT');
  }


  async function getPrevCoverageData(checkPrev) {
    console.log("getPrevCoverageData called");
    return new Promise((resolve, reject) => {
      let d1 = new Date();
      let d2 = moment(d1).format('MM/DD/YYYY');
      db.transaction(txn => {
        let q2 = `SELECT * FROM DR_COVERAGE WHERE VISIT_DATE = ?`;
        if (checkPrev) {
          q2 = `SELECT * FROM DR_COVERAGE WHERE VISIT_DATE != ?`;
        }
        txn.executeSql(
          q2,
          [d2],
          (txn2, txnres2) => {
            console.log('getPrevCoverageData:', txnres2.rows.length);
            resolve(txnres2.rows.length); // ✅ return value here
          },
          (txn2, txnerr) => {
            console.log(txnerr);
            reject(txnerr); // ⛔ in case of error
          }
        );
      });
    });
  }

  async function UploadAllPrevImages() {
    let allfiles = await getAllFolderImages();
    console.log('UploadAllPrevImages allfiles to upload:', allfiles.length);
    if (allfiles.length > 0) {
      let isAllUploaded = await uploadAllImages(props, {}, allfiles, '');
      console.log('uploading prev files:', isAllUploaded);
    }
  }

  /**
 * Dynamically inserts JSON data into a SQLite table.
 * @param {object} db - SQLite database instance
 * @param {string} tableName - Target table name
 * @param {Array} jsonData - Array of objects to insert
 * @returns {Promise<string|null>} Returns table name on error, or null on success
 */

  async function insertJsonDataToTable(db, tableName, jsonData) {
    return new Promise((resolve) => {
      // ✅ Check for empty data
      if (!Array.isArray(jsonData) || jsonData.length === 0) {
        console.warn(`⚠️ No data to insert in table: ${tableName}`);
        return resolve(true);
      }
      if (tableName === 'Gyancast_TrainingContent') {
        console.log("Gyancast_TrainingContent_Data", jsonData)
      }

      // ✅ Collect all unique keys (columns) from all rows
      const columns = Array.from(
        new Set(jsonData.flatMap(row => Object.keys(row)))
      );

      // ✅ Normalize all rows: fill missing columns with null
      const normalizedData = jsonData.map(row => {
        const normalizedRow = {};
        columns.forEach(col => {
          normalizedRow[col] = row.hasOwnProperty(col) ? row[col] : null;
        });
        return normalizedRow;
      });

      // ✅ Convert normalized data to SQL values string
      const valuesArray = normalizedData.map(row => {
        const valueList = columns.map(col => {
          let val = row[col];
          if (val === null || val === undefined) return 'NULL';
          if (typeof val === 'number') return val;
          if (typeof val === 'boolean') return val ? 1 : 0;
          // If val is an object or array, stringify it
          if (typeof val === "object") val = JSON.stringify(val);
          return `'${val.toString().replace(/'/g, "")}'`;// escape single quotes
        });
        return `(${valueList.join(',')})`;
      });

      // ✅ Construct final SQL INSERT
      const sql = `INSERT INTO ${tableName} (${columns.join(',')}) VALUES ${valuesArray.join(',')};`;

      try {
        db.transaction((txn) => {
          // ✅ First, delete existing data
          txn.executeSql(`DELETE FROM ${tableName}`, [], () => {
            // ✅ Then insert new normalized data
            txn.executeSql(sql, [], () => {
              setTaskResponse(jsonData); // Optional: your callback
              console.log(`✅ Inserted data into table: ${tableName}`);
              resolve(true);
            }, (tx, error) => {
              console.error(`❌ Insert failed in table: ${tableName}`, error);
              resolve(false);
            });
          }, (tx, error) => {
            console.error(`❌ Delete failed in table: ${tableName}`, error);
            resolve(false);
          });
        });
      } catch (e) {
        console.error(`❌ Transaction error for table: ${tableName}`, e);
        resolve(false);
      }
    });
  }


  ///created by jp first drop table if exist then re-created fixed new added column issue
  const recreateAllTables = (res) => {
    return new Promise((resolve, reject) => {
      if (res != null && res.Table_Structure) {
        const Table_Structure = res.Table_Structure || [];
        setAllTableQueries(Table_Structure);
        if (Table_Structure.length === 0) {
          resolve(false);
          return;
        }

        const getTableNameFromSql = (sql) => {
          const match = sql.match(/Create Table If Not Exists (\w+)/i);
          return match ? match[1] : null;
        };

        const dropAllTables = () => {
          return new Promise((dropResolve) => {
            let dropCount = 0;
            for (let i = 0; i < Table_Structure.length; i++) {
              const sql = Table_Structure[i].SqlText;
              const tableName = getTableNameFromSql(sql);
              if (!tableName) {
                console.warn('Unable to extract table name from:', sql);
                dropCount++;
                if (dropCount === Table_Structure.length) dropResolve();
                continue;
              }
              db.transaction((txn) => {
                txn.executeSql(
                  `DROP TABLE IF EXISTS ${tableName}`,
                  [],
                  () => {
                    console.log(`Dropped table: ${tableName}`);
                    dropCount++;
                    if (dropCount === Table_Structure.length) dropResolve();
                  },
                  (errTxn, err) => {
                    console.error(`Error dropping ${tableName}:`, err);
                    dropCount++;
                    if (dropCount === Table_Structure.length) dropResolve();
                  }
                );
              });
            }
          });
        };

        const createAllTables = () => {
          return new Promise((createResolve) => {
            let createCount = 0;
            for (let i = 0; i < Table_Structure.length; i++) {
              const sql = Table_Structure[i].SqlText;
              db.transaction((txn) => {
                txn.executeSql(
                  sql,
                  [],
                  () => {
                    console.log(`Created table: ${getTableNameFromSql(sql)}`);
                    createCount++;
                    if (createCount === Table_Structure.length) {
                      setTaskResponse(Table_Structure);
                      createResolve(true);
                    }
                  },
                  (errTxn, err) => {
                    console.error('Create table error:', err, sql);
                    createCount++;
                    if (createCount === Table_Structure.length) createResolve(true);
                  }
                );
              });
            }
          });
        };

        // Execute drop then create
        dropAllTables()
          .then(() => createAllTables())
          .then(resolve)
          .catch(reject);
      } else {
        resolve(false);
      }
    });
  };

  async function updateTaskRes(res, index, count) {
    // var DownloadTasks=getDownloadDataTask();   
    const todate = new Date();
    const today = moment(todate).format("MM/DD/YYYY");
    let d2 = today;
    let dk_data = DownloadTasks[index];
    let key = dk_data.DownloadKey || '';

    let IsMandatory = dk_data.IsMandatory == 'true' || dk_data.IsMandatory == 1 ? true : false;

    return new Promise(async (resolve, reject) => {
      switch (key) {
        case 'Table_Structure': {
          let status = await recreateAllTables(res);
          resolve(status);
          break;
        }

        case 'Mapping_JourneyPlan': {
          if (res != null && typeof res == 'object' && res.Mapping_JourneyPlan != null && res.Mapping_JourneyPlan != '') {
            let data_arr = res.Mapping_JourneyPlan || [];
            let status = insertJsonDataToTable(db, key, data_arr);
            if (status) {
              //get FTD Data when JourneyPlan downloaded
              getFTDData();
              resolve(true);
            }
            resolve(status)
          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Mapping_JourneyPlan'], IsPJPMandatory, 'Mapping_JourneyPlan');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Mapping_JourneyPlan'], true, 'Mapping_JourneyPlan', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Mapping_JourneyPlan'], true, 'Mapping_JourneyPlan', res);
            resolve(false);
          }
          break;
        }

        case 'Report_AferCheckIn': {
          if (res != null && typeof res == 'object' && res.Report_AferCheckIn != null && res.Report_AferCheckIn != '') {
            let data_arr = res.Report_AferCheckIn || [];
            try {
              let jsonStr = JSON.stringify(data_arr)
              await set_item('Report_AferCheckIn', jsonStr);
              console.log('Report_AferCheckIn added');
              setTaskResponse(data_arr);
              resolve(true);
            } catch (e) {
              resolve(false);
            }

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            resolve(false);
          }
          break;
        }

        case 'Master_AppDashboardWebView': {
          if (res != null && typeof res == 'object' && res.Master_AppDashboardWebView != null && res.Master_AppDashboardWebView != '') {
            let data_arr = res.Master_AppDashboardWebView || [];
            if (data_arr?.length > 0) {
              console.log("Master_AppDashboardWebView", data_arr[0].AppDashboardWebUrl)
              props.set_AppDashboardWebViewObj(data_arr[0].AppDashboardWebUrl)
              resolve(true);
              setTaskResponse(data_arr);
            } else {
              props.set_AppDashboardWebViewObj("")
              setAppDashReportsSec([]);
              resolve(false);
            }
          } else {
            props.set_AppDashboardWebViewObj("")
            setAppDashReportsSec([]);
            resolve(false);
          }

          break;
        }

        case 'Master_MenuAppDashboard': {
          if (res != null && typeof res == 'object' && res.Master_MenuAppDashboard != null && res.Master_MenuAppDashboard != '') {
            let data_arr = res.Master_MenuAppDashboard || [];
            var values = [], reportKeysToDownload = [], MainReportsToShow = [];
            data_arr.map((data_obj) => {
              let { DashboardId, UserType, DashboardName, DashboardType, DownloadKey, GraphDetail, DrillDown, ParentId, DisplayOrder } = data_obj;
              values.push(` ('${DashboardId}','${UserType}','${DashboardName}','${DashboardType}','${DownloadKey}','${GraphDetail}','${DrillDown}','${ParentId}','${DisplayOrder}')`);
              reportKeysToDownload.push(DownloadKey);
              // only those report will be shown which parent id is either null or 0
              if (ParentId == null || ParentId == 0 || ParentId == '0') {
                MainReportsToShow.push(data_obj);
              }
            });
            MainReportsToShow.sort((a, b) => a.DisplayOrder - b.DisplayOrder);
            setAppDashReportsSec(MainReportsToShow);
            var all_vals = values.join(',');
            var sql_stmnt = `INSERT INTO Master_MenuAppDashboard(DashboardId,UserType,DashboardName,DashboardType,DownloadKey,GraphDetail,DrillDown,ParentId,DisplayOrder)
            values ${all_vals}`;
            db.transaction(function (txn) {
              // delete all today data
              txn.executeSql(`delete from Master_MenuAppDashboard where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], async function (txn1, txnres) {
                  console.log('Master_MenuAppDashboard added');
                  // download reports data for dashboard
                  let isReportsDownloaded = await downloadReportKeys(reportKeysToDownload)
                  if (!isReportsDownloaded.success && isReportsDownloaded.error != null && isReportsDownloaded.error != '') {
                    console.log("Cannot download dashboard reports");
                    await onNoData(['No data for Master_MenuAppDashboard'], true, 'Master_MenuAppDashboard - ' + isReportsDownloaded.reportKey, isReportsDownloaded.error);
                    resolve(false);
                  }
                  else {
                    setTaskResponse(data_arr);
                    console.log("All Report Keys Dowbloaded", isReportsDownloaded);
                    resolve(true);
                  }

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

          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            setAppDashReportsSec([]);
            await onNoData(['No data for Master_MenuAppDashboard'], false, 'Master_MenuAppDashboard');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            setAppDashReportsSec([]);
            await onNoData(['No data for Master_MenuAppDashboard'], true, 'Master_MenuAppDashboard', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            setAppDashReportsSec([]);
            await onNoData(['No data for Master_MenuAppDashboard'], true, 'Master_MenuAppDashboard', res);
            resolve(false);
          }
          break;
        }

        // -------------Historic Data ----------------
        case 'LastVisit_PaidVisibility': {
          if (res.PaidVisibility) {
            let data_arr = res.PaidVisibility || [];
            var values = [], child_values = [], checklist_values = [];
            let StoreId_arr = [];
            console.log('LastVisit_PaidVisibility len:', data_arr.length)
            let nonVis_q = `Select * From Master_NonVisibility`;
            let AllNonVis = await executeQuery(nonVis_q, 'get');
            let displayCheckExists = false;
            await Promise.all(
              data_arr.map(async (data_obj, index) => {
                let { StoreId, SubCategoryId, DisplayId, Present, ReasonId, Checklists } = data_obj;
                let commonId = 'PaidVis' + moment().format('MMDDYYYYHHmmss') + index;
                StoreId_arr.push(StoreId);
                //get AllSubCats data
                let getcq = Q_getpaidvisibility({ StoreId: StoreId });
                let AllSubCats = await executeQuery(getcq, 'get');
                let SubCatObj = AllSubCats.find(i => i.SubCategoryId == SubCategoryId) || {};
                let SubCategoryName = SubCatObj.SubCategoryName != null ? SubCatObj.SubCategoryName : '';

                let join = `  INNER JOIN Mapping_Visibility v on p.SubCategoryId=v.SubCategoryId `;
                let join2 = ` INNER join Master_Display md on md.DisplayId=v.DisplayId `;
                let sku_q2 = `SELECT DISTINCT md.DisplayId,md.DisplayName,md.RefImage from Product_Master p  ${join} ${join2} where v.StoreId='${StoreId}' and (p.SubCategoryId='${SubCategoryId}' or p.SubCategoryId= ${SubCategoryId})`;
                let AllDisplays = await executeQuery(sku_q2, 'get');
                let DisplayObj = AllDisplays.find(i => i.DisplayId == DisplayId) || {};
                let DisplayName = DisplayObj.DisplayName != null ? DisplayObj.DisplayName : '';

                let NonVisObj = AllNonVis.find(i => i.ReasonId == ReasonId) || {};
                let Reason = NonVisObj.Reason != null ? NonVisObj.Reason : '';
                let IsRemarkTaken = NonVisObj.IsRemarkTaken == 1 || NonVisObj.IsRemarkTaken == '1' ? 1 : 0;


                values.push(` ('${StoreId}','${d2}','${SubCategoryName}','${SubCategoryId}','${d2}')`);
                child_values.push(` ('${commonId}','${StoreId}','${d2}','${SubCategoryName}','${SubCategoryId}','${Present == true ? 1 : 0}','${DisplayId}','${DisplayName}','','','${Reason}','${ReasonId}','${IsRemarkTaken}','','${d2}') `);

                let Checklist_arr = Checklists || [];
                Checklist_arr.map(async (checklistData, j) => {

                  let { ChecklistId, AnswerId } = checklistData;
                  let DisplayId1 = checklistData.DisplayId;
                  let SubCategoryId1 = checklistData.DisplayId;

                  let checklq = `Select Distinct ChecklistId,ChecklistName,AnswerId,Answer  from Master_Checklist  Where ChecklistId ='${ChecklistId}'`;
                  let checkName_arr = await executeQuery(checklq, 'get');
                  let ChecklistName = checkName_arr.length > 0 ? checkName_arr[0].ChecklistName : '';

                  let AnsObj = checkName_arr.find(i => i.AnswerId == AnswerId) || {};
                  let Answer = AnsObj.Answer != null ? AnsObj.Answer : '';

                  checklist_values.push(` ('${commonId}','${StoreId}','${d2}','${SubCategoryId}','${DisplayId}','${ChecklistName}','${ChecklistId}','${Answer}','${AnswerId}','${d2}') `);
                  displayCheckExists = true;
                });

              })
            ).then(async (val) => {
              let StoreIds = StoreId_arr.join(',');
              let values1 = values.join(',');
              let child_values1 = child_values.join(',');
              let checklist_values1 = checklist_values.join(',');
              //Remove Old data
              let q = `DELETE FROM ${AppTables.PAID_VISIBILITY_HEADER_DATA} WHERE STORE_ID in (${StoreIds}) and VISIT_DATE='${d2}' `;
              let q2 = `DELETE FROM ${AppTables.PAID_VISIBILITY_CHILD_DATA} WHERE STORE_ID in (${StoreIds}) and VISIT_DATE='${d2}' `;
              let q3 = `DELETE FROM ${AppTables.PAID_VIS_CHECKLIST} WHERE STORE_ID in (${StoreIds})  and VISIT_DATE='${d2}' `;
              let isHdrRemoved = await executeQuery(q);
              let isChildRemoved = await executeQuery(q2);
              let isChecklistRemoved = await executeQuery(q3);
              let add_HdrData = `INSERT INTO ${AppTables.PAID_VISIBILITY_HEADER_DATA} (STORE_ID,VISIT_DATE,SUB_CATEGORY,SUB_CATEGORY_ID,ADDED_DATE) VALUES ${values1} `;
              let add_ChildData = `INSERT INTO ${AppTables.PAID_VISIBILITY_CHILD_DATA} (COMMON_ID,STORE_ID,VISIT_DATE,SUB_CATEGORY,SUB_CATEGORY_ID,VISIBILITY_PRESENT,DISPLAY_ID,DISPLAY,IMAGE1,IMAGE2,REASON,REASON_ID,SHOW_RSN_REMARK,REASON_REMARK,ADDED_DATE) VALUES ${child_values1} `;
              let add_Checklist = `INSERT INTO ${AppTables.PAID_VIS_CHECKLIST} (COMMON_ID,STORE_ID,VISIT_DATE,SUB_CATEGORY_ID,DISPLAY_ID,CHECKLIST,CHECKLIST_ID,REASON,REASON_ID,ADDED_DATE) VALUES ${checklist_values1} `;
              db.transaction(function (txn) {
                // delete all today data
                txn.executeSql(add_HdrData, [], function (txn1, txnres) {
                  // insert or refresh all today data
                  txn.executeSql(add_ChildData, [], function (txn1, txnres) {
                    if (displayCheckExists == true) {
                      txn.executeSql(add_Checklist, [], function (txn1, txnres) {
                        console.log('LastVisit_PaidVisibility added');
                        setTaskResponse(data_arr);
                        resolve(true);
                      }, function (Etxn, txnerr) { console.log('txnerr:', txnerr); resolve(true); });
                    }
                    else {
                      console.log('LastVisit_PaidVisibility added');
                      setTaskResponse(data_arr);
                      resolve(true);
                    }
                  }, function (Etxn, txnerr) { console.log('txnerr:', txnerr); resolve(true); });
                }, function (Etxn, txnerr) { console.log('txnerr:', txnerr); resolve(true); });
              });
            });
          }
          else if (res != null && typeof (res) == 'object' && (res.success == false || (res[0] != null && res[0].Result != null))) {
            console.log('No data found');
            await onNoData(['No data for LastVisit_PaidVisibility'], false, 'LastVisit_PaidVisibility');
            resolve(true);
          }
          else {
            await onNoData(['No data for LastVisit_PaidVisibility']);
            resolve(true);
          }
          break;
        }
        case 'LastVisit_Promotion': {
          if (res.Promotion) {
            let data_arr = res.Promotion || [];
            var values = [], child_values = [], stock_values = [];
            let StoreId_arr = [];
            console.log('LastVisit_Promotion len:', data_arr.length)
            let nonVis_q = `Select PromoReasonId as ReasonId,PromoReason as Reason,IsRemarkTaken From Master_PromotionReason`;
            let AllNonVis = await executeQuery(nonVis_q, 'get');
            let QAExists = false, StockExists = false;
            await Promise.all(
              data_arr.map(async (data_obj, index) => {
                let { StoreId, PromoDefinitionId, PromoId, PromoTable, PromoField, PromoValue, ChildName, Present, ReasonId, QuestionAnswers, StockData } = data_obj;
                let commonId = 'Promo' + moment().format('MMDDYYYYHHmmss') + index;
                StoreId_arr.push(StoreId);
                let join = ` inner join Mapping_StorePromotion s on w.PromoDefinitionId=s.PromoDefinitionId  `;
                let sku_q2 = ` SELECT w.PromoName from Master_PromotionDefinition w  ${join} where s.StoreId='${StoreId}' and w.PromoDefinitionId='${PromoDefinitionId}' and w.PromoId='${PromoId}'`;
                let PromoData = await executeQuery(sku_q2, 'get');
                let PromoObj = PromoData.length > 0 ? PromoData[0] : {};
                let PromoName = PromoObj.PromoName != null ? PromoObj.PromoName : '';
                let NonVisObj = AllNonVis.find(i => i.ReasonId == ReasonId) || {};
                let Reason = NonVisObj.Reason != null ? NonVisObj.Reason : '';
                let IsRemarkTaken = NonVisObj.IsRemarkTaken == 1 || NonVisObj.IsRemarkTaken == '1' ? 1 : 0;
                values.push(` ('${commonId}','${StoreId}','${d2}','${PromoDefinitionId}','${PromoId}','${PromoName}','${PromoTable}','${PromoField}','${PromoValue}','${ChildName}','${(Present == true ? 1 : 0)}','','${ReasonId}','${Reason}','','${IsRemarkTaken}','','${d2}')`);
                let QuestionAnswers_arr = QuestionAnswers || [];
                QuestionAnswers_arr.map(async (QAData, j) => {
                  let { PromoQuestionId, AnswerId } = QAData;
                  let PromoDefinitionId1 = QAData.PromoDefinitionId;
                  let PromoId1 = QAData.PromoId;
                  let QAdetailq = `Select Distinct wq.PromoQuestionId,wq.PromoQuestionCode,wq.QuestionType,wq.PromoqShowCamera,wq.PromoAnswerId,wq.PromoAnswerName,wq.PromoaShowCamera from Master_PromotionQuestion wq 
                  Inner join Mapping_PromotionQuestion mq on mq.PromoQuestionId=wq.PromoQuestionId 
                  Where wq.PromoDefinitionId='${PromoDefinitionId}' and  wq.PromoQuestionId='${PromoQuestionId}'`;
                  let QAdetail_arr = await executeQuery(QAdetailq, 'get');
                  let Qdetail = QAdetail_arr.length > 0 ? QAdetail_arr[0] : {};
                  let PromoQuestionCode = Qdetail.PromoQuestionCode != null ? Qdetail.PromoQuestionCode : '';
                  let QuestionType = Qdetail.QuestionType != null ? Qdetail.QuestionType : '';
                  let AnsObj = QAdetail_arr.find(i => i.PromoAnswerId == AnswerId) || {};
                  let Answer = AnsObj.PromoAnswerName != null ? AnsObj.PromoAnswerName : '';
                  child_values.push(` ('${commonId}','${StoreId}','${d2}','${PromoDefinitionId}','${PromoId}','${PromoQuestionId}','${PromoQuestionCode}','${QuestionType}','${Answer}','${AnswerId}','','','${0}','${d2}') `);
                  QAExists = true;
                });
                let StockData_arr = StockData || [];
                StockData_arr.map(async (STkData, k) => {
                  let { PromoStockDefinitionId, PromoStockTable, PromoStockField, PromoStockValue, PromoStockMBQ, Stock, ProductName, isPromoPresent } = STkData;
                  let PromoDefinitionId1 = STkData.PromoDefinitionId;
                  let PromoId1 = STkData.PromoId;
                  stock_values.push(` ('${commonId}','${StoreId}','${d2}','${PromoDefinitionId}','${PromoId}','${PromoStockDefinitionId}','${PromoStockTable}','${PromoStockField}','${PromoStockValue}','${PromoStockMBQ}','${ProductName}','${Stock}','${(isPromoPresent == true ? 1 : 0)}','${d2}') `);
                  StockExists = true;
                });
              })
            ).then(async (val) => {
              let StoreIds = StoreId_arr.join(',');
              let values1 = values.join(',');
              let child_values1 = child_values.join(',');
              let stock_values1 = stock_values.join(',');
              //Remove Old data
              let q = `DELETE FROM ${AppTables.PROMO_HDR_DATA} WHERE STORE_ID in (${StoreIds}) and VISIT_DATE='${d2}' `;
              let q2 = `DELETE FROM ${AppTables.PROMO_CHILD_DATA} WHERE STORE_ID in (${StoreIds}) and VISIT_DATE='${d2}' `;
              let q3 = `DELETE FROM ${AppTables.PROMO_IMAGES} WHERE STORE_ID in (${StoreIds})  and VISIT_DATE='${d2}' `;
              let q4 = `DELETE FROM ${AppTables.PROMO_STOCK_DATA} WHERE STORE_ID in (${StoreIds})  and VISIT_DATE='${d2}' `;
              let isHdrRemoved = await executeQuery(q);
              let isChildRemoved = await executeQuery(q2);
              let isChecklistRemoved = await executeQuery(q3);
              let isStockRemoved = await executeQuery(q4);
              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,ADDED_DATE) VALUES ${values1} `;
              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,ADDED_DATE) VALUES ${child_values1} `;
              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 ${stock_values1} `;
              db.transaction(function (txn) {
                // delete all today data
                txn.executeSql(add_hdr_data, [], async function (txn1, txnres) {
                  // insert or refresh all today data
                  let QAexec = false, StockExec = false;
                  if (QAExists == true) {
                    QAexec = await executeQuery(add_child_data);
                  }
                  if (QAExists == true) {
                    StockExec = await executeQuery(add_stock_data);
                  }
                  console.log('LastVisit_Promotion added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (Etxn, txnerr) { console.log('txnerr:', txnerr); resolve(true); });
              });
            }).catch((err) => {
              resolve(true);
            });
          }
          else if (res != null && typeof (res) == 'object' && (res.success == false || (res[0] != null && res[0].Result != null))) {
            console.log('No data found');
            await onNoData(['No data for LastVisit_PaidVisibility'], false, 'LastVisit_PaidVisibility');
            resolve(true);
          }
          else {
            await onNoData(['No data for LastVisit_PaidVisibility']);
            resolve(true);
          }
          break;
        }
        case 'LastVisit_Visibility': {
          if (res.LastVisit_Visibility) {
            let data_arr = res.LastVisit_Visibility || [];
            var values = [], childV = [], StockV = [];
            let StoreId_arr = [];
            let nonVis_q = `Select POSMReasonId as ReasonId,POSMReason as Reason,IsRemarkTaken From Master_VisibilityReason`;
            let AllNonVis = await executeQuery(nonVis_q, 'get');
            let QAExists = false, StockExists = false;
            await Promise.all(
              data_arr.map(async (data_obj, index) => {
                let { StoreId, VisibilityDefinitionId, VisibilityId, VisibilityTable, VisibilityField, VisibilityValue, ChildName, Present, ReasonId, Question, Stock, QuestionAnswers, StockData } = data_obj;
                StoreId_arr.push(StoreId);
                let PVIS_HEADER_ID = 'PVIS_ID' + moment().format('MMDDYYYYHHmmss') + index;
                let selectlist2 = ` s.StoreId,w.VisibilityDefinitionId,w.VisibilityId,w.VisibilityName,w.VisibilityTable,w.VisibilityField,w.VisibilityValue,w.ChildName,w.VisibilityRefImage,w.VisibilityElementCheckAssortment,w.VisibilityElementStockRequired,'' as IsPresent,w.VisibilityNotExistCamera,'' as PVisNAImage,w.VisibilityExistReasonEnable,w.VisibilityNotExistReasonEnable,'' as ReasonId,'' as Reason,w.NoOfSplit,w.VisibilityImage1,w.VisibilityImage2,w.VisibilityImage1Lable,w.VisibilityImage2Lable,w.VisibilityImage1CameraGrid,w.VisibilityImage2CameraGrid,w.StockQtyRequired`;
                let join2 = ` inner join Mapping_StoreVisibility s on w.VisibilityDefinitionId=s.VisibilityDefinitionId  `;
                let q2 = ` Select ${selectlist2} from Master_VisibilityDefinition w  ${join2} where s.StoreId='${StoreId}' and  VisibilityDefinitionId='${VisibilityDefinitionId}' `;
                let AllDisplays = await executeQuery(q2, 'get');
                let NonVisObj = AllNonVis.find(i => i.ReasonId == ReasonId) || {};
                let IsRemarkTaken = NonVisObj.IsRemarkTaken == 1 || NonVisObj.IsRemarkTaken == '1' ? true : false;
                let VisibilityName = (AllDisplays && AllDisplays[0] && AllDisplays[0]["VisibilityName"] != null) ? AllDisplays[0]["VisibilityName"] : "";
                values.push(` ('${PVIS_HEADER_ID}','${StoreId}','${d2}','${VisibilityDefinitionId}','${VisibilityId}','${VisibilityName}', '${VisibilityTable}' , '${VisibilityField}' , '${VisibilityValue}' , '${ChildName}' , '${Present}' , '${""}' , '${ReasonId}' , '${IsRemarkTaken}' , '' ,'${d2}' )`);
                let StockData_arr = StockData = [];
                StockData_arr.map(async (STkData, k) => {
                  let { VisibilityStockDefinitionId, VisibilityStockTable, VisibilityStockField, VisibilityStockValue, VisibilityStockMBQ, ProductName, Stock, isPromoPresent } = STkData;
                  StockV.push(` ('${PVIS_HEADER_ID}','${StoreId}','${d2}','${VisibilityDefinitionId}','${VisibilityId}','${VisibilityStockDefinitionId}','${VisibilityStockTable}','${VisibilityStockField}','${VisibilityStockValue}','${VisibilityStockMBQ}','${ProductName}','${Stock}','${Present}','${d2}') `);
                  StockExists = true;
                });
                QuestionAnswers.map(async (QAdata, j) => {
                  let { VisibilityQuestionId, AnswerId } = QAdata;
                  let q12 = `select * from Master_VisibilityQuestion wq inner join Mapping_VisibilityQuestion mq on mq.POSMQuestionId=wq.POSMQuestionId where mq.VisibilityDefinitionId='${VisibilityDefinitionId}' and wq.VisibilityQuestionId='${VisibilityQuestionId}'    `;
                  let AllDisplays2 = await executeQuery(q12, 'get');
                  let VisibilityQuestionCode = (AllDisplays2 && AllDisplays2[0] && AllDisplays2[0]["VisibilityQuestionCode"] != null) ? AllDisplays[0]["VisibilityQuestionCode"] : "";
                  let QuestionType = (AllDisplays2 && AllDisplays2[0] && AllDisplays2[0]["QuestionType"] != null) ? AllDisplays[0]["QuestionType"] : "";
                  let VisibilityAnswerId = (AllDisplays2 && AllDisplays2[0] && AllDisplays2[0]["VisibilityAnswerId"] != null) ? AllDisplays[0]["VisibilityAnswerId"] : "";
                  let AnswerInd = AllDisplays2.findIndex(i => i.VisibilityAnswerId == AnswerId);
                  let AnswerObj = AnswerObj >= 0 ? AllDisplays2[AnswerInd] : {};
                  let ANSWER = AnswerObj.VisibilityAnswerName;
                  let IMAGE_ALLOW1 = (AllDisplays2 && AllDisplays2[0] && AllDisplays2[0].VAShowCamera == 'true' || AllDisplays2 && AllDisplays2[0] && AllDisplays2[0].VAShowCamera == true ? 1 : 0)
                  childV.push(` ('${PVIS_HEADER_ID}','${StoreId}','${d2}','${VisibilityDefinitionId}','${VisibilityId}','${VisibilityQuestionId}','${VisibilityQuestionCode}','${QuestionType}','${ANSWER}','${VisibilityAnswerId}','${multi_options_ids}','','${IMAGE_ALLOW1}','${d2}') `);
                  QAExists = true;
                })

              })
            ).then(async (val) => {
              let StoreIds = StoreId_arr.join(',');
              let values1 = values.join(',');
              let child_values = childV.join(',');
              let stockV = StockV.join(',')
              //Remove Old data
              let q = `DELETE FROM ${AppTables.PAIDVIS_HDR_DATA} WHERE STORE_ID in (${StoreIds}) and VISIT_DATE='${d2}' `;
              let q2 = `DELETE FROM ${AppTables.PAIDVIS_CHILD_DATA} WHERE STORE_ID in (${StoreIds}) and VISIT_DATE='${d2}' `;
              let q3 = `DELETE FROM ${AppTables.PAIDVIS_STOCK_DATA} WHERE STORE_ID in (${StoreIds})  and VISIT_DATE='${d2}' `;
              let isHdrRemoved = await executeQuery(q);
              let isChildRemoved = await executeQuery(q2);
              let isChecklistRemoved = await executeQuery(q3);
              let add_hdr_data = `INSERT INTO ${AppTables.PAIDVIS_HDR_DATA} (PVIS_HEADER_ID,STORE_ID,VISIT_DATE,PVIS_DEFINITION_ID,PVIS_ID,PVIS_NAME,PVIS_TABLE,PVIS_FIELD,PVIS_VALUE,CHILD_NAME,IS_PRESENT,PVIS_NA_IMAGE,REASON_ID,REASON,REMARK,ADDED_DATE) VALUES ${values1} `;
              let add_child_data = `INSERT INTO ${AppTables.PAIDVIS_CHILD_DATA} (PVIS_HEADER_ID,STORE_ID,VISIT_DATE,PVIS_DEFINITION_ID,PVIS_ID,QUESTION_ID,QUESTION_CODE,QUESTION_TYPE,ANSWER,ANSWER_ID,MULTI_OPTIONS_IDS,IMAGE1,IMAGE_ALLOW1,ADDED_DATE) VALUES ${child_values} `;
              let add_stock_data = `INSERT INTO ${AppTables.PAIDVIS_STOCK_DATA} (PVIS_HEADER_ID,STORE_ID,VISIT_DATE,PVIS_DEFINITION_ID,PVIS_ID,PVIS_STOCK_DEFINITION_ID,PVIS_STOCK_TABLE,PVIS_STOCK_FIELD,PVIS_STOCK_VALUE,PVIS_STOCK_MBQ,PRODUCT_NAME,STOCK,IS_PVIS_PRESENT,ADDED_DATE) VALUES ${stockV} `;
              db.transaction(function (txn) {
                // delete all today data
                txn.executeSql(add_hdr_data, [], async function (txn1, txnres) {
                  // insert or refresh all today data
                  if (QAExists == true) {
                    QAexec = await executeQuery(add_child_data);
                  }
                  if (QAExists == true) {
                    StockExec = await executeQuery(add_stock_data);
                  }
                  console.log('LastVisit_Visibility added');
                  setTaskResponse(data_arr);
                  resolve(true);

                }, function (Etxn, txnerr) { console.log('txnerr:', txnerr); resolve(true); });

              });
            }).catch((err) => {
              console.log('err:,', err);
              resolve(true);
            });
          }
          else if (res != null && typeof (res) == 'object' && (res.success == false || (res[0] != null && res[0].Result != null))) {
            console.log('No data found');
            onNoData(['No data for LastVisit_Visibility'], false, 'LastVisit_Visibility');
            resolve(true);
          }
          else {
            onNoData(['No data for LastVisit_Visibility']);
            resolve(true);
          }
          break;
        }

        case 'LastVisit_POSM': {
          if (res.POSM) {
            let data_arr = res.POSM || [];
            var values = [], childV = [], checklist_values = [];
            let StoreId_arr = [];
            let nonVis_q = `Select POSMReasonId as ReasonId,POSMReason as Reason,IsRemarkTaken From Master_POSMReason`;
            let AllNonVis = await executeQuery(nonVis_q, 'get');
            let displayCheckExists = false;
            await Promise.all(
              data_arr.map(async (data_obj, index) => {
                let { StoreId, POSMDefinitionId, POSMId, POSMTable, POSMField, POSMValue, Present, ChildName, POSMReasonId, QuestionAnswers } = data_obj;
                let QuestionAnswers_arr = QuestionAnswers || [];
                StoreId_arr.push(StoreId);
                let POSM_HEADER_ID = 'PaidVis' + moment().format('MMDDYYYYHHmmss') + index;
                StoreId_arr.push(StoreId);
                let join2 = ` inner join Mapping_StorePOSM s on w.POSMDefinitionId=s.POSMDefinitionId  `;
                let sku_q2 = ` Select * from Master_POSMDefinition w  ${join2} where s.StoreId='${StoreId}' and w.PosmId='${POSMId}' `;
                let AllDisplays = await executeQuery(sku_q2, 'get');
                let NonVisObj = AllNonVis.find(i => i.ReasonId == POSMReasonId) || {};
                let Reason = NonVisObj.Reason != null ? NonVisObj.Reason : '';
                let IsRemarkTaken = NonVisObj.IsRemarkTaken == 1 || NonVisObj.IsRemarkTaken == '1' ? true : false;
                let POSM_NAME = (AllDisplays && AllDisplays[0] && AllDisplays[0]["POSMName"] != null) ? AllDisplays[0]["POSMName"] : "";
                let POSM_TYPE_ID = (AllDisplays && AllDisplays[0] && AllDisplays[0]["PosmTypeId"] != null) ? AllDisplays[0]["PosmTypeId"] : "";
                let POSM_TYPE_NAME = (AllDisplays && AllDisplays[0] && AllDisplays[0]["POSMTypeName"] != null) ? AllDisplays[0]["POSMTypeName"] : "";
                values.push(` ('${POSM_HEADER_ID}','${StoreId}','${d2}','${POSMDefinitionId}','${POSMId}','${POSM_NAME}', '${POSM_TYPE_ID}' , '${POSM_TYPE_NAME}' , '${POSMTable}' , '${POSMField}' , '${POSMValue}' , '${ChildName}' , '${Present}' , '' , '' , '' , '${POSMReasonId}', '${Reason}', '${IsRemarkTaken}', '','${d2}' )`);
                QuestionAnswers_arr.map(async (QAdata, j) => {
                  let { POSMQuestionId, AnswerId } = QAdata;
                  q12 = `select POSMQuestionCode,POSMQuestionName,QuestionType,POSMAnswerId,POSMAnswerName from Master_POSMQuestion wq inner join Mapping_POSMQuestion mq on mq.POSMQuestionId=wq.POSMQuestionId where mq.POSMDefinitionId='${POSMDefinitionId}' and wq.POSMQuestionId='${POSMQuestionId}'    `;
                  let AllNonVis12 = await executeQuery(q12, 'get');
                  let QUESTION_CODE = AllNonVis12 && AllNonVis12[0] && AllNonVis12[0].POSMQuestionCode != null ? AllNonVis12[0].POSMQuestionCode : ""
                  let QUESTION_TYPE = AllNonVis12 && AllNonVis12[0] && AllNonVis12[0].QuestionType != null ? AllNonVis12[0].QuestionType : ""
                  let AnswerInd = AllNonVis12.findIndex(i => i.POSMAnswerId == AnswerId);
                  let AnswerObj = AnswerObj >= 0 ? AllNonVis12[AnswerInd] : {};
                  let ANSWER = AnswerObj.POSMAnswerName;
                  let IMAGE_ALLOW1 = (AllNonVis12 && AllNonVis12[0] && AllNonVis12[0].PAShowCamera == 'true' || AllNonVis12 && AllNonVis12[0] && AllNonVis12[0].PAShowCamera == true ? 1 : 0)
                  childV.push(` ('${POSM_HEADER_ID}','${StoreId}','${d2}','${POSMDefinitionId}','${POSMId}','${POSMQuestionId}','${QUESTION_CODE}','${QUESTION_TYPE}','${ANSWER}','${AnswerId}','','','${IMAGE_ALLOW1}','${d2}') `);
                  displayCheckExists = true;
                })

              })
            ).then(async (val) => {
              let StoreIds = StoreId_arr.join(',');
              let values1 = values.join(',');
              let child_values = childV.join(',');
              //Remove Old data
              let q = `DELETE FROM ${AppTables.POSM_HDR_DATA} WHERE STORE_ID in (${StoreIds}) and VISIT_DATE='${d2}' `;
              let q2 = `DELETE FROM ${AppTables.POSM_CHILD_DATA} WHERE STORE_ID in (${StoreIds}) and VISIT_DATE='${d2}' `;
              let isHdrRemoved = await executeQuery(q);
              let isChildRemoved = await executeQuery(q2);
              let add_hdr_data = `INSERT INTO ${AppTables.POSM_HDR_DATA} (POSM_HEADER_ID,STORE_ID,VISIT_DATE,POSM_DEFINITION_ID,POSM_ID,POSM_NAME,POSM_TYPE_ID,POSM_TYPE_NAME,POSM_TABLE,POSM_FIELD,POSM_VALUE,CHILD_NAME,IS_PRESENT,POSM_NA_IMAGE,POSM_IMAGE1,POSM_IMAGE2,REASON_ID,REASON,SHOW_RSN_REMARK,REASON_REMARK,ADDED_DATE) VALUES ${values1} `;
              let add_child_data = `INSERT INTO ${AppTables.POSM_CHILD_DATA} (POSM_HEADER_ID,STORE_ID,VISIT_DATE,POSM_DEFINITION_ID,POSM_ID,QUESTION_ID,QUESTION_CODE,QUESTION_TYPE,ANSWER,ANSWER_ID,MULTI_OPTIONS_IDS,IMAGE1,IMAGE_ALLOW1,ADDED_DATE) VALUES ${child_values} `;
              db.transaction(function (txn) {
                // delete all today data
                txn.executeSql(add_hdr_data, [], function (txn1, txnres) {
                  // insert or refresh all today data
                  if (displayCheckExists == true) {
                    txn.executeSql(add_child_data, [], function (txn1, txnres) {
                      console.log('LastVisit_POSM added');
                      setTaskResponse(data_arr);
                      resolve(true);
                    }, function (Etxn, txnerr) { console.log('txnerr:', txnerr) });
                  } else {
                    setTaskResponse(data_arr);
                    resolve(true);
                  }
                }, function (Etxn, txnerr) {
                  console.log('txnerr:', txnerr)
                  resolve(true);
                });
              });
            }).catch((err) => {
              console.log('err:', err);
              resolve(true);
            });
          }
          else if (res != null && typeof (res) == 'object' && (res.success == false || (res[0] != null && res[0].Result != null))) {
            console.log('No data found'); onNoData(['No data for LastVisit_POSM'], false, 'LastVisit_POSM');
            resolve(true);
          }
          else {
            onNoData(['No data for LastVisit_POSM']);
            resolve(true);
          }
          break;
        }
        case 'LastVisit_AdditionalVisibility': {
          if (res.AdditionalVisibility) {
            let data_arr = res.AdditionalVisibility || [];
            var values = [], childV = [], checklist_values = [];
            let StoreId_arr = [];
            await Promise.all(
              data_arr.map(async (data_obj, index) => {
                let { StoreId, Present, BrandId, DisplayId, Remark } = data_obj;
                StoreId_arr.push(StoreId);
                let sku_q2 = ` Select * from Product_Master w where (w.BrandId='${BrandId}' or w.BrandId= ${BrandId}) `;
                let AllDisplays = await executeQuery(sku_q2, 'get');
                let CategoryName = (AllDisplays && AllDisplays[0] && AllDisplays[0]["CategoryName"] != null) ? AllDisplays[0]["CategoryName"] : "";
                let CategoryId = (AllDisplays && AllDisplays[0] && AllDisplays[0]["CategoryId"] != null) ? AllDisplays[0]["CategoryId"] : "";
                let SubCategoryName = (AllDisplays && AllDisplays[0] && AllDisplays[0]["SubCategoryName"] != null) ? AllDisplays[0]["SubCategoryName"] : "";
                let SubCategoryId = (AllDisplays && AllDisplays[0] && AllDisplays[0]["SubCategoryId"] != null) ? AllDisplays[0]["SubCategoryId"] : "";
                let BrandName = (AllDisplays && AllDisplays[0] && AllDisplays[0]["BrandName"] != null) ? AllDisplays[0]["BrandName"] : "";
                let sku_q3 = ` Select * from Master_Display w where (w.DisplayId='${DisplayId}' or w.DisplayId= ${DisplayId}) `;
                let AllDisplays2 = await executeQuery(sku_q3, 'get');
                let DisplayName = (AllDisplays2 && AllDisplays2[0] && AllDisplays2[0]["DisplayName"] != null) ? AllDisplays2[0]["DisplayName"] : "";
                values.push(` ('${StoreId}','${d2}','${Present}','${CategoryName}','${CategoryId}', '${SubCategoryName}' , '${SubCategoryId}' , '${BrandName}' , '${BrandId}' , '${DisplayName}' , '${DisplayId}' , '${Remark}' , '' , '${d2}' )`);
              })
            ).then(async (val) => {
              let StoreIds = StoreId_arr.join(',');
              let values1 = values.join(',');
              //Remove Old data
              let q = `DELETE FROM ${AppTables.ADDITIONAL_VISIBILITY} WHERE STORE_ID in (${StoreIds}) and VISIT_DATE='${d2}' `;
              let isHdrRemoved = await executeQuery(q);
              let add_data = `INSERT INTO ${AppTables.ADDITIONAL_VISIBILITY} (STORE_ID,VISIT_DATE,PRESENT,CATEGORY,CATEGORY_ID,SUB_CATEGORY,SUB_CATEGORY_ID,BRAND,BRAND_ID,DISPLAY,DISPLAY_ID,REMARK,IMAGE,ADDED_DATE) VALUES ${values1} `;
              db.transaction(function (txn) {
                // delete all today data
                txn.executeSql(add_data, [], function (txn1, txnres) {
                  // insert or refresh all today data
                  console.log('LastVisit_AdditionalVisibility added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (Etxn, txnerr) {
                  console.log('txnerr:', txnerr)
                  resolve(true);
                });
              });
            }).catch((err) => {
              console.log('err:', err);
              resolve(true);
            });
          }
          else if (res != null && typeof (res) == 'object' && (res.success == false || (res[0] != null && res[0].Result != null))) {
            console.log('No data found'); onNoData(['No data for LastVisit_POSM'], false, 'LastVisit_POSM');
            resolve(true);
          }
          else {
            onNoData(['No data for LastVisit_POSM']);
            resolve(true);
          }
          break;
        }

        case 'LastVisit_StockSingleKPI': {
          if (res.StockSingleKPI) {
            let data_arr = res.StockSingleKPI || [];
            let StoreId_arr = [];
            var values = [], stock_values = [], mfdStockV = [];
            await Promise.all(
              data_arr.map(async (data_obj, index) => {
                let { StoreId, ProductId, MBQ, MSL, Stock, BackroomStock, DamagedStock, LostStock, ExpiryStock, IsSkuPresent, OutOfStock, LessThanMBQ, NrExpiryStock1, NrExpiryStock2, NrExpiryStock3, MFD_Stocks } = data_obj;
                StoreId_arr.push(StoreId);
                let commonId = 'Stock' + moment().format('MMDDYYYYHHmmss') + index;
                let SKU_UID = 'SKU' + moment().format('MMDDYYYYHHmmss') + index + (Math.floor(Math.random() * 1000) + 1);
                let MFD_Stocks1 = MFD_Stocks || []
                let join = `  inner join Mapping_ProductAssortmentStorewise m on p.ProductId=m.ProductId `;
                let q = `select distinct p.SubCategoryId,p.SubCategoryName,p.BrandId,p.BrandName from Product_Master p  ${join} where (p.ProductId='${ProductId}' or p.ProductId= ${ProductId}) order by p.SubCategoryName`;
                let AllDisplays = await executeQuery(q, 'get');
                let SubCategoryName = (AllDisplays && AllDisplays[0] && AllDisplays[0]["SubCategoryName"] != null) ? AllDisplays[0]["SubCategoryName"] : "";
                let SubCategoryId = (AllDisplays && AllDisplays[0] && AllDisplays[0]["SubCategoryId"] != null) ? AllDisplays[0]["SubCategoryId"] : "";
                let BrandId = (AllDisplays && AllDisplays[0] && AllDisplays[0]["BrandId"] != null) ? AllDisplays[0]["BrandId"] : "";
                let BrandName = (AllDisplays && AllDisplays[0] && AllDisplays[0]["BrandName"] != null) ? AllDisplays[0]["BrandName"] : "";
                let ProductName = (AllDisplays && AllDisplays[0] && AllDisplays[0]["ProductName"] != null) ? AllDisplays[0]["ProductName"] : "";
                values.push(` ('${StoreId}','${d2}','${SubCategoryName}','${SubCategoryId}','${MSL}','','','${d2}') `);
                stock_values.push(` ('${commonId}','${SKU_UID}','${StoreId}','${d2}','${SubCategoryId}','${SubCategoryName}','${BrandId}','${BrandName}','${ProductId}','${ProductName}','${MSL}','${Stock}','${BackroomStock}','${DamagedStock}','${LostStock}','${ExpiryStock}','${IsSkuPresent}','${NrExpiryStock1}','${NrExpiryStock2}','${NrExpiryStock3}','${OutOfStock}','${LessThanMBQ}','${d2}' )`);
                MFD_Stocks1.map((item, j) => {
                  let date = item.Mfd ? new Date(item.Mfd) : "";
                  let Stock = item.Stock ? item.Stock : "";
                  let mfd = item.Mfd ? item.Mfd : "";
                  let LotNo = item.LotNo ? item.LotNo : "";
                  mfdStockV.push(` ('${commonId}','${SKU_UID}','${StoreId}','${d2}','${SubCategoryId}','${BrandId}','${ProductId}','${Stock}','${mfd}','${LotNo}','${date}','${d2}') `);
                })
              })
            ).then(async (val) => {
              let StoreIds = StoreId_arr.join(',');
              let values1 = values.join(',');
              let stock_valuesV = stock_values.join(',');
              let mfdStockv = mfdStockV.join(',');
              //Remove Old data
              let q = `DELETE FROM ${AppTables.STOCK2HDR_DATA} WHERE STORE_ID in (${StoreIds}) and VISIT_DATE='${d2}' `;
              let q2 = `DELETE FROM ${AppTables.STOCK2_DATA} WHERE STORE_ID in (${StoreIds}) and VISIT_DATE='${d2}' `;
              let q3 = `DELETE FROM ${AppTables.STOCK2_MFD_DATA} WHERE STORE_ID in (${StoreIds})  and VISIT_DATE='${d2}' `;
              let isHdrRemoved = await executeQuery(q);
              let isChildRemoved = await executeQuery(q2);
              let isChecklistRemoved = await executeQuery(q3);

              let add_StockHdr = `INSERT INTO ${AppTables.STOCK2HDR_DATA} (STORE_ID,VISIT_DATE,SUB_CATEGORY,SUB_CATEGORY_ID,MSL,IMAGE,IMAGEPATH,ADDED_DATE) VALUES ${values1} `;
              let add_Stock = `INSERT INTO ${AppTables.STOCK2_DATA} (COMMON_ID,STOCK_UID,STORE_ID,VISIT_DATE,SUB_CATEGORY_ID,SUB_CATEGORY,BRAND_ID,BRAND,PRODUCT_ID,PRODUCT,MSL,STOCK,BACKROOM_STOCK,DAMAGED_STOCK,LOST_STOCK,EXPIRY_STOCK,IS_SKU_STOCK_PRESENT,NREXPIRY1_STOCK,NREXPIRY2_STOCK,NREXPIRY3_STOCK,OUT_OF_STOCK,LESS_THAN_MBQ,ADDED_DATE) VALUES ${stock_valuesV} `;
              let add_mfd_Stock = `INSERT INTO ${AppTables.STOCK2_MFD_DATA} (COMMON_ID,STOCK_UID,STORE_ID,VISIT_DATE,SUB_CATEGORY_ID,BRAND_ID,PRODUCT_ID,STOCK,MFD,LOT_NO,DATE,ADDED_DATE) VALUES ${mfdStockv} `;
              db.transaction(function (txn) {
                // delete all today data
                txn.executeSql(add_StockHdr, [], function (txn1, txnres) {
                  // insert or refresh all today data
                  console.log('stock header added');
                  //   // ************************************************
                  txn.executeSql(add_Stock, [], async function (txn2, txnres) {
                    console.log('stock added');
                    if (mfdStockV != null && mfdStockV != '') {
                      await txn.executeSql(add_mfd_Stock, [], async function (txn2, txnres) {
                        console.log('LastVisit_StockSingleKPI added');
                        setTaskResponse(data_arr);
                        resolve(true);
                      }, function (txnE, txnerr) {
                        console.log(txnerr);
                        resolve(true);
                      },);
                    }
                    else {
                      setTaskResponse(data_arr);
                      resolve(true);
                    }
                  })

                }, function (Etxn, txnerr) { console.log('txnerr:', txnerr); resolve(true); });
              });
            }).catch((err) => {
              console.log('err:', err);
              resolve(true);
            });
          } else if (res != null && typeof (res) == 'object' && (res.success == false || (res[0] != null && res[0].Result != null))) {
            console.log('No data found'); onNoData(['No data for LastVisit_StockSingleKPI'], false, 'LastVisit_StockSingleKPI');
            resolve(true);
          }
          else {
            onNoData(['No data for LastVisit_StockSingleKPI']);
            resolve(true);
          }
          break;
        }
        // -------------Last Key (Needs to keep at end) ----------------
        case 'Training_Document': {
          if (res != null && typeof res == 'object' && res.Training_Document != null && res.Training_Document != '') {
            let data_arr = res.Training_Document || [];
            let TraningLink = data_arr.length > 0 ? (data_arr[0].TraningLink || '') : '';
            db.transaction(function (txn) {
              // delete all today data
              let sql_stmnt = `INSERT INTO Training_Document(TraningLink) VALUES('${TraningLink}')`;
              txn.executeSql(`delete from Training_Document where 1=1`, [], function (txn1, txnres) {
                // insert or refresh all today data
                txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                  console.log('Training_Document added');
                  setTaskResponse(data_arr);
                  resolve(true);
                }, function (Etxn, txnerr) { console.log('txnerr:', txnerr); resolve(true); });
              }, function (Etxn, txnerr) { console.log('txnerr:', txnerr); resolve(true); });
            });
          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for Training_Document'], false, 'Training_Document');
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for Training_Document'], true, 'Training_Document', res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for Training_Document'], true, 'Training_Document', res);
            resolve(false);
          }
          break;
        }

        default: {
          if (res != null && typeof res == 'object' && res[key] != null && res[key] != '') {
            let data_arr = res[key] || [];
            if (key === 'Mapping_MenuConfiguration') {
              console.log("Json_Data", data_arr);
            }
            resolve(insertJsonDataToTable(db, key, data_arr));
          }
          // pass to the next download key if data does not exists for this Key
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            await onNoData(['No data for ' + key], false, key);
            resolve(true);
          }
          // Stop Downloading and report error
          else if (res != null && typeof (res) == 'object' && res.success == false) {
            console.log('Error in downloading network', res);
            await onNoData(['No data for ' + key], true, key, res);
            resolve(false);
          }
          // Stop Downloading and report error
          else {
            console.log('Error in downloading else', res);
            await onNoData(['No data for ' + key], true, key, res);
            resolve(false);
          }
          break;
        }
      }
    }).catch((err) => {
      console.log('error in downloading', err);
      return false;
    });
  }
  async function executeQuery(q, type = 'state') {
    //  type can be : state, length or get
    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        await txn.executeSql(q, [], async function (txn2, txnres2) {
          if (type == 'state') {
            resolve(true);
          }
          else {
            if (txnres2.rows.length > 0) {
              if (type == 'length') {
                resolve(txnres2.rows.length);
              }
              else {
                // let data=txnres2.rows.raw();
                let arr = [];
                for (let i = 0; i < txnres2.rows.length; i++) {
                  let data = txnres2.rows.item(i);
                  arr.push(data);
                  if (i == txnres2.rows.length) {
                    resolve(arr);
                  }
                }
              }
            }
            else {
              type == 'length' ? resolve(0) : resolve([]);
            }
          }
        }, function (Etxn, txnerr) { console.log(txnerr); resolve(false) });
      });
    }).then((val) => {
      return val;
    }).catch((err) => {
      console.log(err);
      return false;
    })
  }

  // upload functionality start
  async function startUpload() {
    setLoaderTitle('Loading...');
    setProcessing(true);
    getLocOnCheckout(true);
  }

  async function getMenuList(storeData1) {
    let { StoreId, ChannelId, RegionId } = storeData1;
    return new Promise((resolve, reject) => {

      db.transaction(async function (txn) {
        let q = Q_MenuList(storeData1);
        await txn.executeSql(q, [], async function (txn2, txnres) {
          if (txnres.rows.length > 0) {
            let arr = [];//txnres.rows.raw();    
            console.log('menulist on nb:', arr);
            // resolve(arr);    
            for (var i = 0; i < txnres.rows.length; i++) {
              let data = txnres.rows.item(i);
              arr.push(data);
              if (i == (txnres.rows.length - 1)) {
                resolve(arr);
              }
            }
          }
          else {
            resolve([])
          }
        }, function (txnE, txnerr) { console.log(txnerr); resolve([]); },);
      });
    }).then((val) => {
      return val;
    }).catch((err) => {
      console.log('')
      return []
    })
  }

  async function UpdateUploadCountLocal(upCount) {
    // keep 1 less to actual count as DownloadDataModal shows it as provided_value+1
    setUploadedCount(upCount - 1);
  }

  async function getLocOnCheckout(previousDayUpload = false) {
    return new Promise((resolve, reject) => {
      Geolocation.getCurrentPosition(
        async (position) => {
          clearProcessTimeOut();
          let { latitude, longitude } = position.coords;
          let loc = { lat: latitude, lng: longitude };
          await UploadOnCheckOut(loc, previousDayUpload);
          resolve(true);
        },
        (error) => {
          notify(ST.Cannotgetuserposition);
          setStartUploading(false);
          resolve(false);
        },
        { enableHighAccuracy: true, distanceFilter: 0, interval: 1000, fastestInterval: 2000 }
      );
    }).then((res) => {
      return res
    }).catch((err) => {
      console.log("getLocOnCheckout err:", err)
      notify("Please allow location permission and keep your location on!")
      return false;
    })

  }

  async function UploadOnCheckOut(loc, previousDayUpload = false) {
    try {
      // This function will check all stores , visitors login and distributors data 
      // And will upload if exists any 
      // ####--------- Note : If previousDayUpload is true,                       --------------
      // ####--------- then all data will be uploaded without "VisitDate" condition --------------
      let d1 = new Date();
      let d2 = moment(d1).format('MM/DD/YYYY');
      let token = await get_item('loginToken');
      let loginInfo = await get_item('loginInfo');
      const loginDetails = JSON.parse(loginInfo);
      // Get All Stores Data to be uploaded 
      let PJPStores = await getPJPStoresData('Mapping_JourneyPlan', [], d2, previousDayUpload);
      let AdhocSTores = await getPJPStoresData('Adhoc_JourneyPlan', PJPStores, d2, previousDayUpload);
      let routeWise = await getPJPStoresData('JourneyPlan_RouteWise', AdhocSTores, d2, previousDayUpload);
      let nonProg = await getPJPStoresData('NonProgram_JourneyPlan', routeWise, d2, previousDayUpload);
      let storeSearch = await getPJPStoresData('StoreSearch_JourneyPlan', nonProg, d2, previousDayUpload);
      let AllStores = await getPJPStoresData('NonMerchandising_JourneyPlan', storeSearch, d2, previousDayUpload);
      // let AllStores=await getPJPStoresData('NonMerchandising_JourneyPlan',nonProg,d2,previousDayUpload);
      let AllVisitors = await getVisitorLogin(d2, previousDayUpload); // pending visitors data -Get All Visitors login Data to be uploaded 
      let PeningIRSessC = await getIRPendingSessionCount(props); // pending IR sess data -Get All Visitors login Data to be uploaded 
      let AllDistributors = await getDistributors(d2, previousDayUpload);// pending distributors data -Get All distribbutors Data to be uploaded 
      let AllContracts = await getContractForms(d2); // pending contract forms data -Get All ContractForms Data to be uploaded 
      let AllAddStoreInfo = await getAddStoreInfoForms(d2);
      let AllHomeLocation = await getHomeLocation(d2);
      console.log("PeningIRSessC:", PeningIRSessC);
      let uploadifany = false;
      if (AllStores.length > 0 || AllAddStoreInfo.length > 0 || AllDistributors.length > 0 || AllVisitors.length > 0 || PeningIRSessC > 0 || AllContracts.length > 0 || AllHomeLocation.length > 0) {
        // show uploading modal if any data exists to upload
        uploadifany = true;
        setProcessing(false); // hide process loader
        setTotalUpCount(0);
        setshowProgresssBar(false);
        //start uploading if distributor / contracts data exists - 
        // All data which needs to be uploaded other than (stores,visitor, and pending IR sessions) 
        // should be uploaded from here one by one and should be added in below condition
        if (AllDistributors.length > 0 || AllContracts.length > 0 || AllAddStoreInfo.length > 0 || AllHomeLocation.length > 0) {
          if (AllDistributors.length > 0) {//uploading distributor data 
            setUploadingText('Uploading distributors...');
            clearProcessTimeOut();
            setStartUploading(true);
            setProcessTimeOut(loaderTimeOut_longer);
            let isDistUploaded = await uploadAllDistributors(d2, loc, AllDistributors, previousDayUpload); // upload all distributors data 
            console.log("isDistUploaded:", isDistUploaded);
          }
          if (AllHomeLocation.length > 0) {//uploading AllHomeLocation data 
            console.log("uploading AllHomeLocation data-----", AllHomeLocation);
            setUploadingText('Uploading Home Location...');
            clearProcessTimeOut();
            setStartUploading(true);
            setProcessTimeOut(loaderTimeOut_longer);
            let isHomeLocationUploaded = await uploadAllHomeLocations(d2, loc, AllHomeLocation, previousDayUpload); // upload all distributors data 
            console.log("isHomeLocationUploaded:", isHomeLocationUploaded);
          }
          if (AllContracts.length > 0) {//uploading All Contracts data 
            setUploadingText('Uploading Contracts...');
            clearProcessTimeOut();
            setStartUploading(true);
            setProcessTimeOut(loaderTimeOut_longer);
            let isContractUploaded = await uploadAllContracts(d2, AllContracts); // upload all distributors data 
            console.log("isContractUploaded:", isContractUploaded);
            let isContractFilesUploaded = await uploadAllContractFiles();
            console.log("isContract Files Uploaded:", isContractFilesUploaded);

          }
          if (AllAddStoreInfo.length > 0) {
            //uploading All Contracts data
            setUploadingText(ST.UploadingAddStoreInfo);
            clearProcessTimeOut();
            setStartUploading(true);
            setProcessTimeOut(loaderTimeOut_longer);
            let isAddStoreInfoUploaded = await uploadAllAddStoreInfo(d2, AllAddStoreInfo); // upload all distributors data
            console.log('isAddStoreInfoUploaded:', isAddStoreInfoUploaded);
            let isAddStoreInfoFilesUploaded = await uploadAllAddStoreInfoFiles();
            console.log('isAddStoreInfo Files Uploaded:', isAddStoreInfoFilesUploaded);
            notify("Add Store Info data is uploaded");
          }
        }
        else {
          setUploadingText(ST.UploadingData + '...');
          clearProcessTimeOut();
          setStartUploading(true);
          setProcessTimeOut(loaderTimeOut_longer);
        }
      }
      else {
        console.log("else no data to upload");
        clearProcessTimeOut();
        setProcessing(false); // hide process loader
        props.set_startUpload({ startUpload: false });
        // check if start download is enabled the start Downloading
        setStartDafterPrevUpload(!StartDafterPrevUpload);
        if (props.startDownload == true) { // if uploading is called before start download
          // Don't do anything 
        }
        else {
          notify(ST.NodatatoUpload + ' for the store');
        }

        return false
      }

      if (uploadifany) {
        // return the function only when all uploads are done/completed
        return new Promise((resolve, reject) => {
          function resolveOnCompleteIR(res) {
            resolve(res);
          }

          function onStoreUploadLast(index, shouldret = true, res = true) {
            // check if last index of store then do the common thing 
            if (index == AllStores.length - 1) {
              // if IR session is pending then start uploading IR image data 
              // else stop uploading and hide the upload modal
              // checkForIR will be false if store data is not uploaded 
              if (PeningIRSessC > 0) {
                onUploadComplete(resolveOnCompleteIR)
              }
              else {
                setStartUploading(false);
                // check if start download is enabled the start Downloading
                setStartDafterPrevUpload(!StartDafterPrevUpload);
                if (shouldret) {
                  resolve(res);
                }
              }

            }
          }

          db.transaction(async function (txn) {
            console.log('stores to upload:', AllStores.length);
            // If Stores data exists then start uploading 
            if (AllStores.length > 0) {
              // If Visitors data also exists then upload visitors data first , after that upload stores data
              if (AllVisitors.length > 0) {
                setTotalUpCount(0);
                setshowProgresssBar(false);
                setUploadingText(ST.Uploadingvisitorsdata + '...');
                // setLoaderTitle(ST.Uploadingvisitorsdata+'...');
                let isallVisUploaded = await uploadAllVisitors(props, AllVisitors, previousDayUpload);
                if (isallVisUploaded == true) {
                  notify(ST.AllDataUploaded + '...');
                }
                else {
                  notify(ST.CannotUploadVisitors);
                }
              }
              for (var i = 0; i < AllStores.length; i++) {
                let data = AllStores[i];
                const index = i;
                let { StoreId, StoreName, EmpId, MID, UploadStatus, Status, VisitDate, REASON_ID, JCP_TYPE } = data;
                // get all checkout ids data
                // setLoaderTitle(ST.UploadingDatafor+' '+StoreName+'...');

                let MenuList = await getMenuList(data);
                let allKPIs = await getKPIS(MenuList, props); // get KPIs to be uploaded from Menu list
                let totalUpC = MenuList.length - 1; // keep 1 less to actual count as DownloadDataModal shows it as provided_value+1

                // if(UploadStatus=='U'){ UploadStatus='C';}
                console.log('UploadStatus before Start Uploading Data store :', totalUpC, UploadStatus);
                setTotalUpCount(totalUpC);
                setshowProgresssBar(false);
                setUploadingSubText("Uploading Data for Store:" + StoreId);

                if (UploadStatus == 'C') {
                  let isUploaded_P = await uploadStoreStatus(props, data, 'P', JCP_TYPE, previousDayUpload);
                  if (isUploaded_P == true) {
                    setTotalUpCount(totalUpC);
                    setshowProgresssBar(true);
                    setUploadingText(ST.UploadingData + '...');
                    await uploadAfter_P_status(index, AllStores, data, MenuList, allKPIs, JCP_TYPE, loc, onStoreUploadLast, previousDayUpload)
                  } else {
                    notify(ST.Erroroccurwhileuploadingdatafor + ' ' + StoreName, 'LONG');
                    onStoreUploadLast(index); // check if last then end uploading
                  }
                } else if (UploadStatus == 'D') {
                  setTotalUpCount(totalUpC);
                  setshowProgresssBar(true);
                  setUploadingText(ST.UploadingData + '...');
                  //  this never be called if there is no KPI
                  let allFilesToUpload = await uploadAllData(props, data, allKPIs, props.UserId, JCP_TYPE, false, UpdateUploadCountLocal, previousDayUpload);
                  console.log('allFilesToUpload.length:', allFilesToUpload.length);
                  if (allFilesToUpload.length > 0) {
                    await UploadDataWithImages(index, AllStores, data, MenuList, allKPIs, JCP_TYPE, allFilesToUpload, loc, onStoreUploadLast, previousDayUpload);
                  } else {
                    let isUploaded_U = await uploadStoreStatus(props, data, 'U', JCP_TYPE, previousDayUpload);
                    notify(ST.Alldatauploadedfor + ' ' + StoreName, 'SHORT');
                    onStoreUploadLast(index); // check if last then end uploading
                  }
                }
                else if (UploadStatus == 'P') {
                  setTotalUpCount(totalUpC);
                  setshowProgresssBar(true);
                  setUploadingText(ST.UploadingData + '...');
                  await uploadAfter_P_status(index, AllStores, data, MenuList, allKPIs, JCP_TYPE, loc, onStoreUploadLast, previousDayUpload);
                } else if (UploadStatus == 'L') {
                  setshowProgresssBar(false);
                  setUploadingText(ST.UploadingData + '...');
                  let isAllUploaded_S = await uploadStoreStatus(props, data, 'U', JCP_TYPE, previousDayUpload);
                  if (isAllUploaded_S == true) {
                    notify(ST.Alldatauploadedfor + ' ' + StoreName, 'SHORT');
                    onStoreUploadLast(index); // check if last then end uploading
                  } else {
                    onStoreUploadLast(index); // check if last then end uploading
                  }
                } else {
                  onStoreUploadLast(index); // check if last then end uploading
                }
                if (index == 0) {
                  props.set_startUpload({ startUpload: false });
                }
              }

            }
            else if (AllVisitors.length > 0) {
              // setLoaderTitle(ST.Uploadingvisitorsdata+'...');
              setTotalUpCount(AllVisitors.length - 1);
              setshowProgresssBar(false);
              setUploadingText(ST.Uploadingvisitorsdata + '...');

              let isallVisUploaded = await uploadAllVisitors(props, AllVisitors, previousDayUpload);
              // setProcessing(false);
              // setStartUploading(false);
              if (PeningIRSessC) {
                onUploadComplete(resolveOnCompleteIR)
              } else {
                setStartUploading(false);
                props.set_startUpload({ startUpload: false });
                resolve(true);
              }

              if (isallVisUploaded == true) {
                notify(ST.AllDataUploaded);
              }
              else {
                notify(ST.CannotUploadVisitors);
              }

            }
            else {
              if (PeningIRSessC > 0) { // start Uploading IR session 
                onUploadComplete(resolveOnCompleteIR)
              } else {// set Uploading modal to false when all uploading or no data found
                setStartUploading(false);
                props.set_startUpload({ startUpload: false });
                //check if uploading is called before start download then Start downloading 
                setStartDafterPrevUpload(!StartDafterPrevUpload);
                resolve(true);
              }


              if (AllDistributors.length > 0) {// if distributor data exists and uploaded 
                // Don't do anything 
              }
              else if (AllContracts.length > 0) {// if contract data exists and uploaded 
                // Don't do anything 
              }
              else if (IRSessionPendingCount > 0) {// if IR data exists  and uploading started
                // Don't do anything 
              }
              else {// No data found to upload (in visitors , distributors and stores)
                if (props.startDownload == true) { // if uploading is called before start download
                  // Don't do anything 
                }
                else {
                  notify(ST.NodatatoUpload);
                }
              }

            }
          });

        }).then((res) => {
          return res;
        }).catch((err) => {
          console.log("UploadOnCheckOut err:", err);
          return false;
        })

      }

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

  async function refreshDashBReport() {
    console.log('refreshDashBReport');
    setLoaderTitle("Refreshing dashboard reports..")
    setProcessing(true);
    try {

      let loginInfo = await get_item('loginInfo');
      const loginDetails = JSON.parse(loginInfo);

      let dk_index = DownloadTasks.findIndex(i => i.DownloadKey == 'Master_MenuAppDashboard');
      var data = {
        Downloadtype: "Master_MenuAppDashboard",
        Username: loginDetails.UserId,
        Param1: '',
        Param2: Platform.OS == "ios" ? "iOS" : "Android",
      };
      var url = props.baseurl + getMethodName(METHODS.DOWNLOADJSON_METHOD);
      console.log(url, data);

      await getDownloadJson1(url, data)
        .then(async (res) => {
          let isAdded = await updateTaskRes(res, dk_index, 1);
          if (isAdded == true) {
            notify("Dashboard reports refreshed!");
            setProcessing(false);
          }
          else {
            notify("Cannot refresh dashboard reports!");
            setProcessing(false);
          }
        })
        .catch(err => {
          notify("Cannot refresh dashboard reports!");
          setProcessing(false);
        });

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


  async function downloadReportKeys(reportKeysToDownload = []) {
    console.log('downloadReportKeys');
    let defData = { success: true, error: '', }
    return new Promise(async (resolve, reject) => {
      let reports = {};
      for (let i = 0; i < reportKeysToDownload.length; i++) {
        let reportKey = reportKeysToDownload[i];
        let reportData = await DownloadDashboardReportData(reportKey);
        console.log('DownloadDashboardReportData downloded:', reportKey, reportData);
        if (!reportData.success && reportData.error != null && reportData.error != '') {
          defData["success"] = false;
          defData["error"] = reportData.error;
          defData["reportKey"] = reportKey;
          resolve(defData);
        }

        reports[reportKey] = reportData.data;

        if (i == reportKeysToDownload.length - 1) {

          // console.log('all reports downloded:',reports);
          set_item('Master_MenuAppDashboard', JSON.stringify(reports));
          props.set_DashboardReports(reports);
          resolve(defData);
        }
      }
    }).catch((err) => {
      console.log("err:", err);
      defData["success"] = false;
      defData["error"] = "Error while downloading dashboard reports!";
      resolve(defData);
    });
  }


  // doownload reports 
  async function DownloadDashboardReportData(reportKey = '') {
    console.log('DownloadDashboardReportData:', reportKey);
    let loginInfo = await get_item('loginInfo');
    const loginDetails = JSON.parse(loginInfo);
    console.log("report Key:", reportKey);
    let defData = { success: false, data: {} };
    if (reportKey != null && reportKey != '') {
      setDownloadingText("Master_MenuAppDashboard - " + reportKey);
      let postdata = {
        Downloadtype: reportKey,
        Username: loginDetails.UserId,
        Param1: '',
        Param2: Platform.OS == "ios" ? "iOS" : "Android",
      };
      var url = props.baseurl + getMethodName(METHODS.DOWNLOADJSON_METHOD);
      console.log(url, postdata);
      clearProcessTimeOut();
      setProcessTimeOut();
      return await getDownloadJson1(url, postdata)
        .then(async (res) => {
          clearProcessTimeOut();
          if (res != null && typeof res == 'object' && res[reportKey] != null && res[reportKey] != '') {
            let data_arr = res[reportKey] || [];

            // get columns and colWidth
            let firstRow = data_arr.length > 0 ? data_arr[0] : {};
            console.log('firstRow', firstRow);
            let allCols = [], columnWidth = '50%';
            let i = 0;
            let keylen = Object.keys(firstRow).length;
            // get columns to display in report and store them with data
            for (let key in firstRow) {
              let obj = { 'actual_colname': key };
              let colname = key.replace(/[$$]/g, ' ').replace(/Percent/g, '%');
              obj['colname'] = colname;
              let dontShowCol = (colname == 'Srno' || colname == 'AdKPIId' || colname == 'ReportValue' || colname == 'Color');
              if (!dontShowCol) {
                allCols.push(obj);
              }

              if (i == keylen - 1) {
                console.log('allCols:', allCols);
                if (allCols.length > 0) {
                  let colLen = allCols.length;
                  columnWidth = (94 / colLen) + '%';
                }
              }
              i++;
            }

            defData["success"] = true;
            defData["data"] = { "report_data": data_arr, "report_colWidth": columnWidth, "report_cols": allCols };
            return defData;
          }
          else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            defData["success"] = true;
            return defData;
          }
          else {
            defData["error"] = res;
            return defData;
          }

        }).catch((err) => {
          notify("Please retry downloading! There is some error while downloading data");
          clearProcessTimeOut();
          props.set_startDownload({ startDownload: false });
          console.log('onDownload report error', err);
          return defData;
        })

    }
    else {
      return defData;
    }
  }

  async function onUploadComplete(resolveOnCompleteIR = () => { }) {
    // Sync all IR sessionsfor all stores at onces when all data and images fully uploaded
    // setLoaderTitle('Syncing IR Sessions Status...');
    // stop uploading and hide upload modal 
    function stopUploading() {
      clearProcessTimeOut();
      setStartUploading(false);
      props.set_startUpload({ startUpload: false });
      // check if start download is enabled the start Downloading
      setStartDafterPrevUpload(!StartDafterPrevUpload);

      // resolve uploading data method
      resolveOnCompleteIR(true);
    }

    // if not performics IR app then stop uploading and hide modal
    if (AppName != PerformicsIRAppName) {
      stopUploading();
      return;
    }

    UpdateUploadCountLocal(0); // set uploaded count in progress bar to zero as IR session upload is just started
    setTotalUpCount(0);// set Total uploaded count to 0
    setshowProgresssBar(false);
    setUploadingSubText('');
    setUploadingText('Syncing IR Sessions Status...');
    sessionsToUpload.current = [];
    sessionsReceived.current = 0;
    sessionsUploadedCount.current = 0;
    let sync_result = await SyncIRsessions(props, "2");
    let { isUploadStarted, noDataFound, AllDataUploaded, success, sessionList, sessionListWithDetails } = sync_result;

    if (!success) {
      notify('Cannot Upload Data! Something went wrong.');
      stopUploading();
    }
    else {
      if (noDataFound) {
        notify('No session to upload!');
        stopUploading();
      }
      else {
        if (!isUploadStarted && AllDataUploaded) {
          notify('All images synced! No session to upload.');
          stopUploading();
        } else if (isUploadStarted) {
          // resolve uploading data method but do not stop uploading as IR images uploads are still in process
          resolveOnCompleteIR(true);

          sessionsToUpload.current = sessionListWithDetails;
          console.log("UploadStarted", sessionsToUpload.current.length);
          UpdateUploadCountLocal(0); // set uploaded count in progress bar to zero as IR session upload is just started
          setTotalUpCount(sessionsToUpload.current.length - 1); // set Total Upload Count to IR Session Counts
          setshowProgresssBar(true);
          setUploadingSubText('Uploading IR Sessions');
          setUploadingText('Uploading IR Sessions Data...');
          //set a timeout for session uploading: if no response get from receiver for particular session
          for (let i = 0; i < sessionListWithDetails.length; i++) {
            let { TEMP_SESSION_ID } = sessionListWithDetails[i];
            setTimeout(async () => {

              let timerSessI = sessionsToUpload.current.findIndex(i => i.TEMP_SESSION_ID == TEMP_SESSION_ID);
              let timerSessObj = timerSessI >= 0 ? sessionsToUpload.current[timerSessI] : {};

              if (timerSessObj.IRStatusReceived != null && timerSessObj.IRStatusReceived === true) {
                console.log("Session is already uploaded")
              }
              else { // upload local timout message and move loading to next step after 60 sec if no response received from server
                let udata = { "message": "Session Upload Timeout", "sessionId": TEMP_SESSION_ID, "status": "local" }
                await onIRImageUpload(udata);
              }
            }, 60 * 1000);
          }
        }
      }
    }
  }


  async function onIRImageUpload(data) {
    console.log('onGlobalIRImageUpload on receive in STorelist', data);
    let { message, sessionId, status } = data;
    let snum = sessionsReceived.current + 1;
    let su_num = sessionsUploadedCount.current;
    sessionsReceived.current = snum;



    let sessionIndex = sessionsToUpload.current.findIndex(i => i.TEMP_SESSION_ID == sessionId);
    let sessionObj = sessionIndex >= 0 ? sessionsToUpload.current[sessionIndex] : {};
    console.log('onGlobalIRImageUpload on receive in sessionObj', sessionId, sessionObj);
    let TableName1 = sessionObj['TableName1'] || '';
    let TableName2 = sessionObj['TableName2'] || '';
    let StoreId = sessionObj['StoreId'] || '';
    let StoreName = sessionObj['StoreName'] || '';

    let IRCategoryName = sessionObj["IRCategoryName"] || '';
    let IRTaskName = sessionObj["IRTaskName"] || '';
    let IRPhotoType = sessionObj["IRPhotoType"] || '';
    let IRStoreCode = sessionObj["IRStoreCode"] || '';
    let ScreenName = sessionObj["ScreenName"] || '';
    let IRDetails = { IRCategoryName, IRTaskName, IRPhotoType, IRStoreCode, ScreenName }

    // if any status for the given session is recieved then we don't need to run timer and send local timout for that session 
    // so update its IRStatusReceived to true 
    sessionObj.IRStatusReceived = true;
    sessionsToUpload.current[sessionIndex] = sessionObj;

    // check if session is uploaded then upload its logs
    if (status != null && status == '200' && sessionId != null && sessionId != '') {

      let UnSessionId = await IRLogin.getDataIRSession(sessionId);
      if (UnSessionId != null && UnSessionId != '') {
        sessionsUploadedCount.current = ++su_num;

        // update session uploaded count
        UpdateUploadCountLocal(su_num);
        let isUpdated = await UpdateIRUploadStatus(sessionId, UnSessionId, TableName1, TableName2, StoreId);
        let isUploaded = await LogImageUpload(sessionId, UnSessionId, message, status, StoreId, StoreName, TableName1, TableName2, IRDetails);
        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 {
        notify("Cannot upload images for session:" + sessionId + ". Universal Id not found");
        let isUploaded = await LogImageUpload(sessionId, "", message, status, StoreId, StoreName, TableName1, TableName2, IRDetails);
        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 {
      notify((message != null && message != "" ? message + ". " : "") + "Cannot upload images for session:" + sessionId);
      let isUploaded = await LogImageUpload(sessionId, "", message, status, StoreId, StoreName, TableName1, TableName2, IRDetails);
      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);

    let popupMsg = "";
    let subTstyle = {};
    // All IR Sessions with Images Uploaded : set DataUploaded Status to U (Fully Upload)
    if (su_num == sessionsToUpload.current.length) {
      // setProcessing(false);
      // setStartUploading(false);
      popupMsg = "All IR images uploaded!";
      subTstyle = { color: 'green' };

      notify("All IR images uploaded!");
      console.log('set all uploaded true to U');
      setIRSessionPendingCount(0);
      await getIRSessionStatus();
    }
    // 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);
      popupMsg = `${su_num} out of ${sessionsToUpload.current.length} IR Sessions uploaded! Please Retry`;
      subTstyle = { color: 'red' };
      notify("Uploading IR Sessions!");
      console.log('set all uploaded true to P');
    }
    else if (su_num == 0) {
      subTstyle = { color: 'red' };
      popupMsg = `${su_num} out of ${sessionsToUpload.current.length} IR Sessions uploaded! Please Retry`;
    }

    console.log("IR Session received ", snum)
    // if last broadcast received either uploaded or not, update the processing status to false
    if (snum == sessionsToUpload.current.length) {
      setProcessing(false);
      console.log("IR Session all received ", snum)
      // ---------- stop upload on Ok click (OnOKClick) of popup message ------------
      // show ok button popup on upload success
      setshowProgresssBar(false);
      setUploadingSubText(popupMsg);
      setSubTextStyle(subTstyle);
      setShowOkButtonOnUpload(true);
      console.log('Deregister event when last received');
      IRLogin.deRegisterReceiver();
      await getIRSessionStatus();
    }
  }

  async function OnOKClick() {
    // stop uploading and hide upload modal 
    setStartUploading(false); // hide upload modal 
    setUploadingSubText(''); // then clear upload modal subtext 
    setTotalUpCount(0); // clear tortal upload count
    UpdateUploadCountLocal(0); // clear uploaded count
    setShowOkButtonOnUpload(false); // hide ok button 
    setSubTextStyle(''); // remove style of subtext in uploading modal 
    props.set_startUpload({ startUpload: false });
    // check if start download is enabled the start Downloading
    setStartDafterPrevUpload(!StartDafterPrevUpload);
  }

  async function UpdateIRUploadStatus(TempSessionId, UnSessionId, TableName1, TableName2, StoreId) {
    console.log("UpdateIRUploadStatus");
    // TableName1: IR Upload Table for KPI
    // TableName2: IR Images Table for KPI
    return new Promise((resolve, reject) => {
      if (TableName1 != null && TableName2 != null && TableName1 != '' && TableName2 != '') {
        db.transaction(async function (txn) {
          let q = `Update ${TableName1} set UN_SESSION_ID='${UnSessionId}',UPLOAD_STATUS='1',SYNC_STATUS='Synced' where  TEMP_SESSION_ID='${TempSessionId}' and STORE_ID='${StoreId}' `;//VISIT_DATE='${d2}'
          await txn.executeSql(q, [], async function (txn2, txnres) {
            console.log('Updated IR Upload Status', q);
            let q2 = `Update ${TableName2} set UN_SESSION_ID='${UnSessionId}' where  TEMP_SESSION_ID='${TempSessionId}' and STORE_ID='${StoreId}' `;//VISIT_DATE='${d2}' and
            await txn.executeSql(q2, [], async function (txn2, txnres2) {
              console.log('Updated IR Image Status', q2);
              resolve(true);
            }, function (txnE, txnerr) { console.log(txnerr); resolve(false); },);

          }, function (txnE, txnerr) { console.log(txnerr); resolve(false); },);
        });
      }
      else {
        resolve(false);
      }
    }).catch((Err) => {
      console.log('Error in UpdateIRUploadStatus:', Err);
      return false;
    })
  }

  async function LogImageUpload(TempSessionId, UnSessionId, message, status, StoreId, StoreName, TableName1, TableName2, IRDetails = {}) {
    let { IRCategoryName, IRTaskName, IRPhotoType, IRStoreCode, ScreenName } = IRDetails
    const url = props.baseurl + getMethodName(METHODS.UPLOADJSON_METHOD);
    const nowTime = moment().format('HH:mm:ss');
    let ImageCount = await getImageCount(TempSessionId, TableName2);
    ////Replaced special charecter and white space
    let storeTittle = StoreName.replace(`@!%&`, '').replace(' ', '-');
    console.log("storeTittle:", storeTittle, StoreName);
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    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'] = IRStoreCode;
    obj['TaskName'] = IRTaskName;
    obj['CategoryName'] = IRCategoryName;
    obj['PhotoType'] = IRPhotoType;
    obj['KPIType'] = "";
    obj['ScreenName'] = 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 getImageCount(TempSessionId, TableName2) {
    console.log('getImageCount');
    return new Promise((resolve, reject) => {
      if (TableName2 != null && TableName2 != '') {
        db.transaction(async function (txn) {
          let q = `select DISTINCT TEMP_SESSION_ID,count(IMAGE1) as ImageCount from ${TableName2}  where TEMP_SESSION_ID='${TempSessionId}'  group by TEMP_SESSION_ID `;//VISIT_DATE='${d2}' and 
          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); },);
        });
      }
      else {
        resolve(false);
      }
    }).catch((Err) => {
      console.log('Error in getImageCount:', Err);
      return 0;
    })



  }



  async function uploadAllDistributors(d2, loc, AllStores, previousDayUpload = false) {
    console.log('Distributors to upload:', AllStores.length);
    if (AllStores.length > 0) {
      function onStoreUploadLast(index, shouldret = true, res = true) {
        // check if last index of store then do the common thing 
        if (index == AllStores.length - 1) {
          setStartUploading(false);
        }
      }

      return new Promise(async (resolve, reject) => {
        for (let i = 0; i < AllStores.length; i++) {
          let data = AllStores[i];
          const index = i;
          let { StoreId, StoreName, EmpId, MID, UploadStatus, Status, VisitDate, REASON_ID, JCP_TYPE } = data;
          // get all checkout ids data
          // setLoaderTitle(ST.UploadingDatafor+' '+StoreName+'...');

          let MenuList = await getDBMenuList(data);
          let allKPIs = MenuList;

          let totalUpC = MenuList.length - 1; // keep 1 less to actual count as DownloadDataModal shows it as provided_value+1
          console.log('UploadStatus before Start Uploading Data :', StoreId, UploadStatus);
          // if(UploadStatus=='U'){ UploadStatus='C';}
          setTotalUpCount(totalUpC);
          setshowProgresssBar(false);
          setUploadingSubText("Uploading data for distributor:" + StoreId);

          if (UploadStatus == 'C') {
            let isUploaded_P = await uploadDBStatus(props, data, 'P', JCP_TYPE, loc);
            if (isUploaded_P == true) {
              setTotalUpCount(totalUpC);
              setshowProgresssBar(true);
              setUploadingText(ST.UploadingData + '...');
              await uploadAfter_P_status(index, AllStores, data, MenuList, allKPIs, JCP_TYPE, loc, onStoreUploadLast, previousDayUpload)
            }
            else {
              notify(ST.Erroroccurwhileuploadingdatafor + ' ' + StoreName, 'LONG');
              if (index == AllStores.length - 1) {
                // setProcessing(false);
                setStartUploading(false);
              }
            }
          }
          else if (UploadStatus == 'D') {
            setTotalUpCount(totalUpC);
            setshowProgresssBar(true);
            setUploadingSubText("Uploading data for distributor:" + StoreId);
            //  this never be called if there is no KPI
            let allFilesToUpload = await uploadAll_DBData(props, data, allKPIs, props.UserId, JCP_TYPE, false, loc, UpdateUploadCountLocal);
            console.log('allFilesToUpload.length:', allFilesToUpload.length);
            if (allFilesToUpload.length > 0) {
              await UploadDataWithImages(index, AllStores, data, MenuList, allKPIs, JCP_TYPE, allFilesToUpload, loc, onStoreUploadLast, previousDayUpload);
            }
            else {
              let isUploaded_U = await uploadDBStatus(props, data, 'U', JCP_TYPE, loc);
              notify(ST.Alldatauploadedfor + ' ' + StoreName, 'SHORT');
              if (index == AllStores.length - 1) {
                // setProcessing(false);
                setStartUploading(false);
              }
            }

          }
          else if (UploadStatus == 'P') {
            setTotalUpCount(totalUpC);
            setshowProgresssBar(true);
            setUploadingText(ST.UploadingData + '...');
            await uploadAfter_P_status(index, AllStores, data, MenuList, allKPIs, JCP_TYPE, loc, onStoreUploadLast, previousDayUpload);
          }
          else if (UploadStatus == 'L') {
            setshowProgresssBar(false);
            setUploadingText(ST.UploadingData + '...');
            let isAllUploaded_S = await uploadDBStatus(props, data, 'U', JCP_TYPE, loc);
            if (isAllUploaded_S == true) {
              notify(ST.Alldatauploadedfor + ' ' + StoreName, 'SHORT');
              if (index == AllStores.length - 1) {
                // setProcessing(false);
                setStartUploading(false);
              }
            }
            else {
              if (index == AllStores.length - 1) {
                // setProcessing(false);
                setStartUploading(false);
                notify(ST.Erroroccurwhileuploadingdatafor, 'LONG');
              }
            }
          }

          if (index == 0) {
            props.set_startUpload({ startUpload: false });
          }
          // resolve true for last element after all uploaded
          if (index == AllStores.length - 1) {
            resolve(true);
          }
        }
      }).then((val) => {
        console.log('on all distributors uploaded:', val);
        return true;
      }).catch((err) => {
        console.log('error', err);
        return false;
      });
    }
    else {
      return true;
    }
  }

  async function uploadAllHomeLocations(d2, loc, AllStores, previousDayUpload = false) {
    console.log('Distributors to upload:', AllStores.length);
    if (AllStores.length > 0) {
      function onStoreUploadLast(index, shouldret = true, res = true) {
        // check if last index of store then do the common thing 
        if (index == AllStores.length - 1) {
          setStartUploading(false);
        }
      }

      return new Promise(async (resolve, reject) => {
        for (let i = 0; i < AllStores.length; i++) {
          let data = AllStores[i];
          const index = i;
          let { StoreId, StoreName, EmpId, MID, UploadStatus, Status, VisitDate, REASON_ID, JCP_TYPE } = data;
          // get all checkout ids data
          // setLoaderTitle(ST.UploadingDatafor+' '+StoreName+'...');
          let MenuList = await getDBMenuList(data);
          let allKPIs = MenuList;
          let totalUpC = MenuList.length - 1; // keep 1 less to actual count as DownloadDataModal shows it as provided_value+1
          console.log('UploadStatus before Start Uploading Data :', StoreId, UploadStatus);
          // if(UploadStatus=='U'){ UploadStatus='C';}
          setTotalUpCount(totalUpC);
          setshowProgresssBar(false);
          setUploadingSubText("Uploading data for Home Location");
          // let isUploaded_P=await uploadDBStatus(props,data,'P',JCP_TYPE,loc);
          let { LATITUDE, LONGITUDE } = data;
          let obj = {
            "Latitude": LATITUDE,
            "Longitude": LONGITUDE,
            "UserId": props.UserId,
          };
          console.log("obj------", obj, AllStores)
          let postData = {
            "MID": 0,
            "Keys": "User_Home_Location",
            "JsonData": JSON.stringify(obj),
            "UserId": props.UserId,
          };

          const url = props.baseurl + getMethodName(METHODS.UPLOADJSON_METHOD);
          console.log(url, postData);
          let isUploaded_P = await UploadData2(url, postData)
          console.log("isUploaded_P--", isUploaded_P, isUploaded_P?.UploadJsonResult)
          if (isUploaded_P?.UploadJsonResult == "Success") {
            setTotalUpCount(totalUpC);
            setshowProgresssBar(true);
            setUploadingText(ST.UploadingData + '...');
            await uploadHomeLocationStatus(index, onStoreUploadLast, previousDayUpload)
            notify('Home Location is uploaded successfuly', 'LONG');
          }
          else {
            notify(ST.Erroroccurwhileuploadingdatafor + ' ' + StoreName, 'LONG');
            if (index == AllStores.length - 1) {
              // setProcessing(false);
              setStartUploading(false);
            }
          }
          if (index == 0) {
            props.set_startUpload({ startUpload: false });
          }
          // resolve true for last element after all uploaded
          if (index == AllStores.length - 1) {
            resolve(true);
          }
        }
      }).then((val) => {
        console.log('on all distributors uploaded:', val);
        return true;
      }).catch((err) => {
        console.log('error', err);
        return false;
      });
    }
    else {
      return true;
    }
  }


  // add store info upload
  async function uploadAllAddStoreInfo(d2, AllAddStoreInfo) {
    console.log('uploadAllAddStoreInfo called');
    if (AllAddStoreInfo.length > 0) {
      setTotalUpCount(AllAddStoreInfo.length - 1);
      setUploadedCount(0);
      setshowProgresssBar(true);
      return new Promise(async (resolve, reject) => {
        let uploadCount = 0,
          isAllUploaded = true, UploadData = [];
        for (let i = 0; i < AllAddStoreInfo.length; i++) {
          let data = AllAddStoreInfo[i];
          const index = i;
          let { DISTRIBUTOR_NAME, DISTRIBUTOR_ID, STORE_NAME, STORE_ADDRESS, CITY_NAME, CITY_ID, STORETYPE_NAME, STORETYPE_ID, IMAGE, IMAGEPATH, LAT, LNG, STATUS } = data;
          let UploadDataObj = { DistributorName: DISTRIBUTOR_NAME, DistributorId: DISTRIBUTOR_ID, StoreName: STORE_NAME, StoreAddress: STORE_ADDRESS, CityName: CITY_NAME, CityId: CITY_ID, StoreType: STORETYPE_NAME, StoreTypeId: STORETYPE_ID, ImageName: IMAGE, Longitude: LAT, Latitude: LNG, Status: STATUS }
          // setUploadingSubText('`${ST.UploadingdataforStoreIdProgramId}`(' +StoreId +',' +ProgramDefinitionId +')',);
          setUploadingSubText(`Uploading data for add store Info`);
          UploadData.push(UploadDataObj)
        }
        console.log("UploadAddStoreInfoData------", UploadData)
        let isuploaded = await UploadAddStoreInfoData(props, UploadData);
        if (!isuploaded) {
          isAllUploaded = false;
        }
        uploadCount++;
        setUploadedCount(uploadCount - 1);
        props.set_startUpload({ startUpload: false });
        // if (index == 0) {
        //   props.set_startUpload({startUpload: false});
        // }
        // resolve true for last element after all uploaded
        if (uploadCount == AllAddStoreInfo.length) {
          resolve(isAllUploaded);
        }
      })
        .then(val => {
          console.log('on all distributors uploaded:', val);
          return true;
        })
        .catch(err => {
          console.log('error', err);
          return false;
        });
    } else {
      return true;
    }
  }


  async function uploadAllContracts(d2, AllContracts) {
    console.log("uploadAllContracts called")
    if (AllContracts.length > 0) {
      setTotalUpCount(AllContracts.length - 1);
      setUploadedCount(0);
      setshowProgresssBar(true);
      return new Promise(async (resolve, reject) => {
        let uploadCount = 0, isAllUploaded = true;
        for (let i = 0; i < AllContracts.length; i++) {
          let data = AllContracts[i];
          const index = i;
          let { StoreId, ProgramDefinitionId, ProgramId, IsContractSigned, ReasonId, Reason } = data;
          setUploadingSubText("Uploading data for (StoreId,ProgramId):(" + StoreId + "," + ProgramDefinitionId + ")");

          let ProgramQtns = await getContractQtns(d2, data);
          console.log("getContractQtns", ProgramQtns)
          let UploadData = {}
          UploadData['UserId'] = props.UserId;
          UploadData['Store_Id'] = StoreId;
          UploadData['ProgramId'] = ProgramId;
          UploadData['IsContractSigned'] = IsContractSigned;
          UploadData['ReasonId'] = ReasonId != '' ? ReasonId : '0';
          UploadData['Reason'] = Reason;
          UploadData['ContractQtns'] = ProgramQtns != null ? ProgramQtns : [];
          UploadData['VisitDate'] = d2;

          let isuploaded = await uploadContractData(props, UploadData, data);
          if (!isuploaded) {
            isAllUploaded = false;
          }
          uploadCount++;
          setUploadedCount(uploadCount - 1);
          if (index == 0) {
            props.set_startUpload({ startUpload: false });
          }
          // resolve true for last element after all uploaded
          if (uploadCount == AllContracts.length) {
            resolve(isAllUploaded);
          }
        }
      }).then((val) => {
        console.log('on all distributors uploaded:', val);
        return true;
      }).catch((err) => {
        console.log('error', err);
        return false;
      });
    }
    else {
      return true;
    }
  }

  async function uploadAllContractFiles() {
    let allFilesToUpload = getAllFileForAFolder(ContractFormImagePath, "ContractFormImages");
    if (allFilesToUpload.length > 0) {
      setUploadingText("Uploading Contract Images/Files...")
      setTotalUpCount(allFilesToUpload.length - 1);
      setUploadedCount(0);
      let allImageUploaded = await uploadContractFormFiles(allFilesToUpload, UpdateUploadCountLocal, props);
      return allImageUploaded;
    }
  }

  async function uploadAllAddStoreInfoFiles() {
    let allFilesToUpload = await getAllFileForAFolder(AddStoreImagePath, "AddNewStoreImages");
    console.log("ImgFiles in--------", allFilesToUpload)
    if (allFilesToUpload.length > 0) {
      setUploadingText('Upload Add Store Info File');
      setTotalUpCount(allFilesToUpload.length - 1);
      setUploadedCount(0);
      console.log("ImgFiles in--------", allFilesToUpload.length)
      let allImageUploaded = await uploadContractFormFiles(
        allFilesToUpload,
        UpdateUploadCountLocal,
        props
      );
      return allImageUploaded;
    }
  }



  async function getContractQtns(d2, data) {
    console.log("getContractQtns called", data)
    let allQtnsData = [];
    let { StoreId, ProgramId, ProgramDefinitionId } = data;
    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        // get inserted data for contract form 
        let selectlist = ` DISTINCT T.CategoryId,T.Category,T.Question as Question,T.QuestionId as QuestionId,T.QuestionType as QuestionType,T.ShowContractNotSigned,T.QEnable,T.LengthValidation as LengthValidation,T.QuestionImageAllow,T.DateRange as DateRange,T.MaxLength as MaxLength,T.MinLength as MinLength,T.OTP as OTP,T1.ANSWER As Answer, T1.ANSWER_ID as AnswerId,T1.IMAGE_ALLOW1 as ImageAllow1,T1.IMAGE1 as Image1,T1.IMAGE_ALLOW2 as ImageAllow2,T1.IMAGE2 as Image2,T1.MULTI_OPTIONS_IDS as MultiAnswerId `;
        let join = ` INNER JOIN ${AppTables.CONTRACT_FORM_DATA} T1 on T.CategoryId=T1.CATEGORY_ID and T.QuestionId=T1.QUESTION_ID`;
        let q2 = `Select ${selectlist} FROM Master_ContractFormQuestion T ${join} WHERE T1.STORE_ID='${StoreId}' AND T1.PROGRAM_ID=${ProgramId} AND T1.PROGRAM_DEFINITION_ID=${ProgramDefinitionId}  `;
        q2 += ` ORDER BY T.CategorySequence,T.QuestionSequence `;
        console.log("getContractQtns q2:", q2)
        await txn.executeSql(q2, [], async function (txn2, txnres2) {
          console.log("qtns count:", txnres2.rows.length)
          if (txnres2.rows.length > 0) {
            for (var i = 0; i < txnres2.rows.length; i++) {
              let data = txnres2.rows.item(i);

              let { CategoryId, QuestionId, QuestionType, Answer, AnswerId, MultiAnswerId, Image1, Image2 } = data;
              let obj = {};
              obj['UserId'] = props.UserId;
              obj['Store_Id'] = StoreId;
              obj['ProgramId'] = ProgramId;
              obj['CategoryId'] = CategoryId;
              obj['QuestionId'] = QuestionId;
              obj['QuestionType'] = QuestionType;
              obj['Answer'] = Answer;
              obj['AnswerId'] = AnswerId;
              obj['MultiAnswerId'] = MultiAnswerId != null && MultiAnswerId != 'undefined' ? MultiAnswerId : '';
              obj['AnswerImage1'] = (Image1 || '');
              obj['AnswerImage2'] = (Image2 || '');
              obj['VisitDate'] = d2;

              allQtnsData.push(obj);

              if (i == txnres2.rows.length - 1) {
                resolve(allQtnsData);
              }
            }

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

      });
    }).then((val) => {
      return val;
    })
      .catch((err) => {
        console.log(err);
        return allForms;
      })
  }


  async function getDistributors(d2, previousDayUpload = false) {
    let alldist = [];
    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {

        let stored_Select = `t1.DMID as MID,t1.EmpId,t1.DistributorId as StoreId,t1.DistributorName as StoreName,t1.DistributorCode as StoreCode,t1.Latitude,t1.Longitude,t1.InTime,t1.OutTime,t1.UploadStatus,t1.GeoTag`;

        let join = `INNER JOIN ${AppTables.DISTRIBUTOR_CHECKIN} t2 on t2.DISTRIBUTOR_ID=t1.DistributorId `;
        let q = `Select ${stored_Select},t2.REASON_ID,'Master_Distributor' as JCP_TYPE from Master_Distributor t1 ${join} where  t1.UploadStatus in ('C','P','D','L')`;
        console.log("q:", q);
        if (!previousDayUpload) {
          q += ` and t2.VISIT_DATE='${d2}' `;
        }
        await txn.executeSql(q, [], async function (txn2, txnres2) {

          if (txnres2.rows.length > 0) {
            for (var i = 0; i < txnres2.rows.length; i++) {
              let data = txnres2.rows.item(i);
              alldist.push(data);
            }
            resolve(alldist);
          }
          else {
            resolve(alldist);
          }
        }, function (txnE, txnerr) { console.log(txnerr); resolve(alldist) },);

      });
    }).then((val) => {
      return val;
    }).catch((err) => {
      console.log(err);
      return alldist;
    })
  }

  async function getDBMenuList(storeData1) {
    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        let q = Q_DBMenuList(storeData1);
        await txn.executeSql(q, [], async function (txn2, txnres) {
          if (txnres.rows.length > 0) {
            let arr = [];//txnres.rows.raw();   
            // resolve(arr);      
            for (var i = 0; i < txnres.rows.length; i++) {
              let data = txnres.rows.item(i);
              arr.push(data);
              if (i == (txnres.rows.length - 1)) {
                resolve(arr);
              }
            }
          }
          else {
            resolve([])
          }
        }, function (txnE, txnerr) { console.log(txnerr); resolve([]); },);
      });
    }).then((val) => {
      return val;
    }).catch((err) => {
      console.log('')
      return []
    })
  }

  async function uploadAfter_P_status(index, AllStores, data, MenuList, allKPIs, JCP_TYPE, loc, onStoreUploadLast = () => { }, previousDayUpload = false) {
    let { StoreName } = data;
    if (MenuList.length > 0) {
      // Upload data with Images
      let allFilesToUpload = 0;
      if (JCP_TYPE == "Master_Distributor") {
        allFilesToUpload = await uploadAll_DBData(props, data, allKPIs, props.UserId, JCP_TYPE, false, loc, UpdateUploadCountLocal);
      }
      else {
        allFilesToUpload = await uploadAllData(props, data, allKPIs, props.UserId, JCP_TYPE, true, UpdateUploadCountLocal, previousDayUpload);
      }
      UploadDataWithImages(index, AllStores, data, MenuList, allKPIs, JCP_TYPE, allFilesToUpload, loc, onStoreUploadLast, previousDayUpload);

    }
    else {
      // If There is no menu exists or defined for the distributor or store
      //  Upload statua u if no data exists
      let isAllUploaded_S = false;
      if (JCP_TYPE == "Master_Distributor") {
        // previousDayUpload not required to uploadDBStatus as Master_Distributor does not have visit date 
        isAllUploaded_S = await uploadDBStatus(props, data, 'U', JCP_TYPE, loc);
      } else {
        isAllUploaded_S = await uploadStoreStatus(props, data, 'U', JCP_TYPE, previousDayUpload);
      }

      if (isAllUploaded_S == true) {
        notify(ST.Alldatauploadedfor + ' ' + StoreName, 'SHORT');
        // this is not required in case of distributor as store list upload handling the last event
        if (JCP_TYPE != "Master_Distributor") {
          onStoreUploadLast(index); // check if last then end uploading
        }
      }
      else {
        notify(ST.Erroroccurwhileuploadingdatafor + ' ' + StoreName, 'SHORT');
        // this is not required in case of distributor as store list upload handling the last event
        if (JCP_TYPE != "Master_Distributor") {
          onStoreUploadLast(index); // check if last then end uploading
        }
      }
    }
  }

  async function uploadHomeLocationStatus(index, onStoreUploadLast = () => { }, previousDayUpload = false) {
    await db.transaction(async function (txn) {
      let update_q1 = `UPDATE  ${AppTables.HOME_LOCATION} SET STATUS='1'  `;
      let update_q = `UPDATE  Master_UserHomeLocation SET LocationTaken='1' `;
      await txn.executeSql(update_q1, [], async function (txn2, txnres3) {
        console.log('Update Home location done');
      }, function (txnE, txnerr) { },);
      await txn.executeSql(update_q, [], async function (txn2, txnres3) {
        console.log('Update Home location done');
      }, function (txnE, txnerr) { },);
    });
  }

  async function UploadDataWithImages(index, AllStores, data, MenuList, allKPIs, JCP_TYPE, allFilesToUpload, loc, onStoreUploadLast = () => { }, previousDayUpload = false) {
    let { StoreName } = data;
    if (allFilesToUpload.length > 0) {
      // setLoaderTitle(ST.UploadingImages+'...');
      // keep 1 less to actual count as DownloadDataModal shows it as provided_value+1
      setUploadedCount(0);
      setTotalUpCount(allFilesToUpload.length - 1);
      setshowProgresssBar(true);
      setUploadingText(ST.UploadingImages + '...');
      let isAllUploaded = await uploadAllImages(props, data, allFilesToUpload, JCP_TYPE, loc, UpdateUploadCountLocal, previousDayUpload);
      if (isAllUploaded == true) {
        console.log('JCP_TYPE in images upload', JCP_TYPE);
        notify(ST.Alldataandimagesuploadedfor + ' ' + StoreName, 'SHORT');
        // this is not required in case of distributor as store list upload handling the last event
        if (JCP_TYPE != "Master_Distributor") {
          onStoreUploadLast(index); // check if last then end uploading
        }
      } else {
        console.log('JCP_TYPE in images upload2', JCP_TYPE);
        notify(ST.Cannotuploadimagesfor + ' ' + StoreName, 'SHORT');
        // this is not required in case of distributor as store list upload handling the last event
        if (JCP_TYPE != "Master_Distributor") {
          onStoreUploadLast(index); // check if last then end uploading
        }

      }
    }
    else {
      let isupdatedU = false;
      if (JCP_TYPE == "Master_Distributor") {
        isupdatedU = await uploadDBStatus(props, data, 'U', JCP_TYPE, loc);
      }
      else {
        isupdatedU = await uploadStoreStatus(props, data, 'U', JCP_TYPE, previousDayUpload);
      }

      console.log('on no files found to upload , isupdated::', isupdatedU);
      if (isupdatedU) {
        notify(ST.Alldatauploadedfor + ' ' + StoreName, 'SHORT');
        // this is not required in case of distributor as store list upload handling the last event
        if (JCP_TYPE != "Master_Distributor") {
          onStoreUploadLast(index); // check if last then end uploading
        }
      }
      else {
        // this is not required in case of distributor as store list upload handling the last event
        if (JCP_TYPE != "Master_Distributor") {
          onStoreUploadLast(index); // check if last then end uploading
        }
      }

    }
  }


  async function getPJPStoresData(tbname, Stores = [], d2, previousDayUpload = false) {
    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        let join = `INNER JOIN ${AppTables.COVERAGE_DATA} t2 on t2.STORE_ID=t1.StoreId and t2.JCP_TYPE='${tbname}' `;
        let q = `Select t1.*,t2.REASON_ID,t2.JCP_TYPE from ${tbname} t1 ${join} where t1.UploadStatus in ('C','P','D','L')`;
        if (!previousDayUpload) {
          q += ` and t1.VisitDate='${d2}' `;
        }
        console.log("test----------", q)
        await txn.executeSql(q, [], async function (txn2, txnres2) {
          if (txnres2.rows.length > 0) {
            for (var i = 0; i < txnres2.rows.length; i++) {
              let data = txnres2.rows.item(i);
              Stores.push(data);
            }
            resolve(Stores);
          }
          else {
            resolve(Stores);
          }
        }, function (txnE, txnerr) { console.log(txnerr); resolve(Stores) },);

      });
    }).then((val) => {
      return val;
    })
      .catch((err) => {
        console.log(err);
        return Stores;
      })
  }

  async function getVisitorLogin(d2, previousDayUpload = false) {
    let allVisitors = [];
    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        let q = `Select * from ${AppTables.VISITOR_LOGIN} where  OUT_TIME!='' and UPLOADSTATUS!='U' `;
        if (!previousDayUpload) {
          q += ` and VISIT_DATE='${d2}' `;
        }
        await txn.executeSql(q, [], async function (txn2, txnres2) {
          if (txnres2.rows.length > 0) {
            for (var i = 0; i < txnres2.rows.length; i++) {
              let data = txnres2.rows.item(i);
              allVisitors.push(data);
            }
            resolve(allVisitors);
          }
          else {
            resolve(allVisitors);
          }
        }, function (txnE, txnerr) { console.log(txnerr); resolve(allVisitors) },);

      });
    }).then((val) => {
      return val;
    })
      .catch((err) => {
        console.log(err);
        return Stores;
      })
  }

  async function getContractForms(d2) {
    let allForms = [];
    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        let join = ` Inner Join Mapping_ContractForm mp on mp.ProgramId=cf.PROGRAM_ID and mp.StoreId=cf.STORE_ID and mp.ProgramDefinitionId=cf.PROGRAM_DEFINITION_ID `
        let q = `Select mp.*,cf.IS_CONTRACT_SIGNED as IsContractSigned,cf.REASON_ID as ReasonId,cf.REASON as Reason from ${AppTables.CONTRACT_FORM} cf ${join} where mp.ContractFormStatus='0' `;
        await txn.executeSql(q, [], async function (txn2, txnres2) {
          console.log("Allcontracts:", txnres2.rows.length);
          if (txnres2.rows.length > 0) {
            for (var i = 0; i < txnres2.rows.length; i++) {
              let data = txnres2.rows.item(i);
              allForms.push(data);
            }
            resolve(allForms);
          }
          else {
            resolve(allForms);
          }
        }, function (txnE, txnerr) { console.log(txnerr); resolve(allForms) },);

      });
    }).then((val) => {
      return val;
    })
      .catch((err) => {
        console.log(err);
        return allForms;
      })
  }

  async function getAddStoreInfoForms(d2) {
    let allForms = [];
    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        let q = `SELECT * from ${AppTables.ADD_STORE_INFO} WHERE VISIT_DATE='${d2}' AND STATUS='I'`;
        await txn.executeSql(
          q,
          [],
          async function (txn2, txnres2) {
            console.log('All AddStoreInfo:', txnres2.rows.length);
            if (txnres2.rows.length > 0) {
              for (var i = 0; i < txnres2.rows.length; i++) {
                let data = txnres2.rows.item(i);
                allForms.push(data);
              }
              resolve(allForms);
            } else {
              resolve(allForms);
            }
          },
          function (txnE, txnerr) {
            console.log(txnerr);
            resolve(allForms);
          },
        );
      });
    })
      .then(val => {
        return val;
      })
      .catch(err => {
        console.log(err);
        return allForms;
      });
  }

  async function getHomeLocation(d2) {
    let allForms = [];
    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        let q = `SELECT * from ${AppTables.HOME_LOCATION} WHERE VISIT_DATE='${d2}' AND STATUS='I'`;
        await txn.executeSql(
          q,
          [],
          async function (txn2, txnres2) {
            console.log('All AddStoreInfo:', txnres2.rows.length);
            if (txnres2.rows.length > 0) {
              for (var i = 0; i < txnres2.rows.length; i++) {
                let data = txnres2.rows.item(i);
                allForms.push(data);
              }
              resolve(allForms);
            } else {
              resolve(allForms);
            }
          },
          function (txnE, txnerr) {
            console.log(txnerr);
            resolve(allForms);
          },
        );
      });
    })
      .then(val => {
        return val;
      })
      .catch(err => {
        console.log(err);
        return allForms;
      });
  }

  async function getMenuDataTable() {
    let allVisitors = [];
    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        let q = `Select * from Master_MenuAppDashboard `;
        await txn.executeSql(q, [], async function (txn2, txnres2) {
          if (txnres2.rows.length > 0) {
            for (var i = 0; i < txnres2.rows.length; i++) {
              let data = txnres2.rows.item(i);
              allVisitors.push(data);
            }
            resolve(allVisitors);
          }
          else {
            resolve(allVisitors);
          }
        }, function (txnE, txnerr) { console.log(txnerr); resolve(allVisitors) },);

      });
    }).then((val) => {
      return val;
    })
      .catch((err) => {
        console.log(err);
        return Stores;
      })
  }

  async function getMenuAppData(storeData1, menu1) {
    try {
      let loginInfo = await get_item('loginInfo');
      const loginDetails = JSON.parse(loginInfo);
      let AllDashboardData = await getMenuDataTable();
      let dashDataList = []
      Promise.all(AllDashboardData.map(async (downloadKeyObj) => {
        let keyname = downloadKeyObj['DownloadKey']
        let dashboardItem = downloadKeyObj;
        let allReportData = await DownloadReport(keyname, loginDetails);
        // dashDataList
        dashboardItem["list"] = allReportData
        return dashboardItem
      })).then(function (results) {
        console.log("results------", results)
      })
      let allReportData = await DownloadReport();
      console.log('allReportData', allReportData);
      if (allReportData.length > 0) {
        let data = allReportData[0];
        console.log('data dynamicdata-----', data);
        let ShowField = JSON.parse(data.ShowField)
        let ColorField = JSON.parse(data.ColorField)
        let arrCol = []
        if (ShowField.length > 0) {

          for (var i = 0; i < ShowField.length; i++) {
            let data1 = ShowField[i];

            if (data1.Show == "Y") {
              let obj = { FieldName: data1.FieldName }
              let colorobj = ColorField.find(i => i.FieldName == data1.FieldName);
              if (colorobj !== undefined && colorobj != "") {
                obj["Color"] = colorobj.Color
              }
              console.log("ITesm,--", obj)
              arrCol.push(obj);
            }

            if (i == ShowField.length - 1) {
              let colLen = arrCol.length;
              let width = 97 / colLen;
              setColWidth(width + '%');
              setcols(arrCol);
              console.log('reportData:', arrCol);
              // setReportData(arr);

            }
          }
        }

        let filterData = allReportData.filter((item) => item.StoreId == storeData1.StoreId);
        setReportData(filterData);
        // setProcessing(false);
      }

    } catch (err) {
      // setProcessing(false);
      console.log(err);
    }
  }

  async function DownloadReport(keyname, loginDetails) {
    console.log("keyname---", keyname)
    const url = props.baseurl + getMethodName(METHODS.DOWNLOADJSON_METHOD);
    let data = {
      Downloadtype: keyname,
      Username: loginDetails.UserId,
      Param1: '',
      Param2: Platform.OS == "ios" ? "iOS" : "Android",
    };

    console.log(url, data);
    return await getDownloadJson1(url, data)
      .then(async (res) => {
        if (res[keyname]) {
          let data_arr = res[keyname] || [];
          console.log("data_arr------", data_arr)
          return data_arr;
        }
        else {
          return [];
        }
      })
      .catch((err) => {
        console.log('onPage Team error', err);
        return [];
      });
  }


  const handleBannerNavigation = (item, props) => {
    const beforeQuestionMark =
      item?.NoticeLink_FullPage?.split("?")[0] ?? "";
    console.log("banner_item2", item);
    if (item?.FullPageTarget === "deeplink") {
      if (beforeQuestionMark === "reports") {
        props.navigation.navigate('ReportsMenu');
      } else if (
        (beforeQuestionMark === "gyancast" || beforeQuestionMark === "gyancasts") &&
        (props.Gyancast === 1 || props.Gyancast)
      ) {
        props.navigation.navigate('Gyancasts', { Popup: true });
      } else if (beforeQuestionMark === "gyanbuddy" && props.Chatbot) {
        const hours = new Date().getHours();
        const isWithinTime = hours >= 8 && hours < 20;
        if (isWithinTime) {
          props.navigation.navigate('ChatScreen');
        } else {
          notify("⏰ Gyan Buddy is available between 8:00 AM and 8:00 PM only.");
        }
      } else if (beforeQuestionMark === "training") {
        props.navigation.navigate('TrainingMenu');
      }
    } else if (item?.FullPageTarget === "html-webbrowser") {
      openWebBrowser(item?.NoticeLink_FullPage);
    } else if (item?.FullPageTarget === "frame") {
      NB_RetailDay();
    } else if (item?.FullPageTarget === "contact") {
      createContact(beforeQuestionMark);
    } else {
      props.navigation.navigate('Bannerdetail', { imagedesc: item });
    }
  };

  function _renderTabularReport(item) {
    let report_key = item.DownloadKey;
    let reportContentObj = props.AppDashboardReports != null && typeof props.AppDashboardReports == 'object' && props.AppDashboardReports[report_key] != null && props.AppDashboardReports[report_key] != '' ? props.AppDashboardReports[report_key] : {};
    let report_data = reportContentObj['report_data'] != null ? reportContentObj['report_data'] : [];
    let report_colWidth = reportContentObj['report_colWidth'] != null ? reportContentObj['report_colWidth'] : '50%';
    let report_cols = reportContentObj['report_cols'] != null ? reportContentObj['report_cols'] : [];
    return (
      <View style={customStyle.DashBTbl_ReportWrap} >
        {/* render No data */}
        {report_data.length <= 0 && <View style={customStyle.DashBTbl_NoDataCon}><Text style={customStyle.DashBTbl_NoDataText}>No Data</Text></View>}
        {report_data.length > 0 && <ScrollView horizontal={true} style={{ width: '100%' }} contentContainerStyle={{}}>
          {/* render columns */}
          <View>
            {/* render header */}
            <View style={customStyle.DashBTbl_ReportHdr}>
              {report_cols.map((column, index) => {
                return (
                  <View style={[customStyle.DashBTbl_ReportHdrCol, customStyle.DashBTbl_ReportColW]}>
                    <Text style={customStyle.DashBTbl_ReportHdrColTxt}>{column.colname}</Text>
                  </View>
                )
              })}
            </View>
            {/* render content */}
            <View style={[customStyle.DashBTblBody]}>
              {report_data.map((row, row_index) => {

                return (
                  <TouchableOpacity disabled={item.DrillDown ? false : true} style={[customStyle.DashBTbl_Item, (row_index == report_data.length - 1 ? {} : customStyle.DashBTbl_ItemB)]} onPress={() => { props.navigation.navigate("DashboardReportDetail", { "ReportData": item, "AdKPIId": row["AdKPIId"] }) }}>
                    {report_cols.map((column, index) => {
                      let colValue = row[column.actual_colname] != null ? row[column.actual_colname] : '';

                      let color_obj = get_rowColSettings(colValue, column.actual_colname, row);

                      let cust_style = {}, bg_style = {};
                      if (color_obj.color != null && color_obj.color != '') {
                        bg_style["backgroundColor"] = color_obj.color;
                        cust_style["color"] = '#fff'
                      }
                      if (color_obj.fontsize != null && color_obj.fontsize != '') {
                        cust_style["fontSize"] = color_obj.fontsize
                      }
                      if (color_obj.bold == 1) {
                        cust_style["fontWeight"] = "600"
                      }

                      return (
                        <View style={[customStyle.DashBTbl_ItemCol, customStyle.DashBTbl_ReportColW, bg_style]}>
                          <Text style={[customStyle.DashBTbl_ItemColText, cust_style]}>{colValue}</Text>
                        </View>
                      )
                    })}
                  </TouchableOpacity>
                )
              })}
            </View>
          </View>

        </ScrollView>}
      </View>
    )
  }


  function _renderCardReport(item) {
    let report_key = item.DownloadKey;
    let reportContentObj = props.AppDashboardReports != null && typeof props.AppDashboardReports == 'object' && props.AppDashboardReports[report_key] != null && props.AppDashboardReports[report_key] != '' ? props.AppDashboardReports[report_key] : {};

    // {"report_data":data_arr,"report_colWidth":columnWidth,"report_cols":allCols}
    let report_data = reportContentObj['report_data'] != null ? reportContentObj['report_data'] : [];
    let report_colWidth = reportContentObj['report_colWidth'] != null ? reportContentObj['report_colWidth'] : '50%';
    let report_cols = reportContentObj['report_cols'] != null ? reportContentObj['report_cols'] : [];
    // console.log("report_cols:",report_cols);

    return (
      <View style={customStyle.DashBTbl_ReportWrap} >
        {/* render No data */}
        {report_data.length <= 0 && <View style={customStyle.DashBTbl_NoDataCon}><Text style={customStyle.DashBTbl_NoDataText}>No Data</Text></View>}
        {report_data.length > 0 && <ScrollView horizontal={true} style={{ width: '100%' }} contentContainerStyle={{}}>
          {/* render columns */}
          <View>
            {/* render header */}
            {/* <View style={customStyle.DashBTbl_ReportHdr}>
          {report_cols.map((column,index)=>{
            return(
              <View style={[customStyle.DashBTbl_ReportHdrCol,customStyle.DashBTbl_ReportColW]}>
                <Text  style={customStyle.DashBTbl_ReportHdrColTxt}>{column.colname}</Text>
              </View>
            )
          })}
          </View> */}
            {/* render content */}
            <View style={customStyle.DashBCard_Wrap}>
              {report_data.map((row, row_index) => {

                let gset_obj = row["Color"] != null && row["Color"] != null != '' ? JSON.parse(row["Color"]) : {};
                let card_bgColor = gset_obj["bgColor"] != null ? gset_obj["bgColor"] : '';
                let card_font = gset_obj["font"] != null ? gset_obj["font"] : {};
                let card_name = gset_obj["card_name"] != null ? gset_obj["card_name"] : '';
                let card_icon = gset_obj["icon"] != null ? gset_obj["icon"] : '';
                let show_random_icon = gset_obj["random_icon"] != null ? gset_obj["random_icon"] : true;
                let hide_report_name = gset_obj["hide_report_name"] != null ? gset_obj["hide_report_name"] : false;
                let isfirsItem = row_index == 0;
                let islastItem = row_index == report_data.length - 1;


                return (
                  <TouchableOpacity disabled={item.DrillDown ? false : true} style={[customStyle.DashBCard_Item, (!isfirsItem && !islastItem ? customStyle.DashBCard_ItemMid : (isfirsItem ? customStyle.DashBCard_ItemFirst : customStyle.DashBCard_ItemLast))]} onPress={() => { props.navigation.navigate("DashboardReportDetail", { "ReportData": item, "AdKPIId": row["AdKPIId"] }) }}>

                    {(card_name != '' || card_icon != '' || show_random_icon) &&
                      <View style={customStyle.DashBCard_Itemhdr}>
                        {!hide_report_name && <Text style={customStyle.DashBCard_ItemhdrText}>{card_name}</Text>}
                        {card_icon != '' &&
                          <View style={customStyle.DashBCard_ItemhdrIcon}>
                            {<Image source={{ uri: card_icon }} style={{ width: '90%' }} resizeMode='contain' />}
                          </View>
                        }
                        {card_icon == '' && show_random_icon &&
                          <View style={customStyle.DashBCard_ItemhdrIcon}>
                            {(row_index % 2 == 0) && <Store_coveredIcon width={'80%'} style={{ borderWidth: 1 }} />}
                            {(row_index % 2 != 0) && <Store_plannedIcon width={'80%'} style={{ borderWidth: 1 }} />}
                          </View>
                        }
                      </View>}
                    <View style={customStyle.DashBCard_ItemContent}>
                      {report_cols.map((column, index) => {
                        let colValue = row[column.actual_colname] != null ? row[column.actual_colname] : '';

                        let color_obj = get_rowColSettings(colValue, column.actual_colname, row);

                        let cust_style = {}, bg_style = {};
                        if (color_obj.color != null && color_obj.color != '') {
                          bg_style["backgroundColor"] = color_obj.color;
                          cust_style["color"] = '#fff'
                        }
                        if (color_obj.fontsize != null && color_obj.fontsize != '') {
                          cust_style["fontSize"] = color_obj.fontsize
                        }
                        if (color_obj.bold == 1) {
                          cust_style["fontWeight"] = "600"
                        }

                        return (
                          <View style={[customStyle.DashBCard_IInn_row, (index == report_cols.length - 1 ? {} : customStyle.DashBCard_IInn_rowB)]}>
                            <Text style={[customStyle.DashBCard_IInn_hd]}>{column.colname}</Text>
                            <Text style={[customStyle.DashBCard_IInn_valueTxt, cust_style]}>{colValue}</Text>
                          </View>
                        )
                      })}
                    </View>
                  </TouchableOpacity>
                )
              })}
            </View>
          </View>

        </ScrollView>}
      </View>
    )
  }

  function _renderDashboardReports() {

    return (
      <View style={customStyle.DashB_ReportWrap}>
        <View style={customStyle.DashB_ReportsHdr}>
          <Text style={customStyle.DashB_ReportsHdrTxt}>{"Reports"}</Text>
          <TouchableOpacity style={customStyle.DashB_ReportsHdrIcon} onPress={() => { refreshDashBReport() }}>
            <Feather name="refresh-cw" size={20} color={PageTheme.$accent_color} />
          </TouchableOpacity>
        </View>
        {AppDashReportsSec.map((item, index) => {
          // console.log("report:",item);
          return (
            <View style={customStyle.DashB_ReportCon} key={index}>
              <View style={customStyle.DashB_ReportConHdr}>
                <Text style={customStyle.DashB_ReportConHdrTxt}>{item.DashboardName}</Text>
              </View>
              <View style={customStyle.DashB_ReportContent}>
                {item.DashboardType == 'Tabular' &&
                  _renderTabularReport(item)
                }
                {item.DashboardType == 'Card' &&
                  _renderCardReport(item)
                }
              </View>
            </View>
          )
        })}
      </View>
    )
  }

  const injectedHeightJS = `
(function() {
  var lastHeight = 0;

  function getHeight() {
    var body = document.body;
    var html = document.documentElement;

    return Math.max(
      body.scrollHeight,
      body.offsetHeight,
      html.clientHeight,
      html.scrollHeight,
      html.offsetHeight
    );
  }

  function sendHeight() {
    var height = getHeight();

    if (height !== lastHeight && height > 0) {
      lastHeight = height;
      window.ReactNativeWebView.postMessage(
        JSON.stringify({ type: "HEIGHT", value: height })
      );
    }
  }

  // initial attempts
  sendHeight();
  setTimeout(sendHeight, 300);
  setTimeout(sendHeight, 1000);
  setTimeout(sendHeight, 2000);

  // mutation observer (modern phones)
  try {
    var observer = new MutationObserver(sendHeight);
    observer.observe(document.body, {
      childList: true,
      subtree: true,
      attributes: true
    });
  } catch(e) {}

  // fallback polling (older phones)
  setInterval(sendHeight, 500);

  window.addEventListener("load", sendHeight);
  window.addEventListener("resize", sendHeight);
})();
true;
`;




  function _renderDashBoard() {
    return (
      <ScrollView >
        <View style={customStyle.NB_background} >
          <Text style={customStyle.NB_text}> Quick Links</Text>
          <FlatList
            horizontal={true}
            data={QuickLinks}
            renderItem={({ item, index }) => {
              let IconCompFunc = item.icon;
              let showVectoreIcon = item.iconType == 'Icon' ? true : false;
              return (
                <View style={customStyle.NB_tblHdrparent} key={index}>
                  <TouchableOpacity onPress={item.itemOnPress} >
                    <View style={[customStyle.NB_tblHdr, (!showVectoreIcon ? customStyle.NB_tblHdr2 : {}), (index % 2 != 0 ? { backgroundColor: '#f4e8fb' } : {})]} >
                      {!showVectoreIcon && item.icon && (<item.icon width={45} height={45} style={{ marginTop: 10 }} />)}
                      {showVectoreIcon && IconCompFunc()}
                    </View>
                    <Text style={customStyle.NB_tblTextItem} >{item.text}</Text>
                  </TouchableOpacity>
                </View>
              )
            }}
          />
        </View>

        {bannerdetail?.length > 0 && (
          <View style={customStyle.NB_bannerImgBg}>
            <Carousel
              ref={imageSlider}
              width={WP('100%')}
              height={165}
              data={bannerdetail}
              loop
              autoPlay
              autoPlayInterval={2000}      // 🔥 same as autoplayDelay
              scrollAnimationDuration={800}
              panGestureHandlerProps={{
                activeOffsetX: [-10, 10], // 🔥 prevents drift (Android fix)
              }}
              onSnapToItem={(index) => setActiveSlide(index)}
              renderItem={({ item }) => {
                const url = item.NoticeLink_Thumbnail;
                return (
                  <View style={customStyle.NB_bannerCard}>
                    <TouchableOpacity
                      activeOpacity={0.9}
                      onPress={() => handleBannerNavigation(item, props)}
                    >
                      <Image
                        source={{ uri: url }}
                        style={customStyle.NB_bannerCardImg}
                        resizeMode="cover"
                      />
                    </TouchableOpacity>
                  </View>
                );
              }}
            />

            {/* Pagination + More */}
            {/* Pagination Container */}
            <View
              style={{
                justifyContent: 'center',
                alignItems: 'center',
                marginBottom: 5,
                position: 'relative',
              }}
            >
              {/* Pagination Dots (CENTER) */}
              <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                {bannerdetail.map((_, index) => (
                  <View
                    key={index}
                    style={[
                      customStyle.NB_bannerDot,
                      {
                        backgroundColor:
                          index === activeSlide
                            ? PageTheme.$primary_color
                            : PageTheme.$tertiary_color,
                        opacity: index === activeSlide ? 0.9 : 0.4,
                        transform: [{ scale: index === activeSlide ? 1 : 0.8 }],
                      },
                    ]}
                  />
                ))}
              </View>

              {/* More Text (RIGHT SIDE) */}
              <TouchableOpacity
                style={{
                  position: 'absolute',
                  right: 5,
                }}
                onPress={() => props.navigation.navigate('BannerMoreInfo',{bannerdetail : bannerdetail})}
              >
                <Text style={{ fontSize: 12,fontWeight:"500", color: PageTheme.$primary_color }}>
                  More...
                </Text>
              </TouchableOpacity>
            </View>
          </View>
        )}


        {props.WebViewDashboard && props.AppDashboardWebViewObj !== "" && QuickLinks.length > 0 && bannerRefresh ?
          <WebView
            style={{
              flex: 1,
              borderRadius: 5,
              margin: 2,
              borderWidth: 1,
              height: webHeight
            }}
            source={{ uri: props.AppDashboardWebViewObj }}
            injectedJavaScript={injectedHeightJS}
            javaScriptEnabled={true}
            domStorageEnabled={true}
            allowFileAccess={true}
            cacheEnabled={false}  // Disable cache
            incognito={true}
            scrollEnabled={false}
            onMessage={(event) => {
              try {
                const msg = JSON.parse(event.nativeEvent.data);
                console.log("height", msg)
                if (msg.type === "HEIGHT" && msg.value > 0) {
                  setWebHeight(msg.value);
                }
              } catch (e) {
                // ignore non-JSON or site events
              }
            }}
            onError={(syntheticEvent) => {
              console.error('WebView error:', syntheticEvent.nativeEvent);
            }}
            onLoadStart={() => console.log('WebView loading...')}
            onLoadEnd={() => console.log('WebView loaded successfully')}
            onLoadProgress={({ nativeEvent }) => {
              console.log('Load progress:', nativeEvent.progress);
            }}
          />
          : <>
            {props.Show_OldMTDReports &&
              <View style={customStyle.NB_PerfBg} >
                <Text style={customStyle.NB_text}>Performance</Text>
                <FlatList
                  horizontal={true}
                  data={StorePerformanceText}
                  style={[customStyle.NBPerf_listStyle]}
                  renderItem={({ item, index }) => {
                    let value = DashboardCovdata[item.value_Key] || '0';
                    return (
                      <View style={customStyle.NB_PerfItem} key={index}>
                        <View style={[customStyle.NB_PerfItemInner, (index % 2 != 0 ? { backgroundColor: '#f4f1e0' } : {})]} >
                          {/* <SvgXml width={'100%'} height={'50%'} marginTop={5} marginLeft={15} xml={item.icon} /> */}
                          {item.icon && (<item.icon width="100%" height="50%" style={{ marginTop: 5, marginLeft: 15 }} />)}
                          <View style={customStyle.NB_PerfRow}>
                            <View style={customStyle.NB_PerfCol1}>
                              <Text style={customStyle.NB_PerfLbl} >{item.text}</Text>
                            </View>
                            <View style={customStyle.NB_PerfCol2}>
                              <Text style={customStyle.NB_PerfValue} >{value}</Text>
                            </View>
                          </View>
                        </View>
                      </View>
                    )
                  }}
                />

                <View style={customStyle.NB_PerfD_row}>
                  <View style={[customStyle.NB_PerfD_col, customStyle.NB_PerfD_col1]}>
                    <View style={[customStyle.NB_PerfD_colInner, customStyle.NB_PerfD_colInner1]}>

                      <View style={[customStyle.NB_PerfD_ItemWrap]} >
                        <Text style={customStyle.NB_PerfD_IHdr_Txt} >{'FTD'}</Text>
                        {/* <SvgXml width={'100%'} height={'50%'} padding={30} xml={store_coveredIcon} /> */}
                        <Store_coveredIcon width={'100%'} height={'50%'} padding={30} />
                        <Store_coveredIcon width={'100%'} height={'50%'} padding={30} />
                      </View >

                      <View style={[customStyle.NB_PerfD_rowI]} >
                        <Text style={customStyle.NB_PerfD_ICon_Lbl}>Planned</Text>
                        <Text style={customStyle.NB_PerfD_ICon_Val} >{DashboardCovdata.FTDPlanned}</Text>
                      </View>
                      <View style={[customStyle.NB_PerfD_rowI, customStyle.NB_PerfD_rowI2, customStyle.pt10]}>
                        <View style={[customStyle.NB_PerfD_colI, customStyle.NB_PerfD_colI1]}>
                          <Text style={customStyle.NB_PerfD_ICon_Lbl}>Covered</Text>
                          <Text style={customStyle.NB_PerfD_ICon_Val} >{DashboardCovdata.FTDCovered}</Text>
                        </View>
                        <View style={customStyle.NB_PerfD_ICon_Separator} ></View>
                        <View style={[customStyle.NB_PerfD_colI, customStyle.NB_PerfD_colI2]}>
                          <Text style={customStyle.NB_PerfD_ICon_Lbl}>Merchandised</Text>
                          <Text style={customStyle.NB_PerfD_ICon_Val} >{DashboardCovdata.FTDMerchandised}</Text>
                        </View>
                      </View>

                    </View>
                  </View>
                  <View style={[customStyle.NB_PerfD_col, customStyle.NB_PerfD_col2]}>
                    <View style={[customStyle.NB_PerfD_colInner, customStyle.NB_PerfD_colInner2]}>

                      <View style={[customStyle.NB_PerfD_ItemWrap]} >
                        <Text style={customStyle.NB_PerfD_IHdr_Txt} >{'MTD'}</Text>
                        {/* <SvgXml width={'100%'} height={'50%'} padding={30} xml={Store_plannedIcon} /> */}
                        <Store_plannedIcon width={'100%'} height={'50%'} padding={30} />
                      </View >

                      <View style={[customStyle.NB_PerfD_rowI]} >
                        <Text style={customStyle.NB_PerfD_ICon_Lbl}>Planned</Text>
                        <Text style={customStyle.NB_PerfD_ICon_Val} >{DashboardCovdata.MTDPlanned}</Text>
                      </View>
                      <View style={[customStyle.NB_PerfD_rowI, customStyle.NB_PerfD_rowI2, customStyle.pt10]}>
                        <View style={[customStyle.NB_PerfD_colI, customStyle.NB_PerfD_colI1]}>
                          <Text style={customStyle.NB_PerfD_ICon_Lbl}>Covered</Text>
                          <Text style={customStyle.NB_PerfD_ICon_Val} >{DashboardCovdata.MTDCovered}</Text>
                        </View>
                        <View style={customStyle.NB_PerfD_ICon_Separator2} ></View>
                        <View style={[customStyle.NB_PerfD_colI, customStyle.NB_PerfD_colI2]}>
                          <Text style={customStyle.NB_PerfD_ICon_Lbl}>Merchandised</Text>
                          <Text style={customStyle.NB_PerfD_ICon_Val} >{DashboardCovdata.MTDMerchandised}</Text>
                        </View>
                      </View>

                    </View>
                  </View>

                </View>
              </View>
            }
            {AppDashReportsSec.length > 0 &&
              _renderDashboardReports()
            }
          </>}
      </ScrollView>
    )
  }

  function DownloadErrorAlert() {

    let { ErrorMsg, ErrorSubMsg, ErrorDetail } = DErrorMsg;

    return (
      <CustomModal
        style={customStyle.dErrM_Style}
        titleStyle={customStyle.dErrMsg}
        title={(ErrorMsg || '')}
        message={(ErrorSubMsg || '')}
        messageStyle={customStyle.dErrSubMsg}
        showModal={showDErrAlert}
      >
        {ErrorDetail != null && ErrorDetail != '' && <Text style={customStyle.dErrDetail}>{ErrorDetail}</Text>}
        <View style={customStyle.storelVisitM_options}>
          <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={() => { setshowDErrAlert(false) }}>
            <Text style={customStyle.storelVisitM_op_btnText}>{'Ok'}</Text>
          </TouchableOpacity>
        </View>
      </CustomModal>
    )
  }

  // WebView Survey

  const [surveydata, setSurveyData] = useState({});
  const [modalVisiblesurvey, setModalVisibleSurvey] = useState(false);
  const [surveyloader, setSurveyLoader] = useState(false);
  const webViewRef = useRef(null);
  const isFocused = useIsFocused();

  const ShowSurveyPopup = async () => {
    console.log("Survey popup called---")
    let projectInfo = await get_item('projectInfo');
    let projectCode = await get_item('projectCode');
    let loginInfo = await get_item('loginInfo');
    const loginDetails = JSON.parse(loginInfo);
    const projectDetails = JSON.parse(projectInfo);

    try {
      setSurveyLoader(true);
      const raw = JSON.stringify({
        ProjectId: projectDetails?.projectID,
        UserId: loginDetails?.UserId,

      });
      console.log("raw---------", raw)
      let res = await fetch(
        "https://api1.parinaam.in/api/cpminternal/GetPopupWeburl",
        {
          method: "POST",
          body: raw,
          headers: {
            "Accept": "application/json",
            "Content-Type": "application/json",
          },
        }
      );
      let responseJson = await res.json();
      if (responseJson) {
        setSurveyData(responseJson?.GetPopupWeburl);
        console.log("responseJson?.GetPopupWeburl[0]?.Status", responseJson)
        if (responseJson?.GetPopupWeburl[0]?.Status) {
          setModalVisibleSurvey(false);
        } else {
          setModalVisibleSurvey(true);
        }
      } else {
        setSurveyData({});
      }
    } catch (error) {
      setSurveyLoader(false);
      console.log("Survey Popup:" + error);
    } finally {
      setSurveyLoader(false);
    }
  };

  useEffect(() => {
    if (props.isInternetAvailable == true) {
      ShowSurveyPopup();
    }

  }, [isFocused]);

  let webUrl = surveydata[0]?.WebUrl;
  const injectedJS = `
  (function() {
    function notifyReactNative() {
      window.ReactNativeWebView.postMessage(
        JSON.stringify({ id: "cpminternalclose", event: "clicked" })
      );
    }

    // Wait until DOM loads
    document.addEventListener("DOMContentLoaded", function() {
      var btn = document.getElementById("cpminternalclose");
      if (btn) {
        btn.addEventListener("click", notifyReactNative);
      }
    });

    // Also check repeatedly (in case content is dynamic)
    var checkInterval = setInterval(function() {
      var btn = document.getElementById("cpminternalclose");
      if (btn) {
        clearInterval(checkInterval);
        btn.addEventListener("click", notifyReactNative);
      }
    }, 500);
  })();
  true;
`;


  const handleMessage = (event) => {
    const data = JSON.parse(event.nativeEvent.data);
    console.log("WebView message:", data);

    if (data.id === "cpminternalclose" && data.event === "clicked") {
      setTimeout(() => {
        setModalVisibleSurvey(false);
        ShowSurveyPopup();
      }, 1500);
    }
  };


  return (
    <>
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS == 'ios' ? true : false)} >
        {processing && <CustomLoader fullHeight={true} title={loaderTitle} />}
        {(props.startDownload && dowloadedCount <= totalCount) && <DownloadDataModal title={ST.DownloadingData} downloadCount={dowloadedCount} totalCount={totalCount} subtitle={downloadingText} />}
        {(startUploading) && <DownloadDataModal title={UploadingText} downloadCount={uploadedCount} totalCount={TotalUpCount} subtitle={UploadingSubText} showProgresssBar={showProgresssBar} showOkButton={showOkButtonOnUpload} OnOKClick={OnOKClick} subTextStyle={subTextStyle} />}
        <DownloadErrorAlert />
        <DrawerHeader {...props} drawer_title={ST.NoticeBoard} projectCode={projectCode} />
        <LinearGradient colors={[PageTheme.$gradient1, PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
          <View style={[customStyle.pageContentWrapper, customStyle.roundScrollInner, { paddingTop: 0 }]}>
            {IRSessionPendingCount > 0 &&
              <TouchableOpacity style={customStyle.NB_IRAlertWrap} onPress={() => { props.navigation.navigate('IRPendingDetails') }}>
                <Feather name='alert-triangle' size={30} color={PageTheme.$accent_color} />
                <Text style={customStyle.NB_IRAlertTxt}>IR Image Upload Pending! Please upload all IR image by clicking side menu "Upload Data" button</Text>
              </TouchableOpacity>}
            {_renderDashBoard()}
          </View>
        </LinearGradient>

      </Container>
      {
        // need to uncomment this popup
        <Modal
          animationType="slide"
          transparent={true}
          visible={modalVisiblesurvey}
          onRequestClose={() => setModalVisibleSurvey(false)}
        >
          <View style={styles.modalContainer}>
            <View style={styles.modalContent}>
              {surveyloader && <CustomLoader fullHeight={true} title={"Loading"} />}
              <WebView
                style={styles.webView}
                source={{ uri: webUrl }}
                onLoadStart={() => setSurveyLoader(true)}
                onLoadEnd={() => {
                  setSurveyLoader(false);
                  console.log("ENd Loadingggg...---");
                }}
                ref={webViewRef}
                injectedJavaScript={injectedJS}
                onMessage={handleMessage}
              />
            </View>
          </View>
        </Modal>
      }

      <TrainingPromptModal
        visible={props.startDownload == false && showTrainingModal && (props.Gyancast == 1 || props.Gyancast)}
        onDoIt={handleDoIt}
        onNotNow={handleNotNow}
        item={TrainingOrg}
        dueDate="17/08/2025"
      />

      <BadgeModal
        visible={showBadge}
        onClose={() => {
          setTimeout(() => {
            setShowBadge(false);
          }, 100);   // 10 seconds
        }}
        onSave={handleSaveBadge}
      />
    </>
  );
}

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


const styles = StyleSheet.create({
  screen: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'transparent',
  },
  buttonText: {
    color: '#fff',
    fontSize: 16,
  },
  modalContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    overflow: 'hidden',
    marginTop: 15
  },
  modalContent: {
    width: '100%',
    minHeight: "85%",
    backgroundColor: 'transparent',
    borderRadius: 10,
    overflow: 'hidden',
  },
  webView: {
    flex: 1,
    backgroundColor: "transparent"
  },
})

