import React, { useState, useEffect, memo, useRef } from 'react';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
import { globalStyles, customStyles, GetPageTheme } from "../styles/Global";
import { StatusBar, Image, TextInput, View, Text, ScrollView, TouchableOpacity, TouchableHighlight, Platform, PermissionsAndroid, FlatList, DeviceEventEmitter, Alert, StyleSheet } 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, getDownloadJson1, checkRange, UploadData2, UpdateStoreStatus, getKPIS, marktext1, marktext2, UploadFormData, resizeImage, restore_ImageWithMetaData, getKPIFieldsForKyc, getValidStores, fetchDistanceMatrix, mergeStoreDistances } from '../controller/functions';
import { get_item } from '../components/localStorage';
import { db, AppVersion, CoverageImagePath } from '../constants/constants';
import CustomHeader from '../components/customHeader';
import { AntDesign, Entypo, Feather, FontAwesome, Fontisto, Ionicons, MaterialCommunityIcons } from '../components/icons';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import NoDataComponent from '../components/NoDataComponent';
import MapIcon from '../assets/performics/map_icon.svg';
import CustomModal from '../components/CustomModal';
import { AppTables } from '../constants/tableConstants';
import { _checkLocationPermission } from '../components/geolocation';
import Geolocation from 'react-native-geolocation-service';
import { getAvailblQuery, getIfAvlbl, getIfKPIDone, getQuery, Q_getMyStoresList, Q_MenuList } from '../constants/ConstantQueries';
import { ConfirmSaveAlert } from '../components/alert';
import { getFolderName, getMethodName, METHODS } from '../constants/methodNames';
import { SyncIRsessions, UpdateIRUploadStatus_G, getIRTables, uploadAllData, uploadAllImages, uploadStoreStatus } from '../constants/uploadData';
import * as RNFS from 'react-native-fs';

import CameraImg2 from '../assets/performics/camera_icon.svg';
import CustomCamera from '../components/Camera';
import HeaderTabs from '../components/HeaderTabs';
import StoreGeoIcon from '../assets/image/storegeoicon.svg'
import DownloadDataModal from '../components/downloadDataModal';
import IRLogin from '../components/IRLogin';
import RouteIcon from '../assets/image/routeicon.svg';
import { AppName, PerformicsIRAppName } from '../../../AppSpecificContant';
import AsyncStorage from "@react-native-async-storage/async-storage";

const StoreItem = memo((props) => {
  const route = useRoute();
  const PageTheme = GetPageTheme(props.DarkMode, route.name);
  const customStyle = customStyles(props.DarkMode, route.name);
  const [KPIFields, setKPIFields] = useState([]);
  const [designation, setDesignation] = useState('');
  const item = props.item;
  //console.log("itemmm:",item);
  const ST = props.StaticText || {};
  let flags = true
  async function getStatus(data) {
    return await props.executeSelQuery(`select * from ${AppTables.COVERAGE_DATA} Where VISIT_DATE='${data.VisitDate}' and STORE_ID = ${data.StoreId}`);
  }

  async function get_to_store_details(data, flag) {
    let AllKPIFields = await getKPIFieldsForKyc();
    setKPIFields(AllKPIFields);
    console.log("AllKPIFields", AllKPIFields)
    let token = await get_item('loginToken');
    let loginInfo = await get_item('loginInfo');
    const loginDetails = JSON.parse(loginInfo);
    let desg = loginDetails.Designation || '';
    setDesignation(desg);
    let ShowCompactStoreProfileRestrict = AllKPIFields?.findIndex((i) => i.KPIFieldName == "CompactStoreProfileRestrict");
    let ShowCompactStoreProfileRestrictObj = ShowCompactStoreProfileRestrict >= 0 ? AllKPIFields[ShowCompactStoreProfileRestrict] : {};
    let ShowCompactStoreSplitArr = ShowCompactStoreProfileRestrictObj?.KPIFieldDisplayName?.split(",") || []
    const isCompactStoreData = ShowCompactStoreSplitArr;
    console.log('iscompetitorValues', isCompactStoreData, designation)
    let checkPJPData = await props.executeSelQuery(`select * from ${AppTables.COVERAGE_DATA} Where VISIT_DATE='${data.VisitDate}' and STORE_ID = ${data.StoreId}`);
    console.log("checkPJPData", checkPJPData.IsAvlbl)
    if (data.UploadStatus == 'U') {
      notify(ST.AllDataalreadyuploadedforthisstore);
    }
    else if (data.UploadStatus == 'L') {
      notify(ST.Alreadymarkedasnotworkingstatusforthisstore);
    }
    else if (data.UploadStatus == 'I' && checkPJPData.IsAvlbl == true) {
      let MenuListLen = data.MenuListLen;
      let MenuListLenWithNonAvlbl = data.MenuCountWithNonAvlbl;
      console.log('menuList length MenuListLenWithNonAvlbl:', MenuListLen, MenuListLenWithNonAvlbl);
      let s_screen = "StoreDailyMenu";
      if (props.ShowStoreProfile == true && data.Deviation != 6) {
        s_screen = "StoreProfile";
      } else if (props.ShowCompactStoreProfile == true) {
        if (!isCompactStoreData.includes(desg)) {
          s_screen = "StoreProfileKyc";
        }
        else {
          s_screen = "StoreDailyMenu";
        }
      }
      else if (props.ShowStoreChecklist == true || props.StoreChecklistOnce == true) {
        s_screen = "StoreChecklist";
      } else if (props.ShowReportAfterCheckIn == true) {
        s_screen = "StoreReport";
      }

      console.log('s_screen:', s_screen);
      if (MenuListLenWithNonAvlbl > 0) {
        props.set_autoback({ 'AutoGoToPrev': false });
        props.navigation.navigate(s_screen, { storeData: data, 'isAdhoc': props.isAdhocScreen, 'isBeat': props.isBeatPlan, 'isNonMerchans': props.isNonMerchan, 'isNonProgs': props.isNonProg, 'isStoreSearch': props.isStoreSearch, '_fromStoreWise': true });
      }
      else {
        notify("No menu map for this store!");
      }
    }
    else if (data.UploadStatus == 'C') {
      notify(ST.Alreadycheckedout);

    }
    else if (data.UploadStatus == 'D') {
      notify(ST.Dataalreadyuploaded);
    }
    else if (data.UploadStatus == 'P') {
      notify(ST.Datapartiallyuploaded);
    }
    else if (data.UploadStatus == 'N' || (data.UploadStatus == 'I' && checkPJPData.IsAvlbl == false) || data.UploadStatus == '') {
      let isAdhocActive = await checkisAdhocActive();
      console.log("checkadhocactiv--", isAdhocActive)
      let isChcekedIn = await checkIfAlreadyCheckdIn();
      let isChcekedInjcp = await checkIfAlreadyCheckdInjcp();
      console.log('ischekin==', isChcekedInjcp)
      let pjpuploadstatus = true;

      if (isChcekedInjcp.IsAvlbl == true) {
        pjpuploadstatus = getcurrentstatus(data.StoreId, isChcekedInjcp.data)
      }
      console.log('isChcekedIn', pjpuploadstatus);
      if (pjpuploadstatus == false || isChcekedIn.IsAvlbl == true) {
        notify(ST.Youarealreadycheckedintotheotherstore, 'LONG');
      } else if (isAdhocActive) {
        notify('Please fill the No working reason', 'LONG');
      }
      else {
        props.setShowStoreVisitModal(true);
        props.setCurrentStore(data);
      }
    }
  }

  async function AskForCancelCheckin(data) {
    props.setCancelCheckOutStore(data);
    props.setShowCancelCIModal(true);
  }

  async function checkisAdhocActive() {
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    let AdhocActivated = props.AdhocActivated || ""
    let AdhocActivatedFlag = AdhocActivated.split(",")
    let checkPjpSize = `SELECT COUNT(*) as count FROM Mapping_JourneyPlan WHERE VisitDate='${d2}'`;
    let result = await props.executeSelQuery(checkPjpSize, '4');

    let join = `INNER JOIN ${AppTables.COVERAGE_DATA} t2 on t2.STORE_ID=t1.StoreId and t2.JCP_TYPE='Mapping_JourneyPlan' `;
    let q = `Select t1.* from Mapping_JourneyPlan t1 ${join} where t1.VisitDate='${d2}' and t1.UploadStatus='U' ${(props.isAdhocScreen && AdhocActivatedFlag > 0) ? `and t2.REASON_ID IN (${props.AdhocActivated})` : ""}`
    let AdhocActive = false;
    let checkPJPData = await props.executeSelQuery(q, '1');
    if ((props.isAdhocScreen && AdhocActivatedFlag > 0) && !checkPJPData.IsAvlbl && result?.data?.count > 0) {
      AdhocActive = true;
    }

    return AdhocActive;

  }


  async function checkIfAlreadyCheckdIn() {
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    let AdhocActivated = props.AdhocActivated || ""
    let AdhocActivatedFlag = AdhocActivated.split(",")
    let join = `INNER JOIN ${AppTables.COVERAGE_DATA} t2 on t2.STORE_ID=t1.StoreId and t2.JCP_TYPE='Mapping_JourneyPlan' `;
    let q = `Select t1.* from Mapping_JourneyPlan t1 ${join} where t1.VisitDate='${d2}' and t1.UploadStatus='I' `
    let join2 = `INNER JOIN ${AppTables.COVERAGE_DATA} t2 on t2.STORE_ID=t1.StoreId and t2.JCP_TYPE='Adhoc_JourneyPlan' `;
    let q2 = `Select t1.* from Adhoc_JourneyPlan t1 ${join2} where t1.VisitDate='${d2}' and t1.UploadStatus='I'  `
    let join3 = `INNER JOIN ${AppTables.COVERAGE_DATA} t2 on t2.STORE_ID=t1.StoreId and t2.JCP_TYPE='JourneyPlan_RouteWise' `;
    let q3 = `Select t1.* from JourneyPlan_RouteWise t1 ${join3} where t1.VisitDate='${d2}' and t1.UploadStatus='I'`
    let join4 = `INNER JOIN ${AppTables.COVERAGE_DATA} t2 on t2.STORE_ID=t1.StoreId and t2.JCP_TYPE='NonMerchandising_JourneyPlan' `;
    let q4 = `Select t1.* from NonMerchandising_JourneyPlan t1 ${join4} where t1.VisitDate='${d2}' and t1.UploadStatus='I'`
    let join5 = `INNER JOIN ${AppTables.COVERAGE_DATA} t2 on t2.STORE_ID=t1.StoreId and t2.JCP_TYPE='NonProgram_JourneyPlan' `;
    let q5 = `Select t1.* from NonProgram_JourneyPlan t1 ${join5} where t1.VisitDate='${d2}' and t1.UploadStatus='I'`
    let join6 = `INNER JOIN ${AppTables.COVERAGE_DATA} t2 on t2.STORE_ID=t1.StoreId and t2.JCP_TYPE='StoreSearch_JourneyPlan' `;
    let q6 = `Select t1.* from StoreSearch_JourneyPlan t1 ${join6} where t1.VisitDate='${d2}' and t1.UploadStatus='I'`

    let checkPJPData = await props.executeSelQuery(q, '1');
    console.log('checkPJPData:', checkPJPData);
    if (!checkPJPData.IsAvlbl) {
      let checkAdhocData = await props.executeSelQuery(q2, '1');
      console.log('checkAdhocData:', checkAdhocData);
      if (!checkAdhocData.IsAvlbl) {
        let checkRouteData = await props.executeSelQuery(q3, '1', props.ShowBeatPlanList == true);
        console.log('checkRouteData:', checkRouteData);
        if (!checkRouteData.IsAvlbl) {
          let checkNonMerData = await props.executeSelQuery(q4, '1', props.ShowNonMerList == true);
          console.log('checkNonMerData:', checkNonMerData);
          if (!checkNonMerData.IsAvlbl) {
            let checkNonProgData = await props.executeSelQuery(q5, '1', props.ShowNonProgram == true);
            if (!checkNonProgData.IsAvlbl) {
              let checkStoreSearchData = await props.executeSelQuery(q6, '1', props.ShowStoreSearch == true);
              console.log('checkStoreSearchData:', checkStoreSearchData);
              return checkStoreSearchData;
            } else {
              return checkNonProgData;
            }
          } else {
            return checkNonMerData;
          }
        }
        else {
          return checkRouteData;
        }
      }
      else {
        return checkAdhocData;
      }
    }
    else {
      return checkPJPData;
    }
  }

  function getcurrentstatus(storeid, item) {
    let status = true;
    // Check if the 'UploadStatus' is 'I' and if the 'StoreId' does not match
    if (item.UploadStatus === 'I') {
      if (storeid !== item.StoreId) {
        status = false;
      }
    }

    return status;
  }

  async function checkIfAlreadyCheckdInjcp() {
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    let AdhocActivated = props.AdhocActivated || '';
    let AdhocActivatedFlag = AdhocActivated.split(',');
    // Define the table names and queries
    let tables = [
      { name: 'Mapping_JourneyPlan', query: `SELECT t1.* FROM Mapping_JourneyPlan t1 WHERE t1.VisitDate='${d2}' AND t1.UploadStatus='I'` },
      { name: 'Adhoc_JourneyPlan', query: `SELECT t1.* FROM Adhoc_JourneyPlan t1 WHERE t1.VisitDate='${d2}' AND t1.UploadStatus='I'` },
      { name: 'JourneyPlan_RouteWise', query: `SELECT t1.* FROM JourneyPlan_RouteWise t1 WHERE t1.VisitDate='${d2}' AND t1.UploadStatus='I'` },
      { name: 'NonMerchandising_JourneyPlan', query: `SELECT t1.* FROM NonMerchandising_JourneyPlan t1 WHERE t1.VisitDate='${d2}' AND t1.UploadStatus='I'` },
      { name: 'NonProgram_JourneyPlan', query: `SELECT t1.* FROM NonProgram_JourneyPlan t1 WHERE t1.VisitDate='${d2}' AND t1.UploadStatus='I'` },
      { name: 'StoreSearch_JourneyPlan', query: `SELECT t1.* FROM StoreSearch_JourneyPlan t1 WHERE t1.VisitDate='${d2}' AND t1.UploadStatus='I'` }
    ];

    // Check if a table exists before querying
    for (let table of tables) {
      try {
        // Check if the table exists in the database
        let checkTableExistsQuery = `SELECT name FROM sqlite_master WHERE type='table' AND name='${table.name}'`;
        let tableExists = await props.executeSelQuery(checkTableExistsQuery, '1');
        // If the table exists, execute the query
        if (tableExists) {
          let result = await props.executeSelQuery(table.query, '1');
          console.log(`Result from ${table.name}:`, result);
          // If data is found, return the result and stop further execution
          if (result) {
            return result;  // Stop further queries if data is found
          }
        } else {
          console.log(`Table '${table.name}' does not exist, skipping...`);
        }
      } catch (error) {
        console.log(`Error querying table '${table.name}':`, error.message);
        // Continue to the next table if error occurs
        continue;
      }
    }
    // If no matching data was found in any table, return null
    console.log('No matching data found in any table.');
    return null;
  }

  return (
    <TouchableOpacity
      style={[customStyle.storel, item?.StoreBgColor && item?.StoreBgColor.trim() !== ""
        ? { backgroundColor: item?.StoreBgColor }
        : { backgroundColor: "#fff" }]}
      key={props.index}
      onPress={() => { get_to_store_details(item, flags) }}>
      {/* {console.log('store--', item, flags)} */}
      <View style={customStyle.storel_card_outer}>
        <View style={customStyle.storel_card}>
          <View style={customStyle.storel_card_content}>
            <Text style={customStyle.storel_card_title}>{item.StoreName}</Text>
          </View>
        </View>
        <View style={customStyle.storel_details}>
          <View style={customStyle.storel_code}>
            <View style={[customStyle.storel_codeCon, customStyle.storel_codeBorder, customStyle.storel_codeConAddr]}>
              <Text style={customStyle.storel_codeLbl}>{ST.StoreId + ':'}</Text>
              <Text style={customStyle.storel_codeText}>{item.StoreId}</Text>
            </View>
            <View style={[customStyle.storel_codeCon, customStyle.storel_codeConAddr]}>
              <Text style={customStyle.storel_codeLbl}>{ST.StoreType + ':'}</Text>
              <Text style={[customStyle.storel_codeText, { width: '50%' }]}>{item.StoreType}</Text>
            </View>
          </View>
          <View style={customStyle.storel_code}>
            <View style={[customStyle.storel_codeCon, customStyle.storel_codeConAddr]}>
              <Text style={customStyle.storel_codeLbl}>{'Store Category:'}</Text>
              <Text style={[customStyle.storel_codeText, customStyle.storel_codeTextAddr]}>{item.StoreCategory}</Text>
            </View>
          </View>
          <View style={customStyle.storel_code}>
            <View style={[customStyle.storel_codeCon, customStyle.storel_codeConAddr]}>
              <Text style={customStyle.storel_codeLbl}>{ST.StoreCode + ':'}</Text>
              <Text style={[customStyle.storel_codeText, customStyle.storel_codeTextAddr]}>{item.StoreCode}</Text>
            </View>
          </View>
          {item.DistributorName != null && item.DistributorId != null && item.DistributorName != '' && item.DistributorId != '' &&
            <View style={[customStyle.storel_code, customStyle.storel_codeBorderTop, customStyle.mt10]}>
              <View style={[customStyle.storel_codeCon, customStyle.storel_codeConAddr]}>
                <Text style={customStyle.storel_codeLbl}>{'Distributor:'}</Text>
                <Text style={[customStyle.storel_codeText, customStyle.storel_codeTextAddr]}>{item.DistributorName}</Text>
              </View>
            </View>
          }
          <View style={[customStyle.storel_code, customStyle.storel_codeBorderTop, customStyle.mt10]}>
            <View style={[customStyle.storel_codeCon, customStyle.storel_codeConAddr]}>
              <Text style={customStyle.storel_codeLbl}>{ST.Address + ':'}</Text>
              <Text style={[customStyle.storel_codeText, customStyle.storel_codeTextAddr]}>{item.Address}</Text>
            </View>
          </View>
          {((item.LastVisitDate != null && item.LastVisitDate != '' && item.LastVisitDate != 'undefined') || (item.Score != null && item.Score != '' && item.Score != 'undefined')) &&
            <View style={[customStyle.storel_code, customStyle.storel_codeBorderTop, customStyle.mt10]}>
              {(item.LastVisitDate != null && item.LastVisitDate != '' && item.LastVisitDate != 'undefined') &&
                <View style={[customStyle.storel_codeCon, ((item.Score != null && item.Score != '' && item.Score != 'undefined') ? customStyle.storel_codeBorder : {}), customStyle.storel_codeConAddr]}>
                  <Text style={customStyle.storel_codeLbl}>{'Last Visit Date:'}</Text>
                  <Text style={customStyle.storel_codeText}>{item.LastVisitDate}</Text>
                </View>}
              {(item.Score != null && item.Score != '' && item.Score != 'undefined') &&
                <View style={[customStyle.storel_codeCon, customStyle.storel_codeConAddr]}>
                  <Text style={customStyle.storel_codeLbl}>{'Store Score:'}</Text>
                  <Text style={[customStyle.storel_codeText, { width: '50%' }]}>{item.Score}</Text>
                </View>}
            </View>
          }

          {(props.StoreRouteView && item.GeoTag !== "N" && item.UploadStatus === "N" && item?.Distance != undefined && item?.Distance) &&
            <View style={[customStyle.storel_code, customStyle.storel_codeBorderTop, customStyle.mt10, { flexDirection: "row", justifyContent: "space-between", alignItems: "center", paddingRight: 12, }]}>
              <View style={[customStyle.storel_codeCon, customStyle.storel_codeConAddr, { alignItems: "flex-start", alignContent: "center" }]}>
                <Text style={[customStyle.storel_codeLbl, { flex: 1, fontWeight: "bold" }]}>
                  {item?.Distance === "Very close to your store!"
                    ? "Very close to your store!"
                    : `${item?.Distance} away, approx. ${item?.Duration}`}
                </Text>
              </View>
              <TouchableOpacity style={[customStyle.storel_codeCon, customStyle.storel_codeConAddr, {}]} onPress={() => { props.navigation.navigate('NavigationRouteScreen', { storeData: item, 'isAdhoc': props.isAdhocScreen, 'isBeat': props.isBeatPlan, 'isNonMerchans': props.isNonMerchan, isNonProgs: props.isNonProg, isStoreSearch: props.isStoreSearch }) }}>
                <RouteIcon width={30} height={30} />
              </TouchableOpacity>
            </View>
          }

          {(item.MTDMerchandised != null && item.MTDMerchandised != '' && item.MTDMerchandised != 'undefined') &&
            <View style={[customStyle.storel_code, customStyle.storel_codeBorderTop, customStyle.mt10]}>
              <View style={[customStyle.storel_codeCon, customStyle.storel_codeConAddr]}>
                <Text style={customStyle.storel_codeLbl}>{'MTD Merchandised Count:'}</Text>
                <Text style={customStyle.storel_codeText}>{item.MTDMerchandised}</Text>
              </View>
            </View>
          }

          {

            (item.CheckInTime != null && item.CheckInTime != '') &&
            <View style={[customStyle.storel_code, customStyle.storel_codeBorderTop, customStyle.mt10]}>
              <Fontisto style={customStyle.storel_codeIcon} color={PageTheme.$secondary_color_dark} name='clock' />
              <View style={[customStyle.storel_codeCon, customStyle.storel_codeBorder]}>
                <Text style={customStyle.storel_codeText}>{ST.CheckIn + ':'}</Text>
                <Text style={customStyle.storel_codeText}>{item.CheckInTime}</Text>
              </View>
              {(item.CheckOutTime != null && item.CheckOutTime != '') &&
                <View style={[customStyle.storel_codeCon]}>
                  <Text style={customStyle.storel_codeText}>{ST.CheckOut + ':'}</Text>
                  <Text style={customStyle.storel_codeText}>{item.CheckOutTime}</Text>
                </View>
              }
            </View>
          }

          {

            (item.UploadStatus != null && item.UploadStatus != '' && item.UploadStatus != 'N') &&
            <View style={[customStyle.storel_code, customStyle.storel_codeBorderTop, customStyle.mt10]}>
              <View style={[customStyle.storel_usWrap]}>
                {item.UploadStatus != null && (item.UploadStatus == 'I' || item.UploadStatus == 'L') &&
                  <TouchableOpacity style={[customStyle.storel_usCon, customStyle.storel_usConBtn, customStyle.storel_usConBtn2]} onPress={() => { AskForCancelCheckin(item) }}>
                    {item.UploadStatus == 'L' ? <MaterialCommunityIcons name='exclamation' color='red' size={20} />
                      : <MaterialCommunityIcons name='login' color='#1f7dbc' size={20} />}
                    {item.UploadStatus == 'L' ? <Text style={[customStyle.storel_usText, { color: 'red' }, customStyle.storel_usBtnText]}>{ST.NotWorking}
                    </Text> : <Text style={[customStyle.storel_usText, { color: '#1f7dbc' }, customStyle.storel_usBtnText]}>{ST.CheckedIn}</Text>}

                    <View style={[customStyle.storel_usBtnRemoveIcon]}>
                      <FontAwesome name='trash' size={20} color={'red'} />
                    </View>
                  </TouchableOpacity>}
                {item.UploadStatus != null && item.UploadStatus == 'C' &&
                  <View style={[customStyle.storel_usCon]}>
                    <MaterialCommunityIcons name='logout' color='#ffd667' size={20} />
                    <Text style={[customStyle.storel_usText, { color: '#ffd667' }]}>{ST.CheckedOut}</Text>
                  </View>}
                {item.UploadStatus != null && item.UploadStatus == 'P' &&
                  <View style={[customStyle.storel_usCon]}>
                    <AntDesign name='cloudupload' color='red' size={20} />
                    <Text style={[customStyle.storel_usText, { color: 'red' }]}>{ST.PartiallyUploaded}</Text>
                  </View>}
                {item.UploadStatus != null && item.UploadStatus == 'D' &&
                  <View style={[customStyle.storel_usCon]}>
                    <Ionicons name='checkmark-sharp' color='green' size={20} />
                    <Text style={[customStyle.storel_usText, { color: 'green' }]}>{ST.DataUploaded}</Text>
                  </View>}
                {item.UploadStatus != null && item.UploadStatus == 'U' &&
                  <View style={[customStyle.storel_usCon]}>
                    <Ionicons name='checkmark-done-sharp' color='green' size={20} />
                    <Text style={[customStyle.storel_usText, { color: 'green' }]}>{ST.Uploaded}</Text>
                  </View>}
                {item.allDone == true && (item.UploadStatus == 'I') &&
                  <TouchableOpacity style={customStyle.storel_CheckOutBtn} onPress={() => { props.onCheckOut ? props.onCheckOut(item) : ''; }}>
                    <Text style={customStyle.storel_CheckOutBtnText}>{ST.CheckOut}</Text>
                  </TouchableOpacity>
                }
              </View>
            </View>}

        </View>
        {item.GeoTag == 'Y' &&
          <TouchableOpacity activeOpacity={0.5} style={customStyle.storel_geotag_btn} onPress={() => { props.navigation.navigate('ShowMap', { storeData: item }) }} >
            <MapIcon width={30} height={30} />
          </TouchableOpacity>
        }
        {item.GeoTag == 'N' &&
          <TouchableOpacity activeOpacity={1} style={customStyle.storel_geotag_btn} onPress={() => { }} >
            <Entypo name='location-pin' size={30} color={'#b4b4b4'} />
          </TouchableOpacity>
        }
      </View>
    </TouchableOpacity>
  );
});

function StoreList(props) {
  const route = useRoute();
  const ST = props.StaticText || {};
  // get all theme styles acc to current theme set 
  const PageTheme = GetPageTheme(props.DarkMode, route.name);
  const customStyle = customStyles(props.DarkMode, route.name);
  const [loaderTitle, setLoaderTitle] = useState();
  const [processing, setProcessing] = useState((props.isDataDownloaded ? true : false));
  const [isAdhocScreen, setIsAdhocScreen] = useState(false);
  const [isBeatPlan, setIsBeatPlan] = useState(false);
  const [isNonMerchan, setIsNonMerchan] = useState(false);
  const [isNonProg, setIsNonProg] = useState(false);
  const [isStoreSearch, setIsStoreSearch] = useState(false);
  const [nodataFound, setNodataFound] = useState(false);
  const [showStoreVisitModal, setShowStoreVisitModal] = useState(false);
  const [showGeoTagModal, setShowGeoTagModal] = useState(false);
  const [showDistanceModal, setShowDistanceModal] = useState(false);
  const [currentStore, setCurrentStore] = useState({});
  const [storeDistance, setStoreDistance] = useState('0 M');
  const [storeDistanceinM, setStoreDistanceinM] = useState(0);
  const [geoFenceData, setGeoFenceData] = useState({});
  const [showAlert, setShowAlert] = useState(false);
  const [checkOutStore, setCheckOutStore] = useState({});
  const [rerenderdata, setrerenderdata] = useState(false);
  let [state, setState] = useState({ storeList: [] });
  let [stateForSearch, setStateforSearch] = useState({ storeList: [] });
  const [globalStorelist, setGlobalStorelist] = useState([]);
  const [cancelCheckOutStore, setCancelCheckOutStore] = useState({});
  const [showCancelCIModal, setShowCancelCIModal] = useState(false);
  const [searchedItem, setSearchedItem] = useState('');
  const [CheckOutImage, setCheckOutImage] = useState('');
  const [CheckOutImagePath, setCheckOutImagePath] = useState('');
  const [CheckOutImageModal, setCheckOutImageModal] = useState(false);
  const [showImageSaveOp, setShowImageSaveOp] = useState(true);
  const [showCamera, setShowCamera] = useState(false);
  const showCameraRef = useRef(false);
  const [GeoFenceEnable_Checkout, setGeoFenceEnable_Checkout] = useState(false);
  const [GeoFenceRadius_Checkout, setGeoFenceRadius_Checkout] = useState('');
  const [uploadedCount, setUploadedCount] = useState(0);
  const [TotalUpCount, setTotalUpCount] = useState(0);
  const [startUploading, setStartUploading] = useState(false);
  const [UploadingSubText, setUploadingSubText] = useState("");
  const [UploadingText, setUploadingText] = useState("Uploading Data...");
  const [showProgresssBar, setshowProgresssBar] = useState(false);
  const [designation, setDesignation] = useState('');
  const sessionsToUpload = useRef([]);
  const sessionsUploadedCount = useRef(0);
  const sessionsReceived = useRef(0);
  const d1 = new Date();
  const d2 = moment(d1).format('MM/DD/YYYY');

  useEffect(() => {
    setLoaderTitle(ST.Loading + '...');
    console.log('props.isDataDownloaded in storelist:', props.isDataDownloaded);
    let CO_GeoFenceEnable = props.GFEnable_checkout != null ? props.GFEnable_checkout : false;
    let CO_GeoFenceRadius = props.GFRadius_checkout != null ? props.GFRadius_checkout : '';
    setGeoFenceEnable_Checkout(CO_GeoFenceEnable);
    setGeoFenceRadius_Checkout(CO_GeoFenceRadius);
    getData();
    console.log('tettving_some:',"jeeevanp");

    const unsubscribe = props.navigation.addListener('beforeRemove', onBeforeRemove);
    const unsubscribeFocus = props.navigation.addListener('focus', () => {
      checkLocalData();
    });
    const removeIRListener = DeviceEventEmitter.addListener('onGlobalIRImageUpload', (data) => { onIRImageUpload(data) });
    return function cleanup() {
      unsubscribeFocus()
      if (AppName == PerformicsIRAppName && props.IR_CameraEnableOnApp == true) {
        IRLogin.deRegisterReceiver();
      }
      removeIRListener.remove();
      return unsubscribe;
    };
  }, []);

  function onBeforeRemove(e) {
    if (showCameraRef.current == true) {
      e.preventDefault();
      BGUpdateShowCamera(false);
    }
    else {
      return;
    }
  }

  function BGUpdateShowCamera(val) {
    showCameraRef.current = val;
    setShowCamera(val);
  }


  async function calLocatDistance() {
    if (currentStore.Latitude != '' && currentStore.Latitude != null) {
      const hasPermission = await _checkLocationPermission();
      if (hasPermission == true) {
        Geolocation.getCurrentPosition(
          async (position) => {
            let loc = { lat: position.coords.latitude, lng: position.coords.longitude };
            var distance = checkRange(loc.lat, loc.lng, currentStore.Latitude, currentStore.Longitude);
            // console.log('distance=====:',currentStore.Latitude, currentStore.Longitude,loc.lat, loc.lng);
            let dinKM = (distance / 1000);
            let distanceinM = (distance == '' || distance == null || isNaN(distance)) ? ' 0 m' : (dinKM > 1 ? dinKM.toFixed(1) + ' Km' : distance + ' m');
            setStoreDistance(distanceinM);
            setStoreDistanceinM(distance);
            setGeoFenceData({locLat: loc.lat, locLng: loc.lng, storeLat: currentStore.Latitude, storeLng: currentStore.Longitude, distance: distance ,storeId: currentStore.StoreId,VisitDate: d2});
            console.log("GeoFenceEnable", props.GeoFenceEnable, "GeoFenceRadius", props.GeoFenceRadius, "distance", distance);
            if (props.GeoFenceEnable == true && distance > props.GeoFenceRadius) {
              setShowDistanceModal(true);
            }
            else {
              props.navigation.navigate('StoreCheckin', { storeData: currentStore, 'isAdhoc': isAdhocScreen, 'isBeat': isBeatPlan, "isNonMerchans": isNonMerchan, isNonProgs: isNonProg, 'isStoreSearch': isStoreSearch, '_fromStoreWise': true });
            }
          },
          (error) => {
            notify(ST.Cannotgetuserposition);
          },
          { enableHighAccuracy: false, distanceFilter: 0, interval: 1000, fastestInterval: 2000 }
        );
      }
      else {
        notify(ST.Pleaseallowlocationpermission);
      }
    }
    else {
      notify(ST.Storelocationnotavailable);
    }

  }

  async function getData() {
    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);
    let desg = loginDetails.Designation || '';
    setDesignation(desg);
    let checkInAvlbl = await checkIfCheckInAvlbl();
    console.log('Store checkInAvlbl: ', checkInAvlbl);
    if (checkInAvlbl.IsAvlbl && checkInAvlbl.IsDataInCoverage == false) {
      await restoreCheckIn(checkInAvlbl.data);
    }

    checkLocalData();
  }

  async function checkIfCheckInAvlbl() {
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    let join = `LEFT OUTER JOIN ${AppTables.COVERAGE_DATA} t2 on t2.STORE_ID=t1.StoreId and t2.JCP_TYPE='Mapping_JourneyPlan' `;
    let q = `Select t1.*,'Mapping_JourneyPlan' as JCP_TYPE,(CASE WHEN t2.STORE_ID is null THEN 0 ELSE 1 END ) as IsCheckInAvlbl  from Mapping_JourneyPlan t1 ${join} where t1.VisitDate='${d2}' and t1.UploadStatus='I'`
    let join2 = `LEFT OUTER JOIN ${AppTables.COVERAGE_DATA} t2 on t2.STORE_ID=t1.StoreId and t2.JCP_TYPE='Adhoc_JourneyPlan' `;
    let q2 = `Select t1.*,'Adhoc_JourneyPlan' as JCP_TYPE,(CASE WHEN t2.STORE_ID is null THEN 0 ELSE 1 END ) as IsCheckInAvlbl from Adhoc_JourneyPlan t1 ${join2} where t1.VisitDate='${d2}' and t1.UploadStatus='I'`
    let join3 = `LEFT OUTER JOIN ${AppTables.COVERAGE_DATA} t2 on t2.STORE_ID=t1.StoreId and t2.JCP_TYPE='JourneyPlan_RouteWise' `;
    let q3 = `Select t1.*,'JourneyPlan_RouteWise' as JCP_TYPE,(CASE WHEN t2.STORE_ID is null THEN 0 ELSE 1 END ) as IsCheckInAvlbl from JourneyPlan_RouteWise t1 ${join3} where t1.VisitDate='${d2}' and t1.UploadStatus='I'`
    let join4 = `LEFT OUTER JOIN ${AppTables.COVERAGE_DATA} t2 on t2.STORE_ID=t1.StoreId and t2.JCP_TYPE='NonMerchandising_JourneyPlan' `;
    let q4 = `Select t1.*,'NonMerchandising_JourneyPlan' as JCP_TYPE,(CASE WHEN t2.STORE_ID is null THEN 0 ELSE 1 END ) as IsCheckInAvlbl from NonMerchandising_JourneyPlan t1 ${join4} where t1.VisitDate='${d2}' and t1.UploadStatus='I'`
    let join5 = `LEFT OUTER JOIN ${AppTables.COVERAGE_DATA} t2 on t2.STORE_ID=t1.StoreId and t2.JCP_TYPE='NonProgram_JourneyPlan' `;
    let q5 = `Select t1.*,'NonProgram_JourneyPlan' as JCP_TYPE,(CASE WHEN t2.STORE_ID is null THEN 0 ELSE 1 END ) as IsCheckInAvlbl from NonProgram_JourneyPlan t1 ${join5} where t1.VisitDate='${d2}' and t1.UploadStatus='I'`
    let join6 = `LEFT OUTER JOIN ${AppTables.COVERAGE_DATA} t2 on t2.STORE_ID=t1.StoreId and t2.JCP_TYPE='StoreSearch_JourneyPlan' `;
    let q6 = `Select t1.*,'StoreSearch_JourneyPlan' as JCP_TYPE,(CASE WHEN t2.STORE_ID is null THEN 0 ELSE 1 END ) as IsCheckInAvlbl from StoreSearch_JourneyPlan t1 ${join6} where t1.VisitDate='${d2}' and t1.UploadStatus='I'`

    let checkPJPData = await props.executeSelQuery(q, '2');
    if (!checkPJPData.IsAvlbl) {
      let checkAdhocData = await props.executeSelQuery(q2, '2');
      if (!checkAdhocData.IsAvlbl) {
        let checkRouteData = await props.executeSelQuery(q3, '2', props.ShowBeatPlanList == true);
        if (!checkRouteData.IsAvlbl) {
          let checkNonMerData = await props.executeSelQuery(q4, '2', props.ShowNonMerList == true);
          if (!checkNonMerData.IsAvlbl) {
            let checkNonProgData = await props.executeSelQuery(q5, '1', props.ShowNonProgram == true);
            if (!checkNonProgData.IsAvlbl) {
              let checkShowStoreSearchData = await props.executeSelQuery(q6, '1', props.ShowStoreSearch == true);
              return checkShowStoreSearchData;
            } else {
              return checkNonProgData;
            }
          } else {
            return checkNonMerData;
          }
        }
        else {
          return checkRouteData;
        }
      }
      else {
        return checkAdhocData;
      }
    }
    else {
      return checkPJPData;
    }

  }

  async function executeSelQuery(q = '', type = '1', isTableAvlbl = true) {
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    let obj = { IsAvlbl: false, data: {} };
    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        if (isTableAvlbl) {
          await txn.executeSql(q, [], async function (txn2, txnres2) {
            //  console.log('Data in covergae len:',txnres2.rows.length);     
            if (txnres2.rows.length > 0) {
              // show from local
              let data = txnres2.rows.item(0);
              let IsDataInCoverage1 = data.IsCheckInAvlbl == '1' || data.IsCheckInAvlbl == 1 ? true : false;
              obj.IsAvlbl = true;
              obj.data = data;
              if (type == '2') {
                obj.IsDataInCoverage = IsDataInCoverage1;
              }
              resolve(obj);
            }
            else {
              resolve(obj);
            }
          }, function (Etxn, txnerr) { console.log(txnerr); resolve(obj); });
        }
        else {
          resolve(obj);
        }
      });

    }).then((val) => {
      return val;
    }).catch((err) => {
      return obj;
    });
  }

  async function restoreCheckIn(item) {
    console.log('restoreCheckIn');
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        let { StoreId, VisitDate, MID, Latitude, Longitude, UploadStatus, InTime, OutTime, JCP_TYPE } = item;
        let JcpType = JCP_TYPE;
        let In_Time = (InTime != '' && InTime != null && InTime != '00:00:00' && InTime != '00:00') ? moment(InTime, "HH:mm:ss").format('MM/DD/YYYY HH:mm:ss') : '';
        let Out_Time = (OutTime != '' && OutTime != null && OutTime != '00:00:00' && OutTime != '00:00') ? moment(OutTime, "HH:mm:ss").format('MM/DD/YYYY HH:mm:ss') : '';
        let CHECKOUT_TIME = (Out_Time != '' && Out_Time != null) ? Out_Time : In_Time;
        // add store Coverage data
        let q = `delete from ${AppTables.COVERAGE_DATA} where STORE_ID='${StoreId}' and VISIT_DATE='${VisitDate}' `;
        let values = ` ('${StoreId}','${VisitDate}','${Latitude}','${Longitude}','','${CHECKOUT_TIME}','','0','','','','${MID}','${JcpType}','${d2}')`;
        let insert_q = ` insert into ${AppTables.COVERAGE_DATA}(STORE_ID,VISIT_DATE ,LATITUDE,LONGITUDE,IMAGE,CHECKOUT_TIME,CHECKOUT_IMAGE,REASON_ID,REASON,REMARK,STORE_FLAG,MID,JCP_TYPE,ADDED_DATE) values ${values}`;

        console.log('insert_q:', insert_q);
        await txn.executeSql(q, [], async function (txn2, txnres2) {
          console.log('store coverage deleted');
          await txn.executeSql(insert_q, [], async function (txn2, txnres3) {
            console.log('InsertCoverageData done');
            // add storeCheckin data
            let q2 = `delete from ${AppTables.CHECKIN_DATA} where STORE_ID='${StoreId}' and VISIT_DATE='${VisitDate}' `;
            let values2 = ` ('${StoreId}','${VisitDate}','${Latitude}','${Longitude}','${In_Time}','','${Out_Time}','','','${JcpType}','${d2}')`;
            let insert_q2 = ` INSERT INTO ${AppTables.CHECKIN_DATA}(STORE_ID,VISIT_DATE,LATITUDE,LONGITUDE,CHECKIN_TIME,CHECKIN_IMAGE,CHECKOUT_TIME,CHECKOUT_IMAGE,REMARK,JCP_TYPE,ADDED_DATE) values ${values2}`;
            console.log('insert_q2:', insert_q2);
            await txn.executeSql(q2, [], async function (txn2, txnres4) {
              console.log('removed');
              await txn.executeSql(insert_q2, [], async function (txn2, txnres5) {
                console.log('checkin data added');
                resolve(true);
              }, function (Etxn, txnerr) { console.log(txnerr); resolve(false); });
            }, function (Etxn, txnerr) { console.log(txnerr); resolve(false); });

          }, function (Etxn, txnerr) { console.log(txnerr); resolve(false); });
        }, function (Etxn, txnerr) { console.log(txnerr); resolve(false); });

      });

    }).then((val) => {
      return val;
    }).catch((err) => {
      return false;
    });
  }


  // 📌 Function to filter stores
  const getFilteredStores = (stores) => {
    return stores
      .filter(store => {
        const hasValidLatLng =
          store.GeoTag !== "N" &&
          store.Latitude &&
          store.Longitude &&
          store.Latitude !== "0" &&
          store.Longitude !== "0";
        return store.UploadStatus === "N" && hasValidLatLng;
      })
      .map(store => ({
        StoreId: store.StoreId,
        latitude: parseFloat(store.Latitude),
        longitude: parseFloat(store.Longitude),
      }));
  };
  async function checkLocalData() {
    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);
    let params = props.route.params ? props.route.params : {};
    let isAdhoc = params.isAdhoc || false;
    let isBeat = params.isBeat != null ? params.isBeat : false;
    let isNonMerchan1 = params.isNonMerchans != null ? params.isNonMerchans : false;
    let isNonProgam = params.isNonProgs != null ? params.isNonProgs : false;
    let isStoreSearch1 = params.isStoreSearch != null ? params.isStoreSearch : false;
    setIsAdhocScreen(isAdhoc);
    setIsBeatPlan(isBeat);
    setIsNonMerchan(isNonMerchan1);
    setIsNonProg(isNonProgam)
    setIsStoreSearch(isStoreSearch1)
    console.log("check_flag", isAdhoc, isBeat, isNonMerchan1, isNonProgam, isStoreSearch1)
    let myStoreWithAllFieldsQuery = await Q_getMyStoresList(isAdhoc, isBeat, isNonMerchan1, isNonProgam, isStoreSearch1);
    console.log('myStoreWithAllFieldsQuery:', myStoreWithAllFieldsQuery);
    let CheckInRunning = false
    await db.transaction(async function (txn) {
      await txn.executeSql(myStoreWithAllFieldsQuery, [], async function (txn2, txnres2) {
        console.log("size", txnres2.rows.length)
        if (txnres2.rows.length > 0) {
          // show from local
          var storeArr = [];
          for (var i = 0; i < txnres2.rows.length; i++) {
            let sdata = txnres2.rows.item(i);
            let { InTime, OutTime, UploadStatus, StoreId, MID, MenuCount, MenuDoneCount, StoreName, PS_MenuDoneCount } = sdata;
            console.log("upload_status_new", UploadStatus, StoreId, InTime)
            if (UploadStatus === "I") {
              CheckInRunning = true
            }
            if (InTime != null && InTime != "" && InTime != "00:00:00") {
              sdata.CheckInTime = InTime;
            } else {
              let time = sdata.CheckInTime != null && sdata.CheckInTime != '' ? moment(sdata.CheckInTime, "MM/DD/YYYY HH:mm:ss").format('HH:mm:ss') : '';
              let time2 = sdata.CheckOutTime != null && sdata.CheckOutTime != '' ? moment(sdata.CheckOutTime, "MM/DD/YYYY HH:mm:ss").format('HH:mm:ss') : ''; //new Date(sdata.CheckOutTime)
              let In_Time = (time == '' && UploadStatus != '' && UploadStatus != 'N') ? InTime : time;
              sdata.CheckInTime = In_Time;
            }

            if (OutTime != null && OutTime != "" && OutTime != "00:00:00") {
              sdata.CheckOutTime = OutTime;
            } else {
              let time2 = sdata.CheckOutTime != null && sdata.CheckOutTime != '' ? moment(sdata.CheckOutTime, "MM/DD/YYYY HH:mm:ss").format('HH:mm:ss') : ''; //new Date(sdata.CheckOutTime)
              let Out_Time = (time2 == '' && UploadStatus != '' && UploadStatus != 'N' && UploadStatus != 'I') ? OutTime : time2;
              sdata.CheckOutTime = Out_Time;
            }

            let allDone = false;
            // console.log("props.PartialSaveAllow",props.PartialSaveAllow)
            // Menu wil be counted as done if and only if all available data row is filled - (This Will work only if partial save is allowed)
            if (props.PartialSaveAllow == true) {
              allDone = PS_MenuDoneCount != null && PS_MenuDoneCount != null && MenuCount == PS_MenuDoneCount;
            }
            else { // Menu wil be counted as done if any available data row is filled
              allDone = MenuCount != null && MenuDoneCount != null && MenuCount == MenuDoneCount;
            }
            sdata.allDone = allDone;
            sdata.MenuListLen = MenuCount;
            storeArr.push(sdata);
            // console.log("sdata------", sdata)
            if (i == (txnres2.rows.length - 1)) {
              console.log("test1")
              if (props.StoreRouteView && !isAdhoc && !isBeat && !isNonMerchan1 && !isNonProgam && !isStoreSearch1) {
                if (CheckInRunning == false) {
                  console.log("test2")
                  ///filter stores if have UploadStatus N and Lat,longt both or not zero
                  let mergedData = storeArr
                  const filteredStores = getFilteredStores(storeArr);
                  const distancesStores = await fetchDistanceMatrix(filteredStores)
                  console.log("distancesStores-----", distancesStores)
                  if (distancesStores?.status === "SUCCESS") {
                    //fetch distances for same
                    mergedData = await mergeStoreDistances(storeArr, distancesStores?.data)
                    // Save mergedAll
                    await AsyncStorage.setItem("storeArr", JSON.stringify(mergedData?.mergedAll || []));
                    console.log("Filtered Stores:", mergedData);
                  }
                  storeArr = mergedData?.mergedAll || storeArr
                } else {
                  // Get mergedAll
                  const savedStores = await AsyncStorage.getItem("storeArr");
                  const parsedStores = savedStores ? JSON.parse(savedStores) : [];
                  storeArr = storeArr || parsedStores
                }
              }
              //console.log("storeList-------", storeArr)
              setState({ storeList: storeArr });
              setGlobalStorelist(storeArr);
              setProcessing(false);
            }
          }
        }
        else {
          if (isStoreSearch1 == true) {
            setState({ storeList: [] });
            setProcessing(false);
          }
          else {
            setProcessing(false); notify(ST.Nodatafound); setNodataFound(true);
          }
        }
      }, function (Etxn, txnerr) { console.log("Errorrr",txnerr); setProcessing(false); notify(ST.Nodatafound); setNodataFound(true); });
    });
  }

  async function getDailyMenu(storeData1) {
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    let { StoreId, ChannelId, RegionId, StoreTypeId } = 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 allDone = true;
            for (var i = 0; i < txnres.rows.length; i++) {
              let data = txnres.rows.item(i);
              let isAvlbl = await checkAvailability(storeData1, data);
              let isDone = await updateStatus(storeData1, data, isAvlbl);

              if (isAvlbl && !isDone) {
                allDone = false;
                resolve(allDone);
                break;
              }
              if (i == (txnres.rows.length - 1)) {
                resolve(allDone);
              }
            }
          }
          else {
            resolve(true);
          }
        }, function (txnE, txnerr) { console.log(txnerr); resolve(false); },);

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

  }

  async function getMenuList(storeData1) {
    let { StoreId, ChannelId, RegionId, StoreTypeId } = 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();   
            // 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 checkAvailability(storeData1, data) {

    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        let q2 = getAvailblQuery(data.ScreenName, storeData1);
        if (q2 != '' && q2 != null) {

          await txn.executeSql(q2, [], async function (txn2, txnres2) {
            let isAvlbl = getIfAvlbl(data.ScreenName, txnres2, storeData1);
            resolve(isAvlbl);
          }, function (txnE, txnerr) { console.log(txnerr); resolve(false); },);
        }
        else {
          let isAvlbl = getIfAvlbl(data.ScreenName, {}, storeData1);
          resolve(isAvlbl);
        }
      });
    }).then((val) => {
      return val;
    }).catch((err) => {
      console.log(err);
      return false;
    });
  }


  async function updateStatus(storeData1, data, isAvlbl) {
    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        let q2 = getQuery(data.ScreenName, storeData1);
        if (q2 != '' && q2 != null && isAvlbl == true) {
          await txn.executeSql(q2, [], async function (txn2, txnres2) {
            let isDone = await getIfKPIDone(data.ScreenName, txnres2, storeData1);
            resolve(isDone);

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

  }

  async function onCheckOut(storeData1) {
    // let isAlldone=await getDailyMenu(storeData1);
    let { MinTimeTaken, CheckInTime } = storeData1;
    if (MinTimeTaken != null && MinTimeTaken != '' && parseInt(MinTimeTaken) > 0) {
      let checkin_t = moment(new Date()).format('MM/DD/YYYY') + ' ' + CheckInTime;
      let checkin_t_m = moment(checkin_t).format('MM/DD/YYYY HH:mm:ss');
      let CalTime = moment().diff(checkin_t, 'minutes');
      if (CalTime < parseInt(MinTimeTaken)) {
        notify('You are not allowed to Check-out before ' + MinTimeTaken + ' Minutes from Check-in time. Your Current Duration is ' + CalTime + ' Minutes.');
        return;
      }
    }

    if (storeData1.allDone == true) {
      setCheckOutStore(storeData1);
      if (props.isInternetAvailable == true) {
        setShowAlert(true);
      }
    }
    else {
      notify(ST.PleasefillallKPI, false);
    }
  }

  function onSaveCancel() {
    setShowAlert(false);
  }

  async function getLocOnCheckout(type = "1") {
    if (props.isInternetAvailable == false) {
      return;
    }
    setShowAlert(false);
    setLoaderTitle(ST.Gettinglocation + '...');
    setProcessing(true);

    Geolocation.getCurrentPosition(
      async (position) => {
        let { latitude, longitude } = position.coords;
        let loc = { lat: latitude, lng: longitude };
        var distance = checkRange(loc.lat, loc.lng, checkOutStore.Latitude, checkOutStore.Longitude);
        console.log('COut distance:', distance);
        if (GeoFenceEnable_Checkout == true) {
          if (GeoFenceRadius_Checkout != '' && distance > GeoFenceRadius_Checkout) {
            let locData = { "UserId": props.UserId, 'MID': checkOutStore.MID, "StoreId": checkOutStore.StoreId, "StoreLatitude": checkOutStore.Latitude, 'StoreLongitude': checkOutStore.Longitude, 'currentLatitude': latitude, 'currentLongitude': longitude }
            await sendUserLocation(locData);
            setProcessing(false);
            notify(ST.Youcannotcheckout + ' ' + ST.Youarenotwithinthealloweddistancefromthestore + ' ' + GeoFenceRadius_Checkout + ' m', 'LONG')
          }
          else {
            setProcessing(false);
            checkOutAfterLoc(loc, type);
          }
        }
        else {
          setProcessing(false);
          checkOutAfterLoc(loc, type);
        }
      },
      (error) => {
        notify(ST.Cannotgetuserposition);
        setProcessing(false);
      },
      { enableHighAccuracy: true, distanceFilter: 0, interval: 1000, fastestInterval: 2000 }
    );
  }

  async function checkOutAfterLoc(loc, type = '1') {
    let CheckOut_PhotoReq = props.CheckOut_PhotoReq != null ? props.CheckOut_PhotoReq : false;
    // type='2' means checkout image has been captured already and now we are again checking the user location 
    if (type != '2' && CheckOut_PhotoReq) {
      setShowAlert(false);
      setCheckOutImageModal(true);
    }
    else {
      if (props.isInternetAvailable == true) {
        UpdateCheckOutStatus(loc);
      }
    }
  }

  async function sendUserLocation(data = {}) {
    console.log("sendUserLocation");
    const url = props.baseurl + getMethodName(METHODS.UPLOADJSON_METHOD);
    let postData = {
      'MID': checkOutStore.MID,
      'Keys': "GeoFenceDataStoreList",
      'JsonData': JSON.stringify(data),
      'UserId': props.UserId,
    }
    console.log(url, postData);
    return await UploadData2(url, postData)
      .then(async (res) => {
        if (res.UploadJsonResult != null && res.UploadJsonResult == 'Success') {
          // console.log(KPIdata+' uploaded');
          return true;
        }
        return false;
      })
      .catch(async (err) => {
        return false;
      });
  }

  //========================================================
  function getEmpStoreCheckIn(tbname, VisitDate, stored) {
    return new Promise((resolve, reject) => {
      var query = "SELECT * FROM EMPSTORE_CHECKIN WHERE JCP_TYPE = ? AND VISIT_DATE = ? AND STORE_ID = ?";
      db.transaction((tx) => {
        tx.executeSql(query, [tbname, VisitDate, stored], (tx, results) => {
          if (results.rows.length > 0) {
            resolve(results.rows._array || results.rows); // Resolving with fetched data
          } else {
            resolve([]); // Resolving with empty array if no records found
          }
        }, (error) => {
          console.log("Error executing query:", error);
          reject(error); // Rejecting in case of an error
        });
      });
    });
  }

  async function UpdateCheckOutStatus(loc) {
    try {
      setTotalUpCount(0);
      setshowProgresssBar(false);
      setUploadingText(ST.UpdatingCheckoutStatus + '...');
      setStartUploading(true);
      let { StoreId, MID } = checkOutStore;
      let CheckOut_PhotoReq = props.CheckOut_PhotoReq != null ? props.CheckOut_PhotoReq : false;
      let d = new Date();
      let d2 = moment(d).format('MM/DD/YYYY');
      let d3 = moment(d).format('MM/DD/YYYY HH:mm:ss');
      let loginInfo = await get_item('loginInfo');
      const loginDetails = JSON.parse(loginInfo);
      let data1 = {
        UserId: loginDetails.UserId,
        StoreId: StoreId,
        Latitude: loc.lat,
        Longitude: loc.lng,
        Checkout_Date: d2,
        CheckOutImage: CheckOutImage,
      };

      const url = props.baseurl + getMethodName(METHODS.CHECKOUTDETAIL_METHOD);
      const url1 = (props.imageUploadUrl || URL_IMAGE) + getMethodName(METHODS.UPLOADIMAGES_METHOD);
      console.log(url, data1);
      // Await the result of the upload
      let res = await UploadData2(url, data1);
      console.log('StoreCheckOutSup1:', res, 'MID:', MID);
      if (!res.error) {
        if (res == 1) {
          setCheckOutImage('');
          setCheckOutImagePath('');
          let data = { checkout_image: '' };
          console.log("jeevanp", data);
          const isCheckOutUpdated = await UpdateStoreCheckOut(data);
          if (props.isInternetAvailable == false) {
            return
          }

          if (isCheckOutUpdated == true) {
            let datan = {
              StoreId: StoreId,
              UploadStatus: 'C',
              tbname: isBeatPlan
                ? 'JourneyPlan_RouteWise'
                : isAdhocScreen
                  ? 'Adhoc_JourneyPlan'
                  : isNonMerchan
                    ? 'NonMerchandising_JourneyPlan'
                    : isNonProg
                      ? 'NonProgram_JourneyPlan'
                      : isStoreSearch
                        ? 'StoreSearch_JourneyPlan'
                        : 'Mapping_JourneyPlan',
            };

            var InTime = moment(d).format('HH:mm:ss');
            InTime = await getEmpStoreCheckIn(datan.tbname, d2, datan.StoreId)
              .then((data) => {
                console.log("Fetched Data:", data[0], data[0].CHECKIN_TIME);
                console.log(moment(data[0].CHECKIN_TIME).format());
                InTime = moment(data[0].CHECKIN_TIME, "MM/DD/YYYY HH:mm:ss").format("HH:mm:ss")
                console.log('datan:', InTime);
                return InTime; // Return the formatted time
              })
              .catch((error) => {
                console.error("Error fetching data:", error);
              });

            // Adding extra fields dynamically
            let outtime = moment(d).format('HH:mm:ss');
            datan.InTime = InTime;
            datan.outtime = outtime;
            console.log('datan:', datan);
            const isUpdated = await UpdateStoreStatus(props, datan);
            if (isUpdated == true) {
              let outtime = moment(d).format('HH:mm:ss');
              await updateStoreStatuslocal('C', checkOutStore, false, true, outtime);
              UploadOnCheckOut(loc);
            } else {
              setStartUploading(false); //setProcessing(false);
              notify(ST.Erroroccurwhilecheckout, 'LONG');
            }
          } else {
            setStartUploading(false);
            notify(ST.Erroroccurwhilecheckout, 'LONG');
          }
        } else {
          if (CheckOutImagePath != '') {
            await RNFS.unlink(CheckOutImagePath);
          }
          setCheckOutImage('');
          setCheckOutImagePath('');
          notify(ST.Somethingwentwrong, 'SHORT');
          setStartUploading(false); //setProcessing(false);
        }
      } else {
        if (res.error == true) {
          setStartUploading(false);
          return;
          // Stop the execution and exit the function
        }
        if (CheckOutImagePath != '') {
          await RNFS.unlink(CheckOutImagePath);
          notify(res.errorMsg, 'SHORT');
        }
        setCheckOutImage('');
        setCheckOutImagePath('');
        notify(res.errorMsg, 'SHORT');
        setStartUploading(false); //setProcessing(false);
      }
    } catch (err) {
      if (CheckOutImagePath != '') {
        await RNFS.unlink(CheckOutImagePath);
      }
      setCheckOutImage('');
      setCheckOutImagePath('');
      notify('Error occurred while updating checkout status', 'SHORT');
      setStartUploading(false); //setProcessing(false);
    }
  }
  async function updateStoreStatuslocal(status, storeData1, updateCheckin = false, uCOut = false, cout_time = '') {
    let storeArr = state.storeList;
    let sdata_index = storeArr.findIndex(i => i.StoreId == storeData1.StoreId);
    if (sdata_index >= 0) {
      let sdata = storeArr[sdata_index];
      sdata['UploadStatus'] = status;
      if (updateCheckin == true) {
        sdata['CheckInTime'] = '';
      }
      if (uCOut == true) {
        sdata['CheckOutTime'] = cout_time;
      }
      storeArr[sdata_index] = sdata;
      setState({ ...state, storeArr });
      setGlobalStorelist(storeArr);
      setrerenderdata(!rerenderdata);
    }
  }

  async function UpdateStoreCheckOut(data) {
    if (props.isInternetAvailable == true) {
      console.log("jeevanp", data);
      let calculateDate = moment(new Date()).format('MM/DD/YYYY');
      let calculateTym = moment(new Date()).format('HH:mm:ss');
      console.log("dateandtime--", calculateDate + "\n" + calculateTym)
      let CheckOut_PhotoReq = props.CheckOut_PhotoReq != null ? props.CheckOut_PhotoReq : false;
      return new Promise((resolve, reject) => {
        db.transaction(async function (txn) {
          let q2 = `UPDATE ${AppTables.COVERAGE_DATA} SET CHECKOUT_TIME='${calculateTym}', CHECKOUT_IMAGE='${CheckOut_PhotoReq ? CheckOutImage : ''}' WHERE STORE_ID='${checkOutStore.StoreId}' and VISIT_DATE='${calculateDate}' `;
          await txn.executeSql(q2, [], async function (txn2, txnres2) {
            console.log('store coverage updated');
          }, function (Etxn, txnerr) { console.log(txnerr); resolve(false); });

          let q = `UPDATE ${AppTables.CHECKIN_DATA} SET CHECKOUT_TIME='${calculateTym}', CHECKOUT_IMAGE='${CheckOut_PhotoReq ? CheckOutImage : ''}' WHERE STORE_ID='${checkOutStore.StoreId}' and VISIT_DATE='${calculateDate}' `;
          await txn.executeSql(q, [], async function (txn2, txnres2) {
            console.log('store checkout updated');
            resolve(true);
          }, function (Etxn, txnerr) { console.log(txnerr); resolve(false); });

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


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

  }

  async function UploadCheckoutImageWithP(loc, tbname, storeData) {
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    let pdata = {
      "Mid": storeData.MID,
      "StoreId": storeData.StoreId,
      "VisitDate": d2,
      "Latitude": (loc.lat || ''),
      "Longitude": (loc.lng || ''),
      "ReasonId": 0,
      "Remark": "",
      "Appversion": AppVersion,
      "UploadStatus": "P",
      "UserName": (props.UserId || ''),
      "ImageName": storeData.IMAGE != null ? storeData.IMAGE : '',
      "CheckoutImage": storeData.CHECKOUT_IMAGE != null && storeData.CHECKOUT_IMAGE != 'undefined' ? storeData.CHECKOUT_IMAGE : '',
    }

    const url = props.baseurl + getMethodName(METHODS.GETCOVERAGE_METHOD);
    console.log(url, pdata);
    return await UploadData2(url, pdata)
      .then(async (res) => {
        console.log('status uploadres:', res);
        if (parseInt(res) > 0) {
          let datan1 = { StoreId: storeData.StoreId, UploadStatus: 'P', tbname: tbname };
          let isUpdated = await UpdateStoreStatus(props, datan1);
          return isUpdated;
        }
        else {
          return false;
        }

      })
      .catch((err) => {
        console.log(err);
        return false;
      });
  }

  async function UploadOnCheckOut(loc) {
    try {
      console.log('UploadOnCheckOut');
      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);
      let PJPStores = await getPJPStoresData('Mapping_JourneyPlan', [], d2);
      let AdhocSTores = await getPJPStoresData('Adhoc_JourneyPlan', PJPStores, d2);
      let routeWise = await getPJPStoresData('JourneyPlan_RouteWise', AdhocSTores, d2);
      let nonProgJau = await getPJPStoresData('NonProgram_JourneyPlan', routeWise, d2);
      let storeSearchJP = await getPJPStoresData('StoreSearch_JourneyPlan', nonProgJau, d2);
      let AllStores = await getPJPStoresData('NonMerchandising_JourneyPlan', storeSearchJP, d2);
      console.log('stores to upload:', AllStores.length);

      await db.transaction(async function (txn) {
        console.log('stores to upload:', AllStores.length);
        if (AllStores.length > 0) {
          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, IMAGE, JCP_TYPE } = data;
            let MenuList = await getMenuList(data);
            let allKPIs = await getKPIS(MenuList, props);
            let totalUpC = MenuList.length - 1; // keep 1 less to actual count as DownloadDataModal shows it as provided_value+1
            // get all checkout ids data
            console.log('UploadStatus before Start Uploading Data :', UploadStatus);
            setTotalUpCount(totalUpC);
            setshowProgresssBar(false);
            setUploadingSubText("Uploading Data for Store:" + StoreId);
            if (UploadStatus == 'C') {
              let isUploaded_P_Status = await uploadStoreStatus(props, data, 'P', JCP_TYPE);
              // let isUploaded_P_Status=await UploadCheckoutImageWithP(loc,JCP_TYPE,data);
              console.log('isUploaded_P_Status:', isUploaded_P_Status);

              if (isUploaded_P_Status) {
                await updateStoreStatuslocal('P', data);
                setTotalUpCount(totalUpC);
                setshowProgresssBar(true);
                setUploadingText(ST.UploadingData + '...');
                await uploadAfter_P_status(index, AllStores, data, MenuList, allKPIs, JCP_TYPE);
              }
              else {
                // Stop processing if all stores uploaded
                if (index == AllStores.length - 1) {
                  // setProcessing(false);
                  setStartUploading(false);
                  notify(ST.Erroroccurwhileuploadingdata, 'LONG');
                }
              }
            }
            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);

              if (allFilesToUpload.length > 0) {
                await UploadDataWithImages(index, AllStores, data, MenuList, allKPIs, JCP_TYPE, allFilesToUpload);
              }
              else {
                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);
            }
            else if (UploadStatus == 'L') {
              setshowProgresssBar(false);
              setUploadingText(ST.UploadingData + '...');
              let isAllUploaded_S = await uploadStoreStatus(props, data, 'U', JCP_TYPE);
              if (isAllUploaded_S == true) {
                await updateStoreStatuslocal('U', data);
                notify(ST.Alldatauploadedfor + ' ' + StoreName, 'SHORT');
                if (index == AllStores.length - 1) {
                  // setProcessing(false);
                  // setStartUploading(false);
                  await onUploadComplete();
                  console.log('upload U deleteStore 2', props.StoreRouteView)
                  await deleteStore(data, "U");
                  if (props.StoreRouteView == true || props.StoreRouteView == 1) checkLocalData();

                }
              }
              else {
                if (index == AllStores.length - 1) {
                  // setProcessing(false);
                  setStartUploading(false);
                  notify(ST.Erroroccurwhileuploadingdata, 'LONG');
                  if (props.StoreRouteView == true || props.StoreRouteView == 1) checkLocalData();
                }
              }
            }
            else {
              console.log("No UploadStatus case found while uploading");
            }
          }

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

  async function uploadAfter_P_status(index, AllStores, data, MenuList, allKPIs, JCP_TYPE) {
    let { StoreName } = data;
    if (MenuList.length > 0) {
      // Upload data with Images
      let allFilesToUpload = await uploadAllData(props, data, allKPIs, props.UserId, JCP_TYPE, true, UpdateUploadCountLocal);
      await updateStoreStatuslocal('D', data);
      await UploadDataWithImages(index, AllStores, data, MenuList, allKPIs, JCP_TYPE, allFilesToUpload);
    }
    else if (MenuList.length == 0) {
      let allFilesToUpload = await uploadAllData(props, data, allKPIs, props.UserId, JCP_TYPE, true, UpdateUploadCountLocal);
      await updateStoreStatuslocal('D', data);
      await UploadDataWithImages(index, AllStores, data, MenuList, allKPIs, JCP_TYPE, allFilesToUpload);

    }
    else {
      //  Upload statua u if no data exists
      let allfiles = await getAllFolderImages();
      console.log('allFiles => ', allfiles)
      if (allfiles.length > 0) {
        console.log('upload allFiles data => ')
        await UploadDataWithImages(index, AllStores, data, MenuList, allKPIs, JCP_TYPE, allfiles);
      }
      let isAllUploaded_S = await uploadStoreStatus(props, data, 'U', JCP_TYPE);
      if (isAllUploaded_S == true) {
        await updateStoreStatuslocal('U', data);
        notify(ST.Alldatauploadedfor + ' ' + StoreName, 'SHORT');
        if (index == AllStores.length - 1) {
          // setProcessing(false);
          await onUploadComplete();
          console.log('upload U deleteStore 3', props.StoreRouteView)
          await deleteStore(data, "U");
          if (props.StoreRouteView == true || props.StoreRouteView == 1) checkLocalData();
        }
      }
      else {
        if (index == AllStores.length - 1) {
          // setProcessing(false);
          setStartUploading(false);
          notify(ST.Erroroccurwhileuploadingdata, 'LONG');
          if (props.StoreRouteView == true || props.StoreRouteView == 1) checkLocalData();
        }
      }
    }
  }

  async function UploadDataWithImages(index, AllStores, data, MenuList, allKPIs, JCP_TYPE, allFilesToUpload) {
    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 + '...');
      console.log('set loader title');
      let isAllUploaded = await uploadAllImages(props, data, allFilesToUpload, JCP_TYPE, {}, UpdateUploadCountLocal);
      if (isAllUploaded == true) {
        await updateStoreStatuslocal('U', data);
        notify(ST.Alldataandimagesuploadedfor + ' ' + StoreName, 'SHORT');
        if (index == AllStores.length - 1) {
          // setProcessing(false);
          await onUploadComplete();
          console.log('upload U deleteStore 4', props.StoreRouteView)
          await deleteStore(data, "U");
          if (props.StoreRouteView == true || props.StoreRouteView == 1) checkLocalData();
        }
      } else {
        notify(ST.Cannotuploadimagesfor + ' ' + StoreName, 'SHORT');
        if (index == AllStores.length - 1) {
          // setProcessing(false);
          setStartUploading(false);
          if (props.StoreRouteView == true || props.StoreRouteView == 1) checkLocalData();
        }
      }
    }
    else {
      let isupdatedU = await uploadStoreStatus(props, data, 'U', JCP_TYPE);
      console.log('on no files found to upload , isupdated::', isupdatedU);
      if (isupdatedU) {
        await updateStoreStatuslocal('U', data);
        notify(ST.Alldatauploadedfor + ' ' + StoreName, 'SHORT');
        if (index == AllStores.length - 1) {
          await onUploadComplete();
          console.log('upload U deleteStore 5', props.StoreRouteView)
          await deleteStore(data, "U");
          if (props.StoreRouteView == true || props.StoreRouteView == 1) checkLocalData();

        }
      }
      else if (index == AllStores.length - 1) {
        // setProcessing(false);
        setStartUploading(false);
        if (props.StoreRouteView == true || props.StoreRouteView == 1) checkLocalData();
      }
    }
  }

  async function onUploadComplete() {
    // Sync all IR sessionsfor all stores at onces when all data and images fully uploaded
    // setLoaderTitle('Syncing IR Sessions Status...');
    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);
    let { isUploadStarted, noDataFound, AllDataUploaded, success, sessionList, sessionListWithDetails } = sync_result;

    if (!success) {
      notify('Cannot Upload Data! Something went wrong.');
      setStartUploading(false);
    }
    else {
      if (noDataFound) {
        notify('No session to upload!');
        setStartUploading(false);
      }
      else {
        if (!isUploadStarted && AllDataUploaded) {
          notify('All images synced! No session to upload.');
          setStartUploading(false);
        } else if (isUploadStarted) {
          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); // 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];
            await 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] : {};
    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 }
    console.log('onGlobalIRImageUpload sessionObj:', sessionObj);
    // 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;
        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('Images Log Uploaded1');
          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('Images Log  Uploaded2');
          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('Images Log  Uploaded3');
        notify("Images Log uploaded for session:" + sessionId);
      }
      else {
        console.log('cannot Uploaded image');
        notify("cannot upload log for session:" + sessionId);
      }

    }

    console.log("check snum and su_num:", snum, su_num, sessionsToUpload.current.length);
    // if last broadcast received either uploaded or not, update the processing status to false
    if (snum == sessionsToUpload.current.length) {
      setProcessing(false);
      setStartUploading(false);
      console.log('Deregister event when last received');
      IRLogin.deRegisterReceiver();
    }

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

  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');

            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 Upload Status');
              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 = {}) {
    console.log("LogImageUpload");
    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 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 getPJPStoresData(tbname, Stores = [], d2) {
    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 qt = `Select t1.*,t2.REASON_ID,t2.IMAGE,t2.CHECKOUT_IMAGE,t2.JCP_TYPE from ${tbname} t1 ${join} where t1.VisitDate='${d2}' and t1.UploadStatus in ('C','P','D','L')`

        console.log("queryyyyy", qt);
        await txn.executeSql(qt, [], async function (txn2, txnres2) {
          if (txnres2.rows.length > 0) {

            for (var i = 0; i < txnres2.rows.length; i++) {
              let data = txnres2.rows.item(i);
              console.log("queryyyyy", data);
              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 storeVisited() {
    let checkPJPData = await executeSelQuery(`select * from ${AppTables.COVERAGE_DATA} Where VISIT_DATE='${currentStore.VisitDate}' and STORE_ID = ${currentStore.StoreId}`);
    setShowStoreVisitModal(false);
    if (currentStore.GeoTag == 'N') {
      setShowGeoTagModal(true);
    } else if (currentStore.UploadStatus == 'N' || (currentStore.UploadStatus == 'I' && checkPJPData.IsAvlbl == false) || currentStore.UploadStatus == '') {
      calLocatDistance();
    }
  }

  async function storeNotVisited() {
    setShowStoreVisitModal(false);
    props.navigation.navigate('StoreNonWorkingReasons', { storeData: currentStore, 'isAdhoc': isAdhocScreen, 'isBeat': isBeatPlan, 'isNonMerchans': isNonMerchan, isNonProgs: isNonProg, isStoreSearch: isStoreSearch });
  }

  async function onVisitCancel() {
    setLoaderTitle(ST.DeletingCheckInData + '...')
    setShowCancelCIModal(false);
    setProcessing(true);
    let { MID, StoreId } = cancelCheckOutStore;
    let postdata = { 'Mid': MID, "UserName": props.UserId, }

    const url = props.baseurl + getMethodName(METHODS.DELETECOVERAGE_METHOD);
    console.log(url, postdata);
    await UploadData2(url, postdata)
      .then(async (res) => {
        console.log('delete coverage res:', res);
        if (res == '1') {
          console.log('upload U deleteStore 1')
          let isdeleted = await deleteStore(cancelCheckOutStore, "Cancel");
          if (isdeleted == true) {
            let data = { "StoreId": StoreId, UploadStatus: "N", tbname: (isBeatPlan == true ? 'JourneyPlan_RouteWise' : (isAdhocScreen == true ? 'Adhoc_JourneyPlan' : (isNonMerchan == true ? 'NonMerchandising_JourneyPlan' : isNonProg == true ? 'NonProgram_JourneyPlan' : isStoreSearch == true ? 'StoreSearch_JourneyPlan' : 'Mapping_JourneyPlan'))) };
            let isUpdated = await UpdateStoreStatus(props, data);
            if (isUpdated == true) {
              await updateStoreStatuslocal('N', cancelCheckOutStore, true);
              setProcessing(false);
              notify(ST.CheckInRemoved);
            }
            else {
              setProcessing(false);
              notify(ST.CheckInremovedsuccessfullybutcannotupdatestatus);
            }
          }
          else {
            setProcessing(false);
            notify(ST.CheckInremovedsuccessfullybutcannotupdatestatus);
          }
        }
        else {
          setProcessing(false);
          notify(ST.CannotRemoveCheckIn);
        }

      }).catch(err => {
        console.log('onPage Team error', err);
        setProcessing(false);
        notify(ST.CannotRemoveCheckIn);
      });

  }

  async function deleteStore(storeData1, Status = null) {
    let { StoreId } = storeData1;
    let allQueries = [
      `Delete from ${AppTables.COVERAGE_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.GEOTAG} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.STORE_PROFILE} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.STORE_CHECKLIST} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.STORE_PROFILE_KYC} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.HEADER_BACK_OF_STORE} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.CHILD_BACK_OF_STORE} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.SALES} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.INSERT_OPENINGHEADER_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.STOCK_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.SHARE_OF_SHELF_IMAGE} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.SHARE_OF_SHELF_FACING_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.INSERT_SAMPLED_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.CONTACT_CONVERSION} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.INSERT_ERROR_TRACKING} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.GROOMING_IMAGE_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.ADDITIONAL_VISIBILITY} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.ADDITIONAL_VISIBILITY_STOCK} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.COMPETITION_VISIBILITY} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.COMPETITION_PROMOTION} where STORE_ID='${StoreId}' `,
      // `Delete from ${AppTables.CHECKIN_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.PROMOTION_HEADER_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.PROMOTION_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.PAID_VISIBILITY_HEADER_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.PAID_VISIBILITY_CHILD_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.PAID_VIS_CHECKLIST} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.SURVEY} where STORE_ID='${StoreId}' `,


      `Delete from ${AppTables.SAMPLING_INVENTORY} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.SAMPLING_CUST_TRACK} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.SAMPLING_STOCK_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.SAMPLING_SALE_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.SAMPLING_LIST} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.PROGRAM_HDR_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.PROGRAM_CHILD_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.PROGRAM_IMAGES} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.PROGRAM_STOCK_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.PROMO_HDR_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.PROMO_CHILD_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.PROMO_IMAGES} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.PROMO_STOCK_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.ST_HDR_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.ST_CHILD_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.ST_IMAGES} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.ST_STOCK_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.WINDOW_HDR_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.WINDOW_CHILD_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.WINDOW_IMAGES} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.WINDOW_STOCK_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.WINDOW_IR_IMAGES} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.WINDOW_IRUPLOAD} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.STORE_IMAGES} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.POSM_HDR_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.POSM_CHILD_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.SOS_HDR_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.SOS_CHILD_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.SOS_CHILD_QUES_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.SOS_IMAGES} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.SOS_IR_IMAGES} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.SOS_IRUPLOAD} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.CATEXE_HDR_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.CATEXE_CHILD_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.CATEXE_IMAGES} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.CATEXE_STOCK_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.WAREHOUSE_CAMPAIGN_HDR_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.WAREHOUSE_CAMPAIGN_CHILD_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.WAREHOUSE_CAMPAIGN_IMAGES} where STORE_ID='${StoreId}' `,

      `Delete from ${AppTables.WAREHOUSE_HDR_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.WAREHOUSE_CHILD_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.WAREHOUSE_IMAGES} where STORE_ID='${StoreId}' `,


      // `Delete from ${AppTables.STORE_PROFILE} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.ORDERSTATUS} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.VISICO_HDR_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.VISICO_CHILD_DATA} where STORE_ID='${StoreId}' `,
      // `Delete from ${AppTables.CONTRACT_FORM} where STORE_ID='${StoreId}' `,
      // `Delete from ${AppTables.CONTRACT_FORM_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.POSSALE_DATA} where STORE_ID='${StoreId}' `,
      // `Delete from ${AppTables.VISICO_CHILD_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.CASHTILL_SURVEY} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.SIMPLE_PROMOTION_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.SIMPLE_PROMOHDR_DATA} where STORE_ID='${StoreId}' `,

      `Delete from ${AppTables.STOCK2HDR_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.STOCK2_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.STOCK2_MFD_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.PAIDVIS_HDR_DATA} where STORE_ID='${StoreId}' `,

      `Delete from ${AppTables.STOCKPOMO_HDR_DATA} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.STOCKPROMO_DATA} where STORE_ID='${StoreId}' `,

      `Delete from ${AppTables.QRCODE_SCANNER} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.QRCODE_SALE} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.STORE_KYC_INFO} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.RETURN_STOCK} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.ORDER_SIMPLIFY} where STORE_ID='${StoreId}' `,
      `Delete from ${AppTables.ORDER} where STORE_ID='${StoreId}' `,

    ]

    if (Status != "U") {
      // if(Status=="U"|| Status=="Cancel"){
      allQueries.push(`Delete from ${AppTables.CHECKIN_DATA} where STORE_ID='${StoreId}' `)
    }
    return await Promise.all(
      allQueries.map(async (q, index) => {
        let isDeleted = await executeQuery(q);
        return isDeleted == true;
      })
    )
      .then((val) => {
        // if(val.indexOf(false)<0){}
        return true;
      }).catch((err) => {
        console.log(err);
        return false;
      })
  }

  async function executeQuery(q, type = '1') {
    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        await txn.executeSql(q, [], async function (txn2, txnres2) {
          if (type == '1') {
            resolve(true);
          }
          else {

            if (txnres2.rows.length > 0) {
              let arr = [];//txnres2.rows.raw();
              // resolve(arr);
              for (var i = 0; i < txnres2.rows.length; i++) {
                let data = txnres2.rows.item(i);
                arr.push(data);
                if (i == (txnres2.rows.length - 1)) {
                  resolve(arr);
                }
              }
            }
            else {
              resolve([]);
            }
          }
        }, function (Etxn, txnerr) { console.log(txnerr); type == '1' ? resolve(false) : resolve([]); });
      });
    }).then((val) => {
      return val;
    }).catch((err) => {
      console.log(err);
      let d = type == '1' ? false : [];
      return d;
    })
  }

  function FilterStores(searchedQry) {
    searchedQry = searchedQry.toLowerCase();
    console.log('searchedQry', searchedQry);
    let { storeList } = state;
    let arr = []
    if (searchedQry != null && searchedQry != '') {
      globalStorelist.map((item, index) => {
        let { StoreName, StoreId, StoreCode } = item;
        StoreId = StoreId + '';
        console.log("itemessss", StoreName + "---------------" + StoreCode)
        if (StoreName?.toLowerCase().includes(searchedQry) || StoreCode?.toLowerCase().includes(searchedQry) || StoreId?.includes(searchedQry)) {
          arr.push(item);
        }
      });
    }
    else {
      arr = globalStorelist;
    }
    setState({ storeList: arr });
    setrerenderdata(!rerenderdata)
  }

  async function fetchStoreSearchData(searchedItem) {
    let loginInfo = await get_item('loginInfo');
    const loginDetails = JSON.parse(loginInfo);
    if (searchedItem != null && searchedItem != '' && searchedItem.length > 4) {
      let postdata = {
        Downloadtype: "StoreSearch_JourneyPlan",
        Username: loginDetails.UserId,
        Param1: searchedItem,
        Param2: Platform.OS == "ios" ? "iOS" : "Android",
      };
      var url = props.baseurl + getMethodName(METHODS.DOWNLOADJSON_METHOD);
      console.log(url, postdata);
      return await getDownloadJson1(url, postdata)
        .then(async (res) => {
          if (res != null && typeof res == 'object' && res.StoreSearch_JourneyPlan != null && res.StoreSearch_JourneyPlan != '') {
            let searchResults = res.StoreSearch_JourneyPlan || [];
            // Get existing store list
            let currentStoreList = state.storeList || [];
            // Merge new search results with existing data
            let combinedStoreList = [...currentStoreList, ...searchResults];
            setState({ storeList: combinedStoreList });
            setrerenderdata(!rerenderdata);
          } else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
            console.log('No data found');
            notify("There is no store exists of this name");
          }
        }).catch((err) => {
          notify("Please retry! There is some error while fetching data");
          console.log('onDownload report error', err);
        });
    } else {
      notify("Store name should not be less than 5 characters");
    }
  }

  function _render_StoreVisitModal() {
    return (
      <CustomModal
        style={customStyle.storelVisitM_Style}
        title={ST.StoreVisited}
        titleStyle={customStyle.storelVisitM_titleStyle}
        showModal={showStoreVisitModal}
      >
        <View style={customStyle.storelVisitM_options}>
          <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={() => { storeVisited() }}>
            <Text style={customStyle.storelVisitM_op_btnText}>{ST.Yes}</Text>
          </TouchableOpacity>
          <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={() => { storeNotVisited() }}>
            <Text style={customStyle.storelVisitM_op_btnText}>{ST.No}</Text>
          </TouchableOpacity>
        </View>
      </CustomModal>
    )
  }

  function _render_GeoTagModal() {
    return (
      <CustomModal
        style={customStyle.storelVisitM_Style}
        title={ST.Youneedtogeotagstore}
        titleStyle={customStyle.storelVisitM_titleStyle}
        showModal={showGeoTagModal}
      >
        <View style={customStyle.storelVisitM_options}>
          <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={() => { setShowGeoTagModal(false) }}>
            <Text style={customStyle.storelVisitM_op_btnText}>{ST.Cancel}</Text>
          </TouchableOpacity>
          <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={() => { setShowGeoTagModal(false); props.navigation.navigate('GeoTag', { storeData: currentStore, 'isAdhoc': isAdhocScreen, 'isBeat': isBeatPlan, 'isNonMerchans': isNonMerchan, 'isNonProgs': isNonProg, 'isStoreSearch': isStoreSearch }); }}>
            <Text style={customStyle.storelVisitM_op_btnText}>{ST.OK}</Text>
          </TouchableOpacity>
        </View>
      </CustomModal>
    )
  }

  function _render_CancelCheckinModal() {
    let storename = cancelCheckOutStore.StoreName || '';
    return (
      <CustomModal
        style={customStyle.storelVisitM_Style}
        title={ST.DoyoureallywanttoCancelCheckIn}
        titleStyle={customStyle.storelCancelM_titleStyle}
        messageStyle={customStyle.storelCancelM_subtitleStyle}
        message={storename}
        showModal={showCancelCIModal}
      >
        <View style={customStyle.storelCM_alertCon}>
          <Feather name='alert-triangle' size={20} color={'#ff0000'} />
          <Text style={customStyle.storelCM_alert}>{ST.Yourallcheckindatawillbelost}</Text>
        </View>

        <View style={customStyle.storelVisitM_options}>

          <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={() => { setShowCancelCIModal(false); }}>
            <Text style={customStyle.storelVisitM_op_btnText}>{ST.Cancel}</Text>
          </TouchableOpacity>
          <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={() => { onVisitCancel() }}>
            <Text style={customStyle.storelVisitM_op_btnText}>{ST.OK}</Text>
          </TouchableOpacity>
        </View>
      </CustomModal>
    )
  }

  //upload GeoFence data
   async function uploadGeoFenceData(geoFenceData) {
      let d1 = new Date();
      let d2 = moment(d1).format('MM/DD/YYYY');
      setShowAlert(false);
      setProcessing(true);
      setLoaderTitle('Uploading Data...');
  
  
      let postData = {
        "MID": 0,
        "Keys": "GeoFenceDataStoreList",
        "JsonData": JSON.stringify(geoFenceData),
        "UserId": props.UserId,
      };
  
      // console.log("GeoFenceDataStoreList:", postData)
      console.log("GeoFenceDataStoreList--",JSON.stringify(postData, null, 2));
  
  
      const url = props.baseurl + getMethodName(METHODS.UPLOADJSON_METHOD);
      await UploadData2(url, postData)
        .then(async (res) => {
          console.log('res: 123', res);
          if (res?.UploadJsonResult == "Success") {
            notify('GeoFenceData Uploaded Succesfully', 'SHORT');
              setShowAlert(false);
              setProcessing(false);
          }
          else {
            setShowAlert(false)
            setProcessing(false);
          }
        })
        .catch((err) => {
          console.log(err); setProcessing(false);
        });
  
    }

  async function onDistanceM_OK() {
   // console.log("Hello shaikh", geoFenceData);
    if (props.GeoFenceEnable) {
      if (storeDistanceinM > props.GeoFenceRadius) {
        uploadGeoFenceData(geoFenceData);
        setShowDistanceModal(false);
        notify(ST.Youcannotcheckin + ' ' + ST.Youarenotwithinthealloweddistancefromthestore + ' ' + props.GeoFenceRadius + ' m', 'LONG')
      }
      else {
        setShowDistanceModal(false);
        props.navigation.navigate('StoreCheckin', { storeData: currentStore, 'isAdhoc': isAdhocScreen, 'isBeat': isBeatPlan, 'isNonMerchans': isNonMerchan, 'isNonProgs': isNonProg, 'isStoreSearch': isStoreSearch, '_fromStoreWise': true });
      }
    } else {
      setShowDistanceModal(false);
      props.navigation.navigate('StoreCheckin', { storeData: currentStore, 'isAdhoc': isAdhocScreen, 'isBeat': isBeatPlan, 'isNonMerchans': isNonMerchan, 'isNonProgs': isNonProg, 'isStoreSearch': isStoreSearch, '_fromStoreWise': true });
    }
  }


  function closeImageModal() {
    setCheckOutImageModal(false);
  }

  function cancelImage() {
    if (CheckOutImagePath != '') {
      RNFS.unlink(CheckOutImagePath);
    }
    setCheckOutImage('');
    setCheckOutImagePath('');
    closeImageModal();
  }

  async function openCamera() {
    BGUpdateShowCamera(true);
  }

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

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

      console.log("time", picture_clicked_time);
      console.log("time1", picture_clicked_time_for_pic_name);
      let calculate_tym_date_for_filename = picture_clicked_time_for_pic_name;
      let calculate_tym_date_over_img = picture_clicked_time;

      let filename = storeData.StoreId + '_CheckoutImg-' + calculate_tym_date_for_filename + '.jpg';

      const mark_text1 = calculate_tym_date_over_img;
      const mark_text2 = 'Store Name:' + storeData.StoreName + ' | Store Id:' + storeData.StoreId + ' | User Id:' + storeData.EmpId + ' | Image Type: Check Out' + ' | Date:' + calculate_tym_date_over_img;

      setCheckOutImage(filename);
      let imagePath = `${CoverageImagePath}${filename}`;
      RNFS.copyFile(imgurl, imagePath)
        .then(async (resn) => {
          // render data with clicked image
          let uri = 'file://' + imagePath;
          console.log('image marker', uri);
          setCheckOutImagePath(uri);
          // add metdata then resize image and restored back to the imagePath
          let restore_data = { "destFilePath": imagePath, "imgurl": imgurl, imgWidth, imgHeight, mark_text1, mark_text2 }
          let is_restored = await restore_ImageWithMetaData(restore_data, imgdata);
          console.log("image restored:", is_restored);
        })
        .catch(err => {
          console.log(ST.Errorimagefilewritefailed + '!!!');
          console.log(err.message, err.code);
        });
    }
  }


  function _OpenCaptureImage_Modal() {
    const isImageCap = (CheckOutImagePath == '' || CheckOutImagePath == null) ? false : true;
    return (
      <CustomModal
        style={customStyle.nonWCapImgModal}
        title={ST.CheckOutImage}
        message={ST.Pleaseclickselfieinfrontofstore}
        titleStyle={customStyle.nonWCapImgModal_title}
        messageStyle={customStyle.nonWCapImgModal_subtitle}
        showModal={CheckOutImageModal}
      >
        {
          !isImageCap &&
          <View style={customStyle.nonWCapImgModalCon}>
            <TouchableOpacity style={customStyle.nonWCapImgModal_Camera} onPress={() => { openCamera() }}>
              <CameraImg2 width={100} height={100} />
            </TouchableOpacity>
            <TouchableOpacity style={customStyle.nonWCapImgModal_Cancel_btn} onPress={() => { closeImageModal() }}>
              <Text style={customStyle.nonWCapImgModal_Cancel_btnText}>{ST.Cancel}</Text>
            </TouchableOpacity>
          </View>
        }
        {
          isImageCap &&
          <View style={customStyle.nonWCapImgModalCon}>
            <View style={customStyle.nonWCapImgModal_ImgWrap}>
              <Image style={[customStyle.nonWCapImgModal_Img, (Platform.OS == 'ios' ? customStyle.android_flipIMageView : {})]} source={{ uri: CheckOutImagePath }} />
            </View>
            <TouchableOpacity style={customStyle.nonWCapImgModal_CameraSmall} onPress={() => { openCamera() }}>
              <MaterialCommunityIcons name='camera-retake' size={30} color={PageTheme.$primary_color} />
            </TouchableOpacity>
            {showImageSaveOp &&
              <View style={customStyle.nonWCapImgModal_btng}>
                <TouchableOpacity style={customStyle.nonWCapImgModal_Cancel_btn} onPress={() => { cancelImage() }}>
                  <Text style={customStyle.nonWCapImgModal_Cancel_btnText}>{ST.Cancel}</Text>
                </TouchableOpacity>
                {/* call checkout functionality with type : 2 , which means we have captured the image and again checking the location  */}
                <TouchableOpacity style={customStyle.nonWCapImgModal_Save_btn} onPress={() => { closeImageModal(); getLocOnCheckout('2'); }}>
                  <Text style={customStyle.nonWCapImgModal_Save_btnText}>{ST.Save}</Text>
                </TouchableOpacity>
              </View>}
            {!showImageSaveOp &&
              <TouchableOpacity style={customStyle.nonWCapImgModal_Cancel_btn} onPress={() => { closeImageModal() }}>
                <Text style={customStyle.nonWCapImgModal_Cancel_btnText}>{ST.Close}</Text>
              </TouchableOpacity>
            }

          </View>

        }
      </CustomModal>
    )
  }

  function _render_DistanceModal() {
    return (
      <CustomModal
        style={customStyle.storeDistance_Modal}
        title={'Performics'}
        titleStyle={customStyle.storeDistanceM_title}
        showModal={showDistanceModal}
      >
        <View style={customStyle.storeDistanceM_Con}>
          <Text style={customStyle.storeDistanceM_message}>{ST.Youneedtobeinthestore}</Text>
          <Text style={[customStyle.storeDistanceM_message, customStyle.mb20]}>{ST.toCheckInCheckOut}</Text>
          <Text style={customStyle.storeDistanceM_submessage}>{`${ST.Alloweddistancefromstore}: ${(props.GeoFenceEnable == true ? props.GeoFenceRadius : '500')} m`}</Text>
          <Text style={customStyle.storeDistanceM_submessage}>{`${ST.Yourdistancefromstore}: ${storeDistance}`}</Text>
          <TouchableOpacity style={customStyle.storeDistanceM_btn} onPress={() => { onDistanceM_OK() }}>
            <Text style={customStyle.storeDistanceM_btnText}>Ok</Text>
          </TouchableOpacity>
        </View>
      </CustomModal>
    )

  }


  return (
    <Container {...props} pt={0} avoidSafeArea={(Platform.OS == 'ios' ? true : false)}>
      {processing && <CustomLoader fullHeight={true} title={loaderTitle} />}
      {(startUploading) && <DownloadDataModal title={UploadingText} downloadCount={uploadedCount} totalCount={TotalUpCount} subtitle={UploadingSubText} showProgresssBar={showProgresssBar} />}
      <View style={{ zIndex: 10 }}>
        <CustomHeader {...props} showaddstore={false} title={(isBeatPlan == true ? 'Beat ' + ST.StoreList : (isAdhocScreen == true ? ST.Adhoc + ' ' + ST.StoreList : (isNonMerchan == true ? 'Non Merchandised' : isNonProg == true ? 'Non Program' : isStoreSearch == true ? 'Store Search' : ST.StoreList)))} />
      </View>
      {_render_StoreVisitModal()}
      {_render_GeoTagModal()}
      {_render_DistanceModal()}
      {_render_CancelCheckinModal()}
      {_OpenCaptureImage_Modal()}
      {ConfirmSaveAlert(props, showAlert, onSaveCancel, getLocOnCheckout, ST.Doyoureallywanttocheckout)}
      <CustomCamera cameraType={props.CheckoutOpenBackCamera ? 'back' : 'front'} BottomText={'Store Name:' + checkOutStore.StoreName + ' | Store Id:' + checkOutStore.StoreId + ' | User Id:' + checkOutStore.EmpId + ' | Image Type: Check Out'} onImageCaptured={(imgData) => { BGUpdateShowCamera(false); getImage(imgData) }} showCamera={showCamera} onHideCamera={() => { BGUpdateShowCamera(false); }} />

      <LinearGradient colors={[PageTheme.$gradient1, PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
        <View style={customStyle.pageContentWrapper}>
          {!props.isDataDownloaded && <NoDataComponent {...props} />}
          <View style={[customStyle.storelist_parentwrap]}>
            <HeaderTabs {...props} isAdhocScreen={isAdhocScreen} isBeatPlan={isBeatPlan} isNonMerchans={isNonMerchan} isNonProgs={isNonProg} isStoreSearch={isStoreSearch} />
            {!isStoreSearch &&
              <View style={customStyle.storel_searchbar}>
                <TextInput
                  style={[customStyle.storel_searchInput]}
                  placeholder={ST.Searchby + ` ${ST.StoreName}, ${ST.StoreId}, ${ST.StoreCode}`}
                  autoComplete='off'
                  placeholderTextColor={PageTheme.$placeholder_color}
                  value={searchedItem}
                  onChangeText={(val) => { setSearchedItem(val); FilterStores(val) }}
                />
                <TouchableOpacity style={customStyle.storel_searchBtn} onPress={() => { FilterStores(searchedItem) }}>
                  <AntDesign style={customStyle.storel_searchBtnIcon} name='search1' size={20} color={PageTheme.$accent_color} />
                </TouchableOpacity>
              </View>
            }
            {isStoreSearch &&
              <View style={customStyle.storel_searchbar}>
                <TextInput
                  style={[customStyle.storel_searchInput]}
                  placeholder={ST.Searchby + ` ${ST.StoreName}`}
                  autoComplete='off'
                  placeholderTextColor={PageTheme.$placeholder_color}
                  value={searchedItem}
                  onChangeText={(val) => { setSearchedItem(val) }}
                />
                <TouchableOpacity style={customStyle.storel_searchBtn} onPress={() => { fetchStoreSearchData(searchedItem) }}>
                  <AntDesign style={customStyle.storel_searchBtnIcon} name='search1' size={20} color={PageTheme.$accent_color} />
                </TouchableOpacity>
              </View>
            }

            {getValidStores(state?.storeList) && getValidStores(state?.storeList).length > 0 && !isAdhocScreen && !isBeatPlan && !isNonMerchan && !isNonProg && !isStoreSearch && (props.StoreMapView || props.StoreMapView == 1) ? <View style={styles.container}>
              <TouchableOpacity
                style={styles.button}
                onPress={() => {
                  let filtered_store = getValidStores(state?.storeList);
                  if (filtered_store?.length > 0) {
                    props.navigation.navigate("StoreListMappView", {
                      storeData: filtered_store,
                    })
                  } else {
                    notify("Valid store list not found for MapView.")
                  }
                }
                }
              >
                <View style={{ flexDirection: "row", alignItems: "center" }}>
                  {/* Replace CameraImg with your Map SVG */}
                  <StoreGeoIcon width={20} height={20} />
                  <Text style={[styles.buttonText, { marginLeft: 8 }]}>
                    Store List Map View
                  </Text>
                </View>
              </TouchableOpacity>
            </View> : <></>}

            {nodataFound &&
              <View style={customStyle.noDataCon}>
                <Text style={customStyle.noDataText}>{ST.NoDataAvailable}</Text>
              </View>
            }
            {(props.isDataDownloaded == true && !nodataFound) &&
              <View style={[customStyle.storel_Con, (props.StoreMapView && getValidStores(state?.storeList) && getValidStores(state?.storeList).length > 0 && { paddingBottom: 270 })]}>
                <FlatList
                  data={state.storeList}
                  extraData={rerenderdata}
                  style={customStyle.listcon}
                  initialNumToRender={4}
                  contentContainerStyle={customStyle.iteml_con}
                  renderItem={({ item, index, separators }) => {
                    return (
                      <StoreItem  {...props} item={item} index={index} isAdhocScreen={isAdhocScreen} isBeatPlan={isBeatPlan} isNonMerchan={isNonMerchan} isNonProg={isNonProg} isStoreSearch={isStoreSearch} setShowStoreVisitModal={setShowStoreVisitModal} setCurrentStore={setCurrentStore} onCheckOut={onCheckOut} executeSelQuery={executeSelQuery} storeList={state.storeList} setLoaderTitle={setLoaderTitle} setProcessing={setProcessing} setShowCancelCIModal={setShowCancelCIModal} setCancelCheckOutStore={setCancelCheckOutStore} />
                    );
                  }}
                />
              </View>
            }
          </View>
        </View>
      </LinearGradient>

    </Container>
  );
}





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

const styles = StyleSheet.create({
  container: {
    alignItems: "center",
    justifyContent: "center",
    marginTop: 10,
  },
  button: {
    backgroundColor: "#4a90e2",  // nice blue
    paddingVertical: 14,
    paddingHorizontal: 27,
    borderRadius: 30,            // pill-shaped
    elevation: 2,                // shadow (Android)
    shadowColor: "#000",         // shadow (iOS)
    shadowOpacity: 0.2,
    shadowOffset: { width: 0, height: 2 },
    shadowRadius: 4,
  },
  buttonText: {
    color: "#fff",
    fontSize: 16,
    fontWeight: "500",
    textAlign: "center",
  },
});
