import React, { useState, useEffect, memo, useRef } from 'react';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
import { customStyles, GetPageTheme } from "../styles/Global";
import { Image, View, Text, TouchableOpacity, Platform, DeviceEventEmitter, StyleSheet, ActivityIndicator } from 'react-native';
import { connect } from 'react-redux';
import { mapStateToProps, mapDispatchToProps } from '../reducers/contextProvider';
import { notify } from '../components/notify';
import moment from 'moment';
import { checkRange, UploadData2, UpdateStoreStatus, getKPIS, restore_ImageWithMetaData } from '../controller/functions';
import { get_item } from '../components/localStorage';
import { db, AppVersion, CoverageImagePath } from '../constants/constants';
import CustomHeader from '../components/customHeader';
import { Feather, MaterialCommunityIcons } from '../components/icons';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
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, Q_MenuList } from '../constants/ConstantQueries';
import { ConfirmSaveAlert } from '../components/alert';
import { getMethodName, METHODS } from '../constants/methodNames';
import { SyncIRsessions, uploadAllData, uploadAllImages, uploadStoreStatus } from '../constants/uploadData';
import CameraImg2 from '../assets/performics/camera_icon.svg';
import CustomCamera from '../components/Camera';
import DownloadDataModal from '../components/downloadDataModal';
import IRLogin from '../components/IRLogin';
import { AppName, PerformicsIRAppName } from '../../../AppSpecificContant';
import MapView, { Marker } from "react-native-maps";
import MoreInfoCheckbox from "../components/MoreInfoCheckbox"; // path to component above

function StoreListMappView(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(true);
  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 [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 [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 sessionsToUpload = useRef([]);
  const sessionsUploadedCount = useRef(0);
  const sessionsReceived = useRef(0);
  const [_storeList, SetStoreList] = useState([]);
  const [location, setLocation] = useState(null);
  const [address, setAddress] = useState("");
  const [sortedStores, setSortedStores] = useState([]);
  const mapRef = useRef(null);
  const [mapReady, setMapReady] = useState(false);
  const [checked, setChecked] = useState(false);
  const d1 = new Date();
  const d2 = moment(d1).format('MM/DD/YYYY');

  const getAddressFromLatLong = async (lat, lon) => {
    try {
      setProcessing(true)
      const response = await fetch(
        `https://nominatim.openstreetmap.org/reverse?format=json&lat=${lat}&lon=${lon}&zoom=10&addressdetails=1`,
        {
          headers: {
            "User-Agent": "MyReactNativeApp/1.0",
            'Accept': "application/json",
          },
        }
      );

      const text = await response.text(); // get raw response
      // check if it is valid JSON
      let data;
      try {
        data = JSON.parse(text);
      } catch (e) {
        console.log("Invalid JSON response:", text);
        return;
      }
      console.log("data", data);
      const loc =
        `${data?.address?.city_district || ""}, ${data?.address?.city || ""}, ${data?.address?.country || ""}` ||
        "Unknown";

      setProcessing(false);
      setAddress(loc);

      console.log("Locality:", loc);
    } catch (error) {
      console.error("Nominatim error:", error);
    }
  };
  useEffect(() => {
    // Fetch user location
    Geolocation.getCurrentPosition(
      (position) => {
        const myLat = position.coords.latitude;
        const myLng = position.coords.longitude;
        setLocation({ latitude: myLat, longitude: myLng });
        // Example: get store list from route
        const _storeList = route?.params?.storeData || [];
        console.log("_storeList", _storeList)
        // Sort nearest first
        _storeList.sort((a, b) => a.DistanceInMeters - b.DistanceInMeters);
        console.log("withDistance", _storeList)
        setSortedStores(_storeList);
        // Zoom map to fit all points
        if (mapRef.current && _storeList.length > 0) {
          const coords = [
            ..._storeList.map((s) => ({
              latitude: parseFloat(s.Latitude),
              longitude: parseFloat(s.Longitude),
            })),
            { latitude: myLat, longitude: myLng },
          ];
          mapRef.current.fitToCoordinates(coords, {
            edgePadding: { top: 50, right: 50, bottom: 50, left: 50 },
            animated: true,
          });
        }
      },
      (error) => {
        console.log("Location error:", error);
      },
      { enableHighAccuracy: true, timeout: 30000, maximumAge: 10000, distanceFilter: 0, fastestInterval: 2000, }
    );
  }, []);

  useEffect(() => {
    if (location) {
      getAddressFromLatLong(location.latitude, location.longitude);
    }
  }, [location]);

  useEffect(() => {
    setLoaderTitle(ST.Loading +"/Refreshing" + '...');
    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);
    const unsubscribe = props.navigation.addListener('beforeRemove', onBeforeRemove);
    const unsubscribeFocus = props.navigation.addListener('focus', () => {
    });
    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;
    };
  }, []);

  useEffect(() => {
    if (mapRef.current && _storeList?.length > 0 && location) {
      const coords = [
        ..._storeList.map((loc) => ({
          latitude: parseFloat(loc.Latitude),
          longitude: parseFloat(loc.Longitude),
        })),
        {
          latitude: location.latitude,
          longitude: location.longitude,
        },
      ];

      mapRef.current.fitToCoordinates(coords, {
        edgePadding: { top: 50, right: 50, bottom: 50, left: 50 },
        animated: true,
      });
    }
  }, [_storeList, location]);

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

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

  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 []
    })
  }

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

        // let dinKM=(distance / 1000);
        // let distanceinM=(distance=='' || distance==null || isNaN(distance))?' 0 m':( dinKM > 1 ? dinKM.toFixed(1) + ' Km' : distance + ' m');
        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': "UserCurrentLocation",
      '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 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')
                  await deleteStore(data, "U");
                }
              }
              else {
                if (index == AllStores.length - 1) {
                  // setProcessing(false);
                  setStartUploading(false);
                  notify(ST.Erroroccurwhileuploadingdata, 'LONG');
                }
              }
            }
            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')
          await deleteStore(data, "U");
        }
      }
      else {
        if (index == AllStores.length - 1) {
          // setProcessing(false);
          setStartUploading(false);
          notify(ST.Erroroccurwhileuploadingdata, 'LONG');
        }
      }
    }
  }

  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')
          await deleteStore(data, "U");
        }
      } else {
        notify(ST.Cannotuploadimagesfor + ' ' + StoreName, 'SHORT');
        if (index == AllStores.length - 1) {
          // setProcessing(false);
          setStartUploading(false);
        }
      }
    }
    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')
          await deleteStore(data, "U");
        }

      }
      else if (index == AllStores.length - 1) {
        // setProcessing(false);
        setStartUploading(false);
      }
      else {

      }
    }
  }

  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 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}' `,

    ]

    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 _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={() => { }}>
            <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>
    )
  }

  async function onDistanceM_OK() {
    if (props.GeoFenceEnable) {
      if (storeDistanceinM > props.GeoFenceRadius) {
        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 });
      }
    }
    else {
      setShowDistanceModal(false); props.navigation.navigate('StoreCheckin', { storeData: currentStore, 'isAdhoc': isAdhocScreen, 'isBeat': isBeatPlan, 'isNonMerchans': isNonMerchan, 'isNonProgs': isNonProg, 'isStoreSearch': isStoreSearch });
    }
  }


  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={true} 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}>
        {!processing ? (
          <View style={customStyle.pageContentWrapper}>
            {/* More Info checkbox */}
            <View style={{ marginTop: -5, marginBottom: 3 }}>
              <MoreInfoCheckbox
                checked={checked}
                onToggle={() => setChecked(prev => !prev)}
                label="Store Info"
              />
            </View>

            <View style={[customStyle.mapWrapCon, (Platform.OS === 'ios' ? customStyle.mapWrapConIOS : {})]}>
              <View style={[customStyle.mapWrapper, customStyle.mapWrapperView, { height: "100%" }]}>
                {/* Loader */}
                {!mapReady && processing && (
                  <View style={styles.loaderContainer}>
                    <ActivityIndicator size="large" color="#4a90e2" />
                  </View>
                )}
                {/* Map */}
                {!processing && (
                  <MapView
                    ref={mapRef}
                    style={styles.map}
                    onMapReady={() => setMapReady(true)}
                    initialRegion={{
                      latitude: location?.latitude || 22.9734,   // fallback India center
                      longitude: location?.longitude || 78.6569,
                      latitudeDelta: 0.5,
                      longitudeDelta: 0.5,
                    }}
                  >
                    {/* 📍 Current Location */}
                    {location && (
                      <Marker
                        coordinate={{
                          latitude: location.latitude,
                          longitude: location.longitude,
                        }}
                        pinColor="green"
                        title={address || "You are here"}
                      />
                    )}

                    {/* 🏬 Store Markers */}
                    {sortedStores?.length > 0 &&
                      sortedStores.map((store) => (
                        <Marker
                          key={store.StoreId}
                          coordinate={{
                            latitude: parseFloat(store.Latitude),
                            longitude: parseFloat(store.Longitude),
                          }}
                          tracksViewChanges={true} // ✅ prevents blinking
                        >
                          {/* 📌 Custom Pin with Label */}
                          <View style={{ alignItems: "center" }}>
                            {console.log("tedfdffd", store)}
                            {checked ? <View style={{ backgroundColor: "white", padding: 5, borderRadius: 4, alignItems: "center", justifyContent: "center", }}>
                              <Text style={{ fontWeight: "500", fontSize: 15 }}>
                                {store.StoreName} - {store.StoreId}
                              </Text>
                              <Text style={{ marginTop: 5, backgroundColor: "white", color: "black", padding: 1, borderRadius: 4, size: 16 }}>
                                Address: {store.Address}
                              </Text>
                              <Text style={{ backgroundColor: "white", padding: 1, borderRadius: 4, size: 16 }}>
                                Distance:{" "}
                                {store?.Distance ? store.Distance : "0 m."}
                              </Text>
                              <View
                                style={{
                                  width: 15,
                                  height: 15,
                                  borderRadius: 6,
                                  backgroundColor: "red",
                                  marginTop: 3,
                                  borderWidth: 1,
                                  borderColor: "#fff", // ✅ adds border for visibility
                                }}
                              />
                            </View> : <></>}
                            <View
                              style={{
                                width: 20,
                                height: 20,
                                borderRadius: 6,
                                backgroundColor: "red",
                                marginTop: 3,
                                borderWidth: 1,
                                borderColor: "#fff", // ✅ adds border for visibility
                              }}
                            />
                          </View>

                        </Marker>
                      ))}
                  </MapView>
                )}
              </View>
            </View>
          </View>
        ) : <View style={[customStyle.pageContentWrapper, { justifyContent: 'center', alignItems: 'center' }]}>
          {/* <Text style={{ fontSize: 16, fontWeight: 'bold' }}>
            Refreshing................
          </Text> */}
        </View>}
      </LinearGradient>
    </Container>
  );
}



export default connect(mapStateToProps, mapDispatchToProps)(StoreListMappView);
const styles = StyleSheet.create({
  container: { flex: 1 },
  map: { flex: 1 },
  overlay: {
    position: "absolute",
    top: 50,
    alignSelf: "center",
    backgroundColor: "white",
    padding: 10,
    borderRadius: 8,
    elevation: 5,
  },
  loaderContainer: {
    ...StyleSheet.absoluteFillObject, // fill entire screen
    backgroundColor: "rgba(255,255,255,0.9)",
    alignItems: "center",
    justifyContent: "center",
    zIndex: 2, // sit above the map
  },
  callout: {
    backgroundColor: "white",
    padding: 10,
    borderRadius: 8,
    minWidth: 180,
    elevation: 5,
  },
  description: { fontSize: 14, marginBottom: 4 },
  coords: { fontSize: 12, color: "gray" },

  callout: {
    flexDirection: "column",
    flexShrink: 1,
    maxWidth: 250, // 🔑 prevents cutoff
    padding: 8,
  },
  title: {
    fontWeight: "bold",
    fontSize: 14,
    marginBottom: 2,
  },
  text: {
    fontSize: 13,
    flexShrink: 1,
    flexWrap: "wrap", // 🔑 wraps text
  },
});