import React, { useState, useEffect, useCallback, useRef } from 'react';
import Container from '../components/container';
import { useRoute, useFocusEffect } from '@react-navigation/native';
import { customStyles, GetPageTheme } from "../styles/Global";
import { Image, TextInput, View, Text, ScrollView, TouchableOpacity, Platform, FlatList } 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, marktext1, marktext2, UploadFormData, getDownloadJson1, fetchProjectConfig } from '../controller/functions';
import { get_item } from '../components/localStorage';
import { db, AppVersion } from '../constants/constants';
import CustomHeader from '../components/customHeader';
import { AntDesign, Feather, MaterialCommunityIcons } from '../components/icons';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import NoDataComponent from '../components/NoDataComponent';
import { SvgXml } from 'react-native-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_MenuList } from '../constants/ConstantQueries';
import { ConfirmSaveAlert } from '../components/alert';
import { getFolderName, getMethodName, METHODS } from '../constants/methodNames';
import { 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 StoreItem from '../components/StoreItem';


function StoreList(props) {
   console.log("propss:",props)

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

   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 [isNPNDScreen, setisNPNDScreen] = useState(false);

   const isNPNDRef = useRef(isNPNDScreen);
   const isAdhocRef = useRef(isAdhocScreen);

   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: [] });
   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 [CheckOutLoc, setCheckOutLoc] = useState({});
   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 [showSearchWiseStore, setShowSearchWiseStore] = useState(false);
   const [showStoreSearchLabel, setShowStoreSearchLabel] = useState('');

   const [EmpData, setEmpData] = useState([]);
   const [storeData, setStoreData] = useState([]);
   const [isAsyncDone, setIsAsyncDone] = useState(false);
   const [desig, setDesig] = useState('');
   const [storewisePjp, setStorewisePjp] = useState('');
   const [showsearchwise_dummy, setShowSearchWise_Dummy] = useState(false)


   // useEffect(() => {
   //    // let ShowStoreSearch = props?.ShowStoreSearch ?? false;
   //    // setShowSearchWise_Dummy(ShowStoreSearch);

   //    const params = props.route.params || {};
   //    const empData1 = params.empData || {};

   //    fetchProjectConfig(props.ManagerAppConfig)
   //       .then(storewisePjp => {
   //          setStorewisePjp(storewisePjp);
   //          console.log('storewisePjpTop>>:', storewisePjp);
   //       });

   //    DownloadMappingSurvey(empData1, storewisePjp.StorewisePJP);
   // }, []);

   useEffect(() => {
  const params = props.route.params || {};
  const empData1 = params.empData || {};

  fetchProjectConfig(props.ManagerAppConfig)
    .then(storewisePjp => {
      setStorewisePjp(storewisePjp);

      console.log('storewisePjpTop>>:', storewisePjp);

      // ✅ SAFE: yahi se call
      DownloadMappingSurvey(empData1, storewisePjp?.StorewisePJP);
    })
    .catch(err => {
      console.error('Config error', err);
    });

}, []);



   useFocusEffect(
      useCallback(
         () => {
            fetchLoginInfo();
         }, []));

   const fetchLoginInfo = async () => {
      try {
         const loginInfo = await get_item('loginInfo');
         const loginDetails = loginInfo ? JSON.parse(loginInfo) : null;
         await new Promise((resolve) => setTimeout(resolve, 2000)); // Simulate delay
         setDesig(loginDetails?.Designation || '');
         console.log('Async useEffect completed');
         setIsAsyncDone(true); // Mark async operation as done
         return loginDetails?.Designation || ""
      } catch (error) {
         console.error('Error in async useEffect:', error);
         setIsAsyncDone(true); // Still mark as done to proceed
      }
   };


   useFocusEffect(
      useCallback(() => {
         let isActive = true; // prevents state updates after unmount

         const run = async () => {
            try {
               setLoaderTitle(ST.Loading + '...');

               const params = props.route.params || {};
               const empData1 = params.empData || {};

               const showSearchWiseStore1 =
                  params.showSearchWiseStore != null && params.showSearchWiseStore !== ''
                     ? params.showSearchWiseStore
                     : false;

                      const {StorewisePJP: storewisePjp, StoreSearch: storeSearch } = await fetchProjectConfig(props.ManagerAppConfig);
                      console.log('storewisePjpMid::', storewisePjp, storeSearch);


               const ShowStoreSearch = storeSearch ?storeSearch: false;
               const ShowStoreSearchLabel = props?.ShowStoreSearchLabel ?? false;

               const isAdhoc = params.isAdhoc ?? false;
               const isNPND = params.isNPND ?? false;

               isAdhocRef.current = isAdhoc;
               isNPNDRef.current = isNPND;

               if (!isActive) return;

               // ---- SET STATES ----
               setIsAdhocScreen(isAdhoc);
               setisNPNDScreen(isNPND);
               setEmpData(empData1);
               setShowSearchWiseStore(ShowStoreSearch);
               setShowStoreSearchLabel(ShowStoreSearchLabel);

               const CO_GeoFenceEnable = props.GFEnable_checkout ?? false;
               const CO_GeoFenceRadius = props.GFRadius_checkout ?? '';

               setGeoFenceEnable_Checkout(CO_GeoFenceEnable);
               setGeoFenceRadius_Checkout(CO_GeoFenceRadius);

               // ---- NAVIGATION CHECK ----
               if (props.isDataDownloaded && !props.isAttendanceMarked) {
                  props.navigation.pop();
                  props.navigation.push('Attendance');
                  return;
               }

               let dS = await fetchLoginInfo()
               let ds2 = dS || desig

               console.log("desig-----", ShowStoreSearch, dS);

               // ---- CONDITIONAL ASYNC CALL ----
               if (ShowStoreSearch && ds2 !== "Supervisor") {
                  console.log("THIS IS MANAGER");
                  await getCheckedInData(isAdhocRef.current, isNPNDRef.current, empData1);
               } else {
                  console.log("THIS IS SUPERVISOR");
                  await getData(empData1, isAdhoc, isNPND);
               }

            } catch (err) {
               console.log("Error in useFocusEffect async:", err);
            }
         };

         run();

         return () => {
            isActive = false; // cleanup
         };
      }, [])
   );



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

   function ChangeShowCamera(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("distanceeee-->",distance)
                  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);

                  if (props.GeoFenceEnable == true && distance > props.GeoFenceRadius) {
                     setShowDistanceModal(true);
                  }
                  else {
                     props.navigation.navigate('StoreCheckin', { storeData: currentStore, empData: EmpData, 'isAdhoc': isAdhocScreen, 'IsSearchedStore': showSearchWiseStore, 'isNPND': isNPNDScreen });
                  }
               },
               (error) => {
                  notify(ST.Cannotgetuserposition);
               },
               { enableHighAccuracy: true, distanceFilter: 0, interval: 1000, fastestInterval: 2000 }
            );
         }
         else {
            notify(ST.Pleaseallowlocationpermission);
         }
      }
      else {
         notify(ST.Storelocationnotavailable);
      }

   }

   async function getData(empData1, isAdhoc, isNPND) {
      setLoaderTitle("Loading...");
      setProcessing(true);
      let d1 = new Date();
      let d2 = moment(d1).format('MM/DD/YYYY');

      let loginInfo = await get_item('loginInfo');
      const loginDetails = JSON.parse(loginInfo);
      let projectInfo = await get_item('projectInfo');
      //  const storewisePjp = await fetchProjectConfig(props.ManagerAppConfig);
       const {StorewisePJP: storewisePjp, StoreSearch: storeSearch } = await fetchProjectConfig(props.ManagerAppConfig);
      console.log('storewisePjpMid::', storewisePjp, storeSearch);

      let projectDetails = projectInfo != null ? JSON.parse(projectInfo) : {};
      let SUP_StorewisePJP = projectDetails?.SUP_StorewisePJP != null ? projectDetails?.SUP_StorewisePJP : ''
      let columKey = loginDetails?.Designation == "Supervisor" ? "MerchandiserId" : "EmpId";

      console.log("storewisePjpGetData>>:", storewisePjp);

      try {
         let q = '';
         // when SUP_StorewisePJPis is true then check if data exists or not 
         if (loginDetails?.Designation == "Supervisor" && storewisePjp == true) {
            if (isAdhoc == true) {
               q = `Select * from Sup_JourneyPlanStorewiseSup_Adhoc where VisitDate='${d2}'  `;
            } else if (isNPND) {
               q = `Select * from Sup_NPNDStore where VisitDate='${d2}' `;
            }
            else {
               q = `Select * from Sup_JourneyPlanStorewiseSup where VisitDate='${d2}' `;
            }
         }

         // when SUP_StorewisePJPis is false  
         else {
            if (isAdhoc == true) {
               q = `Select * from Sup_AdhocJourneyPlan where VisitDate='${d2}' and ${columKey}='${empData1?.EmpId}' `;
            } else if (isNPND) {
               q = `Select * from Sup_NPNDStore where VisitDate='${d2}' `;
            }
            else {
               q = `Select * from Sup_JourneyPlan where VisitDate='${d2}' and ${columKey}='${empData1?.EmpId}' `;
            }
            console.log('YE WALA DATA');

            //  For non-supervisor case ========
            if (showSearchWiseStore === true) {
               //  Case 1 & 2 merged ( teamwise case (any of them like sup or am/pm)
               if (isAdhoc == true) {
                  q = `Select * from Sup_AdhocJourneyPlan where VisitDate='${d2}' and ${columKey}='${empData1?.EmpId}' `;
               } else if (isNPND) {
                  q = `Select * from Sup_NPNDStore where VisitDate='${d2}' `;
               } else {
                  q = `Select * from Sup_JourneyPlan where VisitDate='${d2}' and ${columKey}='${empData1?.EmpId}' `;
               }
            }


            //  CONDITIONS FOR STOREWISE PJP
            else if (storewisePjp === true && showSearchWiseStore === false) {
               // console.log('Case 3 storewisepjp true + no search');
               //  Case 3 storewisepjp true + no search
               if (isAdhoc == true) {
                  // q = `Select * from Sup_JourneyPlanStorewiseSup_Adhoc where VisitDate='${d2}' and ${columKey}='${empData1?.EmpId}' `;  //changes by Ajeet
                  q = `Select * from Sup_JourneyPlanStorewiseSup_Adhoc where VisitDate='${d2}' `;
               } else if (isNPND) {
                  q = `Select * from NPNDStore where VisitDate='${d2}' `;
               } else {
                  // q = `Select * from Sup_JourneyPlanStorewiseSup where VisitDate='${d2}' and ${columKey}='${empData1?.EmpId}' `;  //changes by Ajeet
                  q = `Select * from Sup_JourneyPlanStorewiseSup where VisitDate='${d2}' `;
               }
            }
         }

         // console.log("Queryyyyyy in getData() ==> ", q)

         db.transaction(async function (txn) {

            txn.executeSql(q, [], async function (txn2, txnres2) {
               await DownloadMappingSurvey(empData1, storewisePjp);
               console.log('AllStores check:', txnres2.rows.length);
               if (txnres2.rows.length > 0) {
                  let AllStores = await getdownloadedPJP(empData1, isAdhoc, isNPND, storewisePjp);
                  console.log('AllStores:', AllStores.length, JSON.stringify(AllStores));
                  console.log("console 1");
                  setState({ storeList: AllStores });
                  setGlobalStorelist(AllStores);
                  setProcessing(false); setNodataFound(false);
               }
               else if (storewisePjp == false) { // download PJP emp only when Store list is shown Employee Wise i.e. SUP_StorewisePJP is false   
                  let AllStores = await DownloadPJP(empData1, isAdhoc, isNPND, storewisePjp);
                  let isdataNotFound = AllStores.length > 0 ? false : true;
                  console.log("console 2");
                  setState({ storeList: AllStores });
                  setGlobalStorelist(AllStores);
                  setrerenderdata(!rerenderdata);
                  setProcessing(false); setNodataFound(isdataNotFound);
               }
               else {
                  setProcessing(false); setNodataFound(true);
               }
            }, function (txn2, txnerr) { console.log(txnerr); setProcessing(false); notify(ST.Nodatafound); setNodataFound(true); });
         });
      }
      catch (err) {
         console.log(err);
      }
   }

   async function getCheckedInData(isAdhoc, isNPND, empData1) {
      setLoaderTitle("Loading...");
      setProcessing(true);
      try {
         let AllStores = await getAlreadyCheckedInStores(isAdhoc, isNPND);
         console.log('AllStores:', AllStores.length);
         setState({ storeList: AllStores });
         setGlobalStorelist(AllStores);

         if (AllStores.length > 0) {
            setNodataFound(false);
         }
         else {
            // getData(empData1, isAdhoc, isNPND);
            setNodataFound(true);
         }
         setProcessing(false);
      } catch (err) {
         console.log("err in getCheckedInData:");
      }
   }

   async function getAlreadyCheckedInStores(isAdhoc, isNPND) { // need check
      console.log("get already checkedin store ------")
      let d1 = new Date();
      let d2 = moment(d1).format('MM/DD/YYYY');

      return new Promise((resolve, reject) => {

         var q = '', join_tbl = 'Sup_JourneyPlan', tb2 = AppTables.CHECKIN_DATA;

         var join = ` left outer join ${tb2} on ${tb2}.STORE_ID=${join_tbl}.StoreId and ${tb2}.JCP_TYPE='${join_tbl}' and ${tb2}.VISIT_DATE='${d2}' and ${tb2}.EMP_ID=${join_tbl}.MerchandiserId  and ${join_tbl}.UploadStatus in ('I','C','D','U','L')  `;
         var orderby = ` group by ${join_tbl}.StoreId,${join_tbl}.VisitDate  order by ${join_tbl}.StoreName,${tb2}.KEY_ID desc`;

         // get data from PJP /adhoc table
         q = `Select ${join_tbl}.*,${tb2}.CHECKIN_TIME as CheckInTime ,${tb2}.CHECKOUT_TIME as CheckOutTime from ${join_tbl} ${join}  where ${join_tbl}.VisitDate='${d2}' and UploadStatus!='N' `;
         q += ` ${orderby}`;

         // q=`select * from ${join_tbl}`;
         console.log("storelist q getAlreadyCheckedInStores:", q);
         db.transaction(async function (txn) {


            txn.executeSql(q, [], async function (txn2, txnres2) {
               console.log('storelist len', txnres2.rows.length);
               if (txnres2.rows.length > 0) {
                  // show from local
                  var storeArr = [];
                  console.log(txn2, 'storelist len2', txnres2.rows.length);
                  for (var i = 0; i < txnres2.rows.length; i++) {
                     console.log("txnres2.rows==========", txnres2.rows);
                     console.log("txnres2.rows.length", txnres2.rows.length, txnres2.rows.item(i));
                     let sdata = txnres2.rows.item(i);

                     console.log("sdata---->>>>", sdata);
                     let { InTime, OutTime, UploadStatus, StoreId, MID } = sdata;


                     let time = sdata?.CheckInTime
                        ? moment(sdata?.CheckInTime, sdata?.CheckInTime.includes('/')
                           ? "MM/DD/YYYY HH:mm:ss"
                           : "HH:mm:ss"
                        ).format("HH:mm:ss")
                        : '';

                     let time2 = sdata?.CheckOutTime
                        ? moment(sdata?.CheckOutTime, sdata?.CheckOutTime.includes('/')
                           ? "MM/DD/YYYY HH:mm:ss"
                           : "HH:mm:ss"
                        ).format("HH:mm:ss")
                        : '';

                     let In_Time = (time == '' && UploadStatus != '' && UploadStatus != 'N') ? InTime : time;
                     let Out_Time = (time2 == '' && UploadStatus != '' && UploadStatus != 'N' && UploadStatus != 'I') ? OutTime : time2;
                     sdata.CheckInTime = In_Time;
                     sdata.CheckOutTime = Out_Time;

                    
                     console.log("MenuList=======12");
                     let MenuList = await getMenuList(sdata, isAdhoc, isNPND, checkPosale = false);
                     console.log("MenuList=======", MenuList);
                     let allDone = MenuList.length > 0 ? await getDailyMenu(sdata, isAdhoc, isNPND) : true;

                     sdata.allDone = allDone;
                     sdata.MenuList = MenuList || [];
                     storeArr.push(sdata);
                     setStoreData(sdata);

                     if (i == (txnres2.rows.length - 1)) {
                        console.log("storeArr:", storeArr.length);
                        resolve(storeArr);
                     }
                  }
               }
               else {
                  resolve([]);
               }
            }, function (txn2, txnerr) { console.log(txnerr); resolve([]); });
         });
      }).catch((err) => {
         console.log(err);
         return [];
      })

   }

   async function DownloadPJP(empData1, isAdhoc, isNPND, storewisePjp) {
      console.log("download PJPPP12")
      setLoaderTitle("Downloading " + (isAdhoc ? "Adhoc" : "") + " Storelist Data...");
      setProcessing(true);
      let downloadKey = isAdhoc == true ? "Sup_AdhocJourneyPlan" : isNPND ? "Sup_NPNDStore" : "Sup_JourneyPlan";

      let loginInfo = await get_item('loginInfo');
      const loginDetails = JSON.parse(loginInfo);
      const url = props.baseurl + getMethodName(METHODS.DOWNLOADJSON_METHOD);
      let data = '';

      console.log('props.SUP_StorewisePJP-->', storewisePjp);

      if (storewisePjp == true || storewisePjp == 1) {
         console.log('STORE WISE CALLED');

         data = {
            Downloadtype: downloadKey,
            Username: loginDetails.UserId,
            Param1: 0,
            Param2: storewisePjp != '' ? storewisePjp == true ? 1 : 0 : '',
         };
      }
      // Team wise condition------
      else {
         console.log('TEAM WISE CALLED');

         data = {
            Downloadtype: downloadKey,
            Username: loginDetails.UserId,
            Param1: empData1?.EmpId || EmpData?.EmpId,
            Param2: 0,
         };
      }

      console.log('TEAMWISE DATA+++++++++++>:', data);


      return await getDownloadJson1(url, data)
         .then(async (res) => {
            // console.log("DownloadPJP res:",res);
            if (res.Sup_AdhocJourneyPlan != null || res.Sup_JourneyPlan != null) {
               let storeArr = isAdhoc == true ? (res.Sup_AdhocJourneyPlan || []) : isNPND ? (res.Sup_NPNDStore || []) : (res.Sup_JourneyPlan || []);
               let isInserted = await InsertDownloadedPJP(isAdhoc, empData1?.EmpId, storeArr);
               console.log('isInserted:', isInserted)
               if (isInserted) {
                  let loginInfo = await get_item('loginInfo');
                  const loginDetails = JSON.parse(loginInfo);
                  const configData = (() => {
                     try {
                        return typeof props.ManagerAppConfig === "string"
                           ? JSON.parse(props.ManagerAppConfig)
                           : props.ManagerAppConfig;
                     } catch (e) {
                        return null;
                     }
                  })();

                  const configArray = configData?.ManagerAppConfig ?? [];
                  const currentConfig = configArray.find(
                     item => item.Designation?.toLowerCase() === loginDetails?.Designation?.toLowerCase()
                  );

                  const storewisePjp = currentConfig?.StorewisePJP;

                  let AllStores = await getdownloadedPJP(empData1, isAdhoc, isNPND, storewisePjp);
                  console.log("getdownloadedPJP res after download:", AllStores.length);
                  setProcessing(false);
                  notify("Storelist downloaded successfully.");
                  return AllStores;
               }
               else {
                  setProcessing(false);
                  notify("Cannot download storelist data! Error in saving data.");
                  return [];
               }
            }
            else {
               notify('No data found!');
               setProcessing(false);
               return [];
            }

         })
         .catch((err) => {
            console.log('onPage Team error', err);
            setProcessing(false);
            notify("Cannot download storelist data!")
            return [];
         });
   }

   async function DownloadMappingSurvey(empData1, storewisePjp) {
      // console.log("download PJPPP");
      setLoaderTitle("Downloading....");
      setProcessing(true);
      const loginInfo = await get_item('loginInfo');
      const loginDetails = JSON.parse(loginInfo);
      const url = props.baseurl + getMethodName(METHODS.DOWNLOADJSON_METHOD);
      // Define multiple keys
      let downloadKeys = [];
      downloadKeys.push("Mapping_SurveySup")

      let combinedStoreArr = [];
      // console.log('empData1?.EmpId------>', empData1?.EmpId, EmpData?.EmpId);

      console.log("storewisePjpDownloadMappingSurvey>>", storewisePjp)

      for (let key of downloadKeys) {
         let data = {
            Downloadtype: key,
            Username: loginDetails.UserId,
            Param1: storewisePjp ? '' : empData1?.EmpId || EmpData?.EmpId,
            Param2: storewisePjp !== '' ? (storewisePjp === true ? 1 : 0) : '',
         };

         // console.log(`Downloading for key: ${key}`, data);

         try {
            const res = await getDownloadJson1(url, data);

            const storeArr =
               key === "Mapping_SurveySup" ? (res?.Mapping_SurveySup || []) : [];

            combinedStoreArr = combinedStoreArr.concat(storeArr);
         } catch (err) {
            console.log(`Error downloading ${key}:`, err);
         }
      }

      if (combinedStoreArr.length > 0) {

         let res = combinedStoreArr;
         if (res != null && !res.includes("No Data") && res?.length > 0) {
            let data_arr = res || [];
            // console.log('surveys:', data_arr.length)
            let values = [];

            // const sanitize = (str) => (str || '').replace(/'/g, "''");

            data_arr.map((data_obj) => {
               let { SurveyId, StoreId } = data_obj;
               values.push(` ('${StoreId}','${SurveyId}')`);
            });

            let all_vals = values.join(',');
            let sql_stmnt = `INSERT INTO Mapping_SurveySup(StoreId,SurveyId) values ${all_vals}`;
            // console.log('SQL:', sql_stmnt);

            await new Promise((resolve, reject) => {
               db.transaction(function (txn) {
                  txn.executeSql(`DELETE FROM Mapping_SurveySup WHERE 1=1`, [], function (txn1, txnres) {
                     txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
                        // console.log('Mapping_SurveySup added-----');
                        resolve(true);
                     }, function (txn1, txnerr) {
                        console.log('insert err:', txnerr);
                        reject(txnerr);
                     });
                  }, function (txn1, txnerr) {
                     console.log('delete err:', txnerr);
                     reject(txnerr);
                  });
               });
            });
         } else {
            setProcessing(false);
            notify("No data found!");
            return [];
         }


      } else {
         setProcessing(false);
         notify("No data found!");
         return [];
      }
   }

   async function InsertDownloadedPJP(isAdhoc, empData1, storeArr) {
      console.log("InsertDownloadedPJP======", InsertDownloadedPJP);
      return new Promise((resolve, reject) => {

         var values = [], sql_stmnt = '', all_vals = '';
         let d1 = new Date();
         let d2 = moment(d1).format('MM/DD/YYYY');
         let tbname = isAdhoc == true ? 'Sup_AdhocJourneyPlan' : 'Sup_JourneyPlan';
         let q = `Delete from ${tbname} where VisitDate='${d2}'  `;

         storeArr.map((data_obj) => {
            let { MID, ChannelId, StoreId, StoreCode, EmpId, MerchandiserId, VisitDate, ChainId, ChainName, StoreName, Address, Location, Landmark, CityId, CityName, StateId, StateName, RegionId, StoreTypeId, StoreType, Pincode, Latitude, Longitude, Phone, Mobile, ContactPerson, Email, UploadStatus, GeoTag, GeoFenceRadius, InTime, OutTime, CameraAllow } = data_obj;
            values.push(` ('${MID}', '${ChannelId}', '${StoreId}', '${StoreCode}', '${EmpId}', '${MerchandiserId}', '${VisitDate}', '${ChainId}', '${ChainName}', '${StoreName}', '${Address}', '${Location}', '${Landmark}', '${CityId}', '${CityName}', '${StateId}', '${StateName}', '${RegionId}', '${StoreTypeId}', '${StoreType}', '${Pincode}', '${Latitude}', '${Longitude}', '${Phone}', '${Mobile}', '${ContactPerson}', '${Email}', '${UploadStatus}', '${GeoTag}', '${GeoFenceRadius}', '${InTime}', '${OutTime}','${CameraAllow}')`);
         });
         all_vals = values.join(',');
         sql_stmnt = `INSERT INTO ${tbname}(MID,ChannelId,StoreId,StoreCode,EmpId,MerchandiserId,VisitDate,ChainId,ChainName,StoreName,Address,Location,Landmark,CityId,CityName,StateId,StateName,RegionId,StoreTypeId,StoreType,Pincode,Latitude,Longitude,Phone,Mobile,ContactPerson,Email,UploadStatus,GeoTag,GeoFenceRadius,InTime,OutTime,CameraAllow) 
        values ${all_vals}`;

         console.log("sql_stmnt---qweq", sql_stmnt)

         db.transaction(async function (txn) {
            await txn.executeSql(q, [], async function (txn2, txnres4) {
               console.log('removeddata');
               await txn.executeSql(sql_stmnt, [], async function (txn2, txnres2) {
                  resolve(true);
               }, function (txn2, txnerr) { console.log(txnerr); resolve(false); });
            }, function (txn2, txnerr) { console.log(txnerr); resolve(false); });
         })
      }).catch((err) => {
         console.log(err);
         return false;
      })

   }

 const isValidTime = (time) => {
  if (!time) return false;

  return moment(
    time,
    ["MM/DD/YYYY HH:mm:ss", "HH:mm:ss"],
    true
  ).isValid();
};

   async function getdownloadedPJP(empData1, isAdhoc, isNPND, storewisePjp) {

      console.log("callledddd get download PJP--")
      console.log("isNPND---", isNPND);
      let d1 = new Date();
      let d2 = moment(d1).format('MM/DD/YYYY');

      let loginInfo = await get_item('loginInfo');
      const loginDetails = JSON.parse(loginInfo);
      // console.log("loginDetails--------",loginDetails )
      let columKey = loginDetails?.Designation == "Supervisor" ? "MerchandiserId" : "EmpId";
      console.log("isAdhoc=========", isAdhoc);
      return new Promise((resolve, reject) => {
         var join_tbl = '';
         var q = '',
            tb1 = 'Sup_JourneyPlan',
            tb2 = AppTables.CHECKIN_DATA,
            tb3 = 'Sup_AdhocJourneyPlan',
            tb4 = 'Sup_JourneyPlanStorewiseSup',
            tb5 = 'Sup_JourneyPlanStorewiseSup_Adhoc',
            tb6 = 'Sup_NPNDStore';


         if (loginDetails?.Designation == "Supervisor" && storewisePjp == true) {
            join_tbl = isAdhoc == true ? tb5 : isNPND ? tb6 : tb4;
         }
         else {

            join_tbl = isAdhoc == true ? tb3 : isNPND ? tb6 : tb1;
            //  Non-supervisor logic
            if (showSearchWiseStore == true) {
               join_tbl = isAdhoc == true ? tb3 : isNPND ? tb6 : tb1;
            } else if (storewisePjp == true && showSearchWiseStore == false) {
               join_tbl = isAdhoc == true ? tb5 : isNPND ? tb6 : tb4;
            }
         }

         console.log('join_tbl', join_tbl)
         var join = ` left outer join ${tb2} on ${tb2}.STORE_ID=${join_tbl}.StoreId and ${tb2}.JCP_TYPE='${join_tbl}' and ${tb2}.VISIT_DATE='${d2}' and ${tb2}.EMP_ID=${join_tbl}.MerchandiserId  and ${join_tbl}.UploadStatus in ('I','C','D','U','L')  `;
         var orderby = ` group by ${join_tbl}.StoreId,${join_tbl}.VisitDate  order by ${join_tbl}.StoreName,${tb2}.KEY_ID desc`;


         // get data from PJP /adhoc table
         q = `Select ${join_tbl}.*,${tb2}.CHECKIN_TIME as CheckInTime ,${tb2}.CHECKOUT_TIME as CheckOutTime from ${join_tbl} ${join}  where ${join_tbl}.VisitDate='${d2}' `;

         // if SUP_StorewisePJP is true , then we don't need to include below condition in query 
         if (storewisePjp != true) {
            q += ` and ${join_tbl}.${columKey}='${empData1?.EmpId || EmpData?.EmpId}' `;
            // q+=` and ${join_tbl}.MerchandiserId='${empData1.EmpId}' `;
         }

         q += ` ${orderby}`;

console.log("storelist q getdownloadedPJP:", q);
         db.transaction(async function (txn) {
            txn.executeSql(q, [], async function (txn2, txnres2) {
               console.log('storelist len', 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);
                     console.log("sdata--------", sdata);
                     let { InTime, OutTime, UploadStatus, StoreId, MID } = sdata;
                     console.log("InTime, OutTime, UploadStatus, StoreId, MID----->>", InTime, OutTime, UploadStatus, StoreId, MID,sdata.CheckInTime,sdata.CheckOutTime );

                     let time = sdata?.CheckInTime
                        ? moment(sdata?.CheckInTime, sdata?.CheckInTime.includes('/')
                           ? "MM/DD/YYYY HH:mm:ss"
                           : "HH:mm:ss"
                        ).format("HH:mm:ss")
                        : '';

                     let time2 = sdata?.CheckOutTime
                        ? moment(sdata?.CheckOutTime, sdata?.CheckOutTime.includes('/')
                           ? "MM/DD/YYYY HH:mm:ss"
                           : "HH:mm:ss"
                        ).format("HH:mm:ss")
                        : '';
                      console.log("time time2----->>", time, time2);
                     let In_Time = (time == '' && UploadStatus != '' && UploadStatus != 'N') ? InTime : time;
                     let Out_Time = (time2 == '' && UploadStatus != '' && UploadStatus != 'N' && UploadStatus != 'I') ? OutTime : time2;
                     sdata.CheckInTime = In_Time;
                     sdata.CheckOutTime = Out_Time;

                    
                     console.log("checkintime---->>",sdata.CheckInTime,sdata.CheckOutTime );
                     let MenuList = await getMenuList(sdata, isAdhoc, isNPND, true);
                     let allDone = MenuList.length > 0 ? await getDailyMenu(sdata, isAdhoc, isNPND) : true;
                     sdata.allDone = allDone;
                     sdata.MenuList = MenuList || [];
                     storeArr.push(sdata);
                     setStoreData(sdata);

                     if (i == (txnres2.rows.length - 1)) {
                        console.log("storeArr:", storeArr.length);
                        resolve(storeArr);
                     }
                  }
               }
               else {
                  resolve([]);
               }
            }, function (txn2, txnerr) { console.log(txnerr); resolve([]); });
         });
      }).catch((err) => {
         console.log(err);
         return [];
      })


   }

   async function getDailyMenu(storeData1, isAdhoc, isNPND, checkPosale = false) {

      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, isAdhoc, isNPND);

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


                     let isDone = await updateStatus(storeData1, data, isAvlbl);

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

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

   }

   async function getMenuList(storeData1, isAdhoc, isNPND, checkPosale = false) {
      let { StoreId, ChannelId, RegionId, StoreTypeId } = storeData1;

      return new Promise((resolve, reject) => {

         db.transaction(async function (txn) {
            let q = Q_MenuList(storeData1, isAdhoc, isNPND);


            txn.executeSql(q, [], async function (txn2, txnres) {

               if (txnres.rows.length > 0) {
                  let arr = [];
                  for (var i = 0; i < txnres.rows.length; i++) {
                     let data = txnres.rows.item(i);
                     let isAvlbl = await checkAvailability(storeData1, data, checkPosale);
                     // if (isAvlbl) {
                     arr.push(data);
                     // }
                     if (i == (txnres.rows.length - 1)) {
                        resolve(arr);
                     }
                  }
               }
               else {
                  resolve([]);
               }
            }, function (txn2, txnerr) { console.log(txnerr); resolve([]); });
         });
      }).then((val) => {
         return val;
      }).catch((err) => {
         console.log('')
         return []
      })
   }


   async function checkAvailability(storeData1, data, checkPosale = false) {

      return new Promise((resolve, reject) => {
         db.transaction(async function (txn) {
            let q2 = getAvailblQuery(data.ScreenName, storeData1, data, checkPosale);
            if (q2 != '' && q2 != null) {
               // console.log("checkAvailability", q2)
               txn.executeSql(q2, [], async function (txn2, txnres2) {
                  let isAvlbl = getIfAvlbl(data.ScreenName, txnres2, storeData1);
                  resolve(isAvlbl);
               }, function (txn2, 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, data);


            if (q2 != '' && q2 != null && ((isAvlbl == true) || (isAvlbl && (isAvlbl.isAvlbl == true)))) {
               txn.executeSql(q2, [], async function (txn2, txnres2) {
                  let isDone = await getIfKPIDone(data.ScreenName, txnres2, storeData1, isAvlbl, data);
                  resolve(isDone);

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

   }

   async function onCheckOut(storeData1) {
      console.log('storeData1--onCheckOut-->', storeData1);

      let isAlldone = await getDailyMenu(storeData1, isAdhocScreen, isNPNDScreen);
      // let isAlldone=await getDailyMenu(storeData1,EmpData,isAdhocScreen,isNPNDScreen);
      if (isAlldone == true) {
         setCheckOutStore(storeData1);
         setShowAlert(true);
      }
      else {
         notify(ST.PleasefillallKPI, false);
      }
   }

   function onSaveCancel() {
      setShowAlert(false);
   }


   async function getLocOnCheckout() {
      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);
            setProcessing(false);
            // 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) {
                  notify(ST.Youcannotcheckout + ' ' + ST.Youarenotwithinthealloweddistancefromthestore + ' ' + GeoFenceRadius_Checkout + ' m', 'LONG')
               }
               else {
                  checkOutAfterLoc(loc);
               }
            }
            else {
               checkOutAfterLoc(loc);
            }

         },
         (error) => {
            notify(ST.Cannotgetuserposition);
            setProcessing(false);
         },
         { enableHighAccuracy: true, distanceFilter: 0, interval: 1000, fastestInterval: 2000 }
      );
   }

   async function checkOutAfterLoc(loc) {
      let CheckOut_PhotoReq = props.CheckOut_PhotoReq != null ? props.CheckOut_PhotoReq : false;
      if (CheckOut_PhotoReq) {
         setCheckOutLoc(loc);
         setShowAlert(false);
         setCheckOutImageModal(true);
      }
      else {
         UpdateCheckOutStatus(loc);
      }
   }

   async function UpdateCheckOutStatus(loc) {

      setLoaderTitle(ST.UpdatingCheckoutStatus + '...');
      setProcessing(true);
      let { StoreId, MID, EmpId, MerchandiserId } = checkOutStore;
      let CheckOut_PhotoReq = props.CheckOut_PhotoReq != null ? props.CheckOut_PhotoReq : false;

      console.log(CheckOut_PhotoReq, "CheckOut_PhotoReq")

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

       const {StorewisePJP: storewisePjp, StoreSearch: storeSearch } = await fetchProjectConfig(props.ManagerAppConfig);
      console.log("storewisePjpStatuss::",storeSearch, storewisePjp);

      // const loginDetails = JSON.parse(loginInfo);
      // let data1 = '';
      // const configData = (() => {
      //    try {
      //       return typeof props.ManagerAppConfig === "string"
      //          ? JSON.parse(props.ManagerAppConfig)
      //          : props.ManagerAppConfig;
      //    } catch (e) {
      //       return null;
      //    }
      // })();

      // const configArray = configData?.ManagerAppConfig ?? [];
      // const currentConfig = configArray.find(
      //    item => item.Designation?.toLowerCase() === loginDetails?.Designation.toLowerCase()
      // );

      // const storewisePjp = currentConfig?.StorewisePJP;

      data1 = {
         "UserId": loginDetails.UserId,
         "StoreId": StoreId,
         "MerchandiserId": MerchandiserId,
         "Latitude": loc.lat,
         "Longitude": loc.lng,
         "CheckoutDate": d2,
         "CheckOutImage": CheckOut_PhotoReq == true ? CheckOutImage : '',

      }

      // let fpath=Platform.OS=='ios'?CheckOutImagePath.replace('file://',''):CheckOutImagePath;
      var data2 = new FormData();
      data2.append('file', {
         uri: CheckOutImagePath,
         type: 'image/jpg',
         name: CheckOutImage,
      });

      let foldername = getFolderName(CheckOutImage);
      data2.append('Foldername', foldername);
      data2.append('Path', d2);

      console.log('data1=====>', data1);
      console.log('data2--------->', data2);


      const url = props.baseurl + getMethodName(METHODS.CHECKOUTDETAIL_METHOD);
      const url1 = (props.imageUploadUrl || URL_IMAGE) + getMethodName(METHODS.UPLOADIMAGES_METHOD);
      console.log(url, data1);
      await UploadData2(url, data1)
         .then(async (res) => {
            console.log('StoreCheckOutSup1:', res, 'MID:', MID);
            if (!res.error) {
               if (res == 1) {
                  //Check out completed
                  if (CheckOut_PhotoReq) {
                     // Upload Image 
                     await UploadFormData(url1, data2)
                        .then(async (res1) => {
                           console.log('checkout image upload:', res1);
                           cancelImage();
                        })
                        .catch((err) => {
                           console.log(err);
                        });
                  }


                  let data = { checkout_image: '' };
                  const isCheckOutUpdated = await UpdateStoreCheckOut(data);

                  if (isCheckOutUpdated == true) {
                     let datan = '';

                     let ShowStoreSearch = storeSearch?storeSearch : false;

                     if (ShowStoreSearch && designation != "Supervisor") {
                        datan = { StoreId: StoreId, UploadStatus: 'C', tbname: 'Sup_JourneyPlan', EmpId: MerchandiserId };
                     }
                     else if (ShowStoreSearch ? (designation == "Supervisor" && storewisePjp == true) : storewisePjp == true) {
                        datan = { StoreId: StoreId, UploadStatus: 'C', tbname: (isAdhocScreen == true ? 'Sup_JourneyPlanStorewiseSup_Adhoc' : isNPNDScreen ? "Sup_NPNDStore" : 'Sup_JourneyPlanStorewiseSup'), EmpId: MerchandiserId };
                     }
                     else {
                        datan = { StoreId: StoreId, UploadStatus: 'C', tbname: (isAdhocScreen == true ? 'Sup_AdhocJourneyPlan' : isNPNDScreen ? "Sup_NPNDStore" : 'Sup_JourneyPlan'), EmpId: MerchandiserId };
                     }

                     console.log("datan==============1", 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);
                        setLoaderTitle(ST.UploadingData + '...');
                        UploadOnCheckOut(loc, storewisePjp,storeSearch);
                     }
                     else {
                        setProcessing(false); notify(ST.Erroroccurwhilecheckout, 'LONG');
                     }
                  }
                  else {
                     notify(ST.Erroroccurwhilecheckout, 'LONG');
                  }

               }
               else {
                  notify(ST.Somethingwentwrong, 'SHORT'); setProcessing(false);
               }
            }
            else {
               notify(ST.Somethingwentwrong, 'SHORT'); setProcessing(false);
            }
         })
         .catch((err) => {
            console.log('onPage Team error', err);
            notify(ST.Somethingwentwrong, 'SHORT'); 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;
         // console.log('storeArr',storeArr)
         console.log("console 4")
         setState({ ...state, storeArr });
         setGlobalStorelist(storeArr);
         setrerenderdata(!rerenderdata);
      }
   }

   async function UpdateStoreCheckOut(data) {
      console.log('UpdateStoreCheckOut')
      let CheckOut_PhotoReq = props.CheckOut_PhotoReq != null ? props.CheckOut_PhotoReq : false;
      let d1 = new Date();
      let d2 = moment(d1).format('MM/DD/YYYY');
      let now = moment(d1).format('MM/DD/YYYY HH:mm:ss');
      return new Promise((resolve, reject) => {
         db.transaction(async function (txn) {
            let q2 = `UPDATE ${AppTables.COVERAGE_DATA} SET CHECKOUT_TIME='${now}', CHECKOUT_IMAGE='${CheckOut_PhotoReq ? CheckOutImage : ''}' WHERE STORE_ID='${checkOutStore.StoreId}' and EMP_ID='${checkOutStore.MerchandiserId}' and VISIT_DATE='${d2}' `;

            txn.executeSql(q2, [], async function (txn2, txnres2) {
               console.log('store coverage updated');
            }, function (txn2, txnerr) { console.log(txnerr); resolve(false); });

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

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

   }

   async function UploadOnCheckOut(loc, storewisePjp,storeSearch) {
      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 = '', PJPStores1 = '', AllStores = '';

         let ShowStoreSearch = storeSearch ? storeSearch : false;

         if ((ShowStoreSearch ? (designation == "Supervisor" && storewisePjp == true) : storewisePjp == true)) {
            PJPStores = await getPJPStoresData('Sup_JourneyPlanStorewiseSup', [], d2);
            console.log('Allstores', PJPStores);
            if (isNPNDScreen) {
               PJPStores1 = await getPJPStoresData('Sup_NPNDStore', PJPStores, d2);
            } else {
               PJPStores1 = PJPStores;
            }

            AllStores = await getPJPStoresData('Sup_JourneyPlanStorewiseSup_Adhoc', PJPStores1, d2);
         }
         else {
            PJPStores = await getPJPStoresData('Sup_JourneyPlan', [], d2);
            if (isNPNDScreen) {
               PJPStores1 = await getPJPStoresData('Sup_NPNDStore', PJPStores, d2);
            } else {
               PJPStores1 = PJPStores;
            }
            AllStores = await getPJPStoresData('Sup_AdhocJourneyPlan', PJPStores1, d2);

         }


         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];
                  console.log("data===2", data);
                  const index = i;
                  let { StoreId, StoreName, EmpId, MerchandiserId, MID, UploadStatus, Status, VisitDate, REASON_ID, IMAGE, JCP_TYPE, ChannelId, StoreTypeId, ChainId, CHECKOUT_IMAGE } = data;
                  let Deviation = isAdhocScreen == true ? 1 : isNPNDScreen ? 2 : 0;

                  console.log(data, "dattaaaaaaa store list");

                  let MenuList = await getMenuList(data, isAdhocScreen, isNPNDScreen, true);
                  let allKPIs = await getKPIS(MenuList);
                  console.log("allKPIs---", allKPIs, UploadStatus);
                  // get all checkout ids data
                  // let allKPIs=['Stocks','BRS','SOS','PaidVis','AddVis','CompVis','Promotion','CompPromo','Contacts','Sale','Survey'];
                  let pdata = '';

                  if (UploadStatus == 'C') {
                     pdata = {
                        "StoreId": StoreId,
                        "VisitDate": d2,
                        // "Mid":MID,
                        "MerchandiserId": MerchandiserId,
                        "Latitude": loc.lat,
                        "Longitude": loc.lng,
                        "ReasonId": REASON_ID != '' ? REASON_ID : 0,
                        "Remark": "",
                        "CheckInImage": IMAGE,
                        "AppVersion": AppVersion,
                        "Checkout_Image": CHECKOUT_IMAGE,
                        "ChainId": ChainId,
                        "StoreTypeId": StoreTypeId,
                        "ChannelId": ChannelId,
                        "UploadStatus": 'P',
                        "UserId": loginDetails.UserId,
                        "Deviation": Deviation,
                     };


                     const url2 = props.baseurl + getMethodName(METHODS.GETCOVERAGE_METHOD);
                     console.log(url2, pdata, "data sending by me on Storelist ..........");
                     await UploadData2(url2, pdata)
                        .then(async (res) => {
                           console.log('status uploadres:', res, 'MID:', MID);

                           if (!res.error) {
                              let tbname = JCP_TYPE;
                              let datan = { StoreId: StoreId, UploadStatus: 'P', tbname: tbname, EmpId: MerchandiserId };
                              const isUpdated = await UpdateStoreStatus(props, datan);
                              if (isUpdated == true) {

                                 await updateStoreStatuslocal('P', data);
                                 await uploadAfter_P_status(index, AllStores, data, MenuList, allKPIs, JCP_TYPE);

                              }
                              else {
                                 if (index == AllStores.length - 1) {
                                    setProcessing(false); notify(ST.Erroroccurwhileuploadingdata, 'LONG');
                                 }
                              }
                           }
                           else {
                              if (index == AllStores.length - 1) {
                                 setProcessing(false); notify(ST.Erroroccurwhileuploadingdata, 'LONG');
                              }
                           }

                        })
                        .catch((err) => {
                           console.log(err);
                           if (index == AllStores.length - 1) {
                              setProcessing(false); notify(ST.Erroroccurwhileuploadingdata, 'LONG');
                           }
                        });
                  }
                  else if (UploadStatus == 'D') {
                     //  this never be called if there is no KPI
                     console.log("UploadStatusD");
                     let allFilesToUpload = await uploadAllData(props, data, allKPIs, props.UserId, JCP_TYPE, false, MenuList,false);

                     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);
                        }
                     }
                  }
                  else if (UploadStatus == 'P') {
                     await uploadAfter_P_status(index, AllStores, data, MenuList, allKPIs, JCP_TYPE);
                  }
                  else if (UploadStatus == 'L') {
                     let isAllUploaded_S = await uploadStoreStatus(props, data, 'U', JCP_TYPE, EmpData);
                     if (isAllUploaded_S == true) {
                        await updateStoreStatuslocal('U', data);
                        notify(ST.Alldatauploadedfor + ' ' + StoreName, 'SHORT');
                        if (index == AllStores.length - 1) {
                           setProcessing(false);
                        }
                     }
                     else {
                        if (index == AllStores.length - 1) {
                           setProcessing(false); notify(ST.Erroroccurwhileuploadingdata, 'LONG');
                        }
                     }
                  }
               }

            }
         });



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

   async function uploadAfter_P_status(index, AllStores, data, MenuList, allKPIs, JCP_TYPE) {
      console.log("JCP_TYPEJCP_TYPE", 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, MenuList,false);
         console.log('allFilesToUpload:', allFilesToUpload.length);
         await updateStoreStatuslocal('D', data);
         UploadDataWithImages(index, AllStores, data, MenuList, allKPIs, JCP_TYPE, allFilesToUpload);
      }
      else {
         //  Upload statua u if no data exists
         let isAllUploaded_S = await uploadStoreStatus(props, data, 'U', JCP_TYPE, EmpData);
         if (isAllUploaded_S == true) {
            await updateStoreStatuslocal('U', data);
            notify(ST.Alldatauploadedfor + ' ' + StoreName, 'SHORT');
            if (index == AllStores.length - 1) {
               setProcessing(false);
            }
         }
         else {
            if (index == AllStores.length - 1) {
               setProcessing(false); notify(ST.Erroroccurwhileuploadingdata, 'LONG');
            }
         }
      }
   }

   async function UploadDataWithImages(index, AllStores, data, MenuList, allKPIs, JCP_TYPE, allFilesToUpload) {
      console.log("JCP_TYPEJCP_TYPE", JCP_TYPE)
      let { StoreName } = data;
      console.log("data== store list", data)
      if (allFilesToUpload.length > 0) {
         setLoaderTitle(ST.UploadingImages + '...');
         console.log('set loader title');

         let isAllUploaded = await uploadAllImages(props, data, allFilesToUpload, JCP_TYPE, EmpData);

         console.log('isAllUploaded-->', isAllUploaded);


         if (isAllUploaded == true) {

            await uploadStoreStatus(props, data, 'U', JCP_TYPE, EmpData);
            await updateStoreStatuslocal('U', data);
            notify(ST.Alldataandimagesuploadedfor + ' ' + StoreName, 'SHORT');
            if (index == AllStores.length - 1) {
               setProcessing(false);
            }
         } else {
            notify(ST.Cannotuploadimagesfor + ' ' + StoreName, 'SHORT');
            if (index == AllStores.length - 1) {
               setProcessing(false);
            }
         }
      }
      else {
         let isupdatedU = await uploadStoreStatus(props, data, 'U', JCP_TYPE, EmpData);
         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) {
            setProcessing(false);
         }
      }
   }

   async function getPJPStoresData(tbname, Stores = [], d2) {
      return new Promise((resolve, reject) => {
         db.transaction(async function (txn) {
            let join, qt;
            join = `INNER JOIN ${AppTables.COVERAGE_DATA} t2 on t2.STORE_ID=t1.StoreId and t2.EMP_ID=t1.MerchandiserId and t2.JCP_TYPE='${tbname}' `;
            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','I')`
            console.log('qt111', qt);

            txn.executeSql(qt, [], async function (txn2, txnres2) {
               console.log('length of pjp', txnres2.rows.length);
               if (txnres2.rows.length > 0) {

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

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

   async function storeVisited() {
      console.log('isgeotag:', currentStore.GeoTag);
      setShowStoreVisitModal(false);

      if (currentStore.GeoTag == 'N') {
         setShowGeoTagModal(true);
      }
      else if (currentStore.UploadStatus == 'N' || currentStore.UploadStatus == '') {
         // calLocatDistance();
           props.navigation.navigate('StoreCheckin', { storeData: currentStore, empData: EmpData, 'isAdhoc': isAdhocScreen, 'IsSearchedStore': showSearchWiseStore, 'isNPND': isNPNDScreen });
      }
      else {

      }
   }

   async function storeNotVisited() {
      setShowStoreVisitModal(false);
      props.navigation.navigate('StoreNonWorkingReasons', { storeData: currentStore, empData: EmpData, 'isAdhoc': isAdhocScreen, 'IsSearchedStore': showSearchWiseStore, 'isNPND': isNPNDScreen });
   }

   async function onVisitCancel() {
      let d1 = new Date();
      let d2 = moment(d1).format('MM/DD/YYYY');
      setLoaderTitle(ST.DeletingCheckInData + '...')
      setShowCancelCIModal(false);
      setProcessing(true);
      let { MID, StoreId, EmpId, MerchandiserId } = cancelCheckOutStore;
      let postdata = '';
      // const storewisePjp = await fetchProjectConfig(props.ManagerAppConfig);
       const {StorewisePJP: storewisePjp, StoreSearch: storeSearch } = await fetchProjectConfig(props.ManagerAppConfig);

      console.log("storewisePjpVisitCancel::", storewisePjp);

      console.log("MerchandiserId:", MerchandiserId);
      let methodN = getMethodName(METHODS.DELETECOVERAGE_METHOD);
      postdata = { 'StoreId': StoreId, "UserId": props.UserId, "MerchandiserId": MerchandiserId, "VisitDate": d2 }

      if (storewisePjp == true) {
         methodN = getMethodName(METHODS.DELETECOVERAGE_METHOD_SUPWISE);
         postdata = { "MId": MID, "UserId": props.UserId }
      }
      const url = props.baseurl + methodN;
      console.log(url, postdata);
      await UploadData2(url, postdata)
         .then(async (res) => {
            console.log('delete coverage res:', res);
            if (res == '1') {
               let isdeleted = await deleteStore(cancelCheckOutStore);
               if (isdeleted == true) {

                  let data = '';

                  let ShowStoreSearch = storeSearch ? storeSearch : false;
                  let loginInfo = await get_item('loginInfo');
                  const loginDetails = JSON.parse(loginInfo);

                  let designation = loginDetails?.Designation

                  console.log("designation===", designation);

                  if (showSearchWiseStore && designation != "Supervisor") {
                     data = { "StoreId": StoreId, UploadStatus: "N", tbname: "Sup_JourneyPlan", EmpId: MerchandiserId };
                  }
                  else if (ShowStoreSearch ? (designation == "Supervisor" && storewisePjp == true) : storewisePjp == true) {
                     data = { "StoreId": StoreId, UploadStatus: "N", tbname: (isAdhocScreen == true ? 'Sup_JourneyPlanStorewiseSup_Adhoc' : 'Sup_JourneyPlanStorewiseSup'), EmpId: MerchandiserId };
                  }
                  else {
                     data = { "StoreId": StoreId, UploadStatus: "N", tbname: (isAdhocScreen == true ? 'Sup_AdhocJourneyPlan' : 'Sup_JourneyPlan'), EmpId: MerchandiserId };
                  }
                  let isUpdated = await UpdateStoreStatus(props, data);
                  if (isUpdated == true) {
                     await updateStoreStatuslocal('N', cancelCheckOutStore, true);
                     setProcessing(false);
                     console.log("check in removed called ======")
                     notify(ST.CheckInRemoved);
                     // if(showSearchWiseStore){
                     //   getCheckedInData(); // refresh user data
                     // }

                     if (ShowStoreSearch && desig != "Supervisor") {
                        getCheckedInData(isAdhocRef.current, isNPNDRef.current);
                     }
                  }
                  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) {
      let { StoreId, MerchandiserId } = storeData1;
      let allQueries = [
         `Delete from ${AppTables.COVERAGE_DATA} where STORE_ID='${StoreId}' and EMP_ID='${MerchandiserId}'`,
         `Delete from ${AppTables.CHECKIN_DATA} where STORE_ID='${StoreId}' and EMP_ID='${MerchandiserId}' `,
         `Delete from ${AppTables.GEOTAG} where STORE_ID='${StoreId}' and EMP_ID='${MerchandiserId}' `,
         // `Delete from ${AppTables.HEADER_BACK_OF_STORE} where STORE_ID='${StoreId}' and EMP_ID='${MerchandiserId}' `,
         // `Delete from ${AppTables.CHILD_BACK_OF_STORE} where STORE_ID='${StoreId}' and EMP_ID='${MerchandiserId}' `,
         // `Delete from ${AppTables.SALES} where STORE_ID='${StoreId}' and EMP_ID='${MerchandiserId}' `,
         // `Delete from ${AppTables.INSERT_OPENINGHEADER_DATA} where STORE_ID='${StoreId}' and EMP_ID='${MerchandiserId}' `,
         // `Delete from ${AppTables.STOCK_DATA} where STORE_ID='${StoreId}' and EMP_ID='${MerchandiserId}' `,
         // `Delete from ${AppTables.SHARE_OF_SHELF_IMAGE} where STORE_ID='${StoreId}' and EMP_ID='${MerchandiserId}' `,
         // `Delete from ${AppTables.SHARE_OF_SHELF_FACING_DATA} where STORE_ID='${StoreId}' and EMP_ID='${MerchandiserId}' `,
         // `Delete from ${AppTables.INSERT_SAMPLED_DATA} where STORE_ID='${StoreId}' and EMP_ID='${MerchandiserId}' `,
         // `Delete from ${AppTables.CONTACT_CONVERSION} where STORE_ID='${StoreId}' and EMP_ID='${MerchandiserId}' `,
         // `Delete from ${AppTables.INSERT_ERROR_TRACKING} where STORE_ID='${StoreId}' and EMP_ID='${MerchandiserId}' `,
         // `Delete from ${AppTables.GROOMING_IMAGE_DATA} where STORE_ID='${StoreId}' and EMP_ID='${MerchandiserId}' `,
         // `Delete from ${AppTables.ADDITIONAL_VISIBILITY} where STORE_ID='${StoreId}' and EMP_ID='${MerchandiserId}' `,
         `Delete from ${AppTables.COMPETITION_VISIBILITY} where STORE_ID='${StoreId}' and EMP_ID='${MerchandiserId}' `,
         `Delete from ${AppTables.COMPETITION_PROMOTION} where STORE_ID='${StoreId}' and EMP_ID='${MerchandiserId}' `,
         // `Delete from ${AppTables.PROMOTION_HEADER_DATA} where STORE_ID='${StoreId}' and EMP_ID='${MerchandiserId}' `,
         // `Delete from ${AppTables.PROMOTION_DATA} where STORE_ID='${StoreId}' and EMP_ID='${MerchandiserId}' `,
         // `Delete from ${AppTables.PAID_VISIBILITY_HEADER_DATA} where STORE_ID='${StoreId}' and EMP_ID='${MerchandiserId}' `,
         // `Delete from ${AppTables.PAID_VISIBILITY_CHILD_DATA} where STORE_ID='${StoreId}' and EMP_ID='${MerchandiserId}' `,
         // `Delete from ${AppTables.PAID_VIS_CHECKLIST} where STORE_ID='${StoreId}' and EMP_ID='${MerchandiserId}' `,
         `Delete from ${AppTables.STORE_IMAGES} where STORE_ID='${StoreId}' and EMP_ID='${MerchandiserId}' `,
         `Delete from ${AppTables.SURVEY} where STORE_ID='${StoreId}' and EMP_ID='${MerchandiserId}' `,
         `Delete from ${AppTables.VISAUDIT_HDR_DATA} where STORE_ID='${StoreId}' and EMP_ID='${MerchandiserId}' `,
         `Delete from ${AppTables.VISAUDIT_CHILD_DATA} where STORE_ID='${StoreId}' and EMP_ID='${MerchandiserId}' `,
         `Delete from ${AppTables.VISAUDIT_STOCK_DATA} where STORE_ID='${StoreId}' and EMP_ID='${MerchandiserId}' `,
      ]

      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) {
            txn.executeSql(q, [], async function (txn2, txnres2) {
               if (type == '1') {
                  resolve(true);
               }
               else {
                  let arr = [];
                  if (txnres2.rows.length > 0) {
                     for (var i = 0; i < txnres2.rows.length; i++) {
                        let data = txnres2.rows.item(i);
                        arr.push(data);
                     }
                     resolve(arr);
                  }
                  else {
                     resolve([]);
                  }
               }
            }, function (txn2, 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) => {
            console.log('itemstorelist', item)
            let { StoreName, StoreId, StoreCode } = item;
            StoreId = StoreId + '';

            console.log('itemteamlist', item)
            if (StoreName.toLowerCase().includes(searchedQry) || StoreCode.toLowerCase().includes(searchedQry) || StoreId.includes(searchedQry)) {
               arr.push(item);
            }
         });
      }
      else {
         arr = globalStorelist;
      }
      console.log("console 5")
      setState({ storeList: arr });
      setrerenderdata(!rerenderdata)
   }

   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, empData: EmpData, 'isAdhoc': isAdhocScreen, 'IsSearchedStore': showSearchWiseStore, 'isNPND': isNPNDScreen }); }}>
                  <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() {
      console.log('storeDistanceinMpjp', storewisePjp);

      if (storewisePjp == true) {
         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, empData: storeData, 'isAdhoc': isAdhocScreen, 'IsSearchedStore': showSearchWiseStore, 'isNPND': isNPNDScreen });
            }
         }
         else {
            setShowDistanceModal(false); props.navigation.navigate('StoreCheckin', { storeData: currentStore, empData: storeData, 'isAdhoc': isAdhocScreen, 'IsSearchedStore': showSearchWiseStore, 'isNPND': isNPNDScreen });
         }
      }

      else {
         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, empData: EmpData, 'isAdhoc': isAdhocScreen, 'IsSearchedStore': showSearchWiseStore, 'isNPND': isNPNDScreen });
            }
         }
      }
   }


   function closeImageModal() {
      setCheckOutImageModal(false);
   }

   function cancelImage() {
      setCheckOutImage('');
      setCheckOutImagePath('');
      closeImageModal();
   }

   async function openCamera() {
      setCheckOutImageModal(false);
      ChangeShowCamera(true);
      // props.navigation.navigate('CameraScreen',{'getImage':getImage,'cameraType':'front'});
   }

   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.height;


         let picture_clicked_time = new Date();
         picture_clicked_time = moment(picture_clicked_time).format('DD-MM-YYYY HH:mm:ss')


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

         await marktext1(mark_text1, imgurl)
            .then((res) => {
               if (res.success) {
                  let uri = res.uri;
                  marktext2(mark_text2, uri, imgWidth, imgHeight)
                     .then((res) => {
                        if (res.success) {
                           let picture_clickedd = new Date();
                           let picture_clicked_date = moment(picture_clickedd).format('YYYYMMDD');
                           let picture_clicked_time = moment(picture_clickedd).format('HHmmss');
                           let filename = storeData.StoreId + '_CheckoutImg-' + picture_clicked_date + '_' + picture_clicked_time + '.jpg';

                           setCheckOutImage(filename);
                           // renamefile
                           let imagePath = `${RNFS.DocumentDirectoryPath}/${filename}`;
                           RNFS.copyFile(res.uri, imagePath)
                              .then(resn => {
                                 let uri = 'file://' + imagePath;
                                 console.log('image marker', uri);
                                 setCheckOutImagePath(uri);
                              })
                              .catch(err => {
                                 console.log(ST.Errorimagefilewritefailed + '!!!');
                                 console.log(err.message, err.code);
                              });

                        }
                        else {
                           if (res.imagenotfound) {
                              notify(ST.Pleasecaptureaimage);
                           }
                           else {
                              notify(res.error);
                           }
                        }
                     });
               }
               else {
                  if (res.imagenotfound) {
                     notify(ST.Pleasecaptureaimage);
                  }
                  else {
                     notify(res.error);
                  }
               }
            });
      }
   }


   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() }}>
                     <SvgXml width={100} height={100} xml={CameraImg2} />
                  </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>
                        <TouchableOpacity style={customStyle.nonWCapImgModal_Save_btn} onPress={() => { closeImageModal(); UpdateCheckOutStatus(CheckOutLoc); }}>
                           <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>
      )

   }

   async function gotoStoreSearch() {
      props.navigation.navigate('SearchStoreList', { teamlistEmpData: EmpData, 'isAdhoc': isAdhocScreen, 'isNPND': isNPNDScreen });
      // props.navigation.navigate("SearchStoreList",{"teamlistEmpData":EmpData}); // addby me (17 apr);
   }


   const [designation, setDesignation] = useState('')

   useEffect(() => {
      (async () => {
         let loginInfo = await get_item('loginInfo');
         const loginDetails = JSON.parse(loginInfo);

         // console.log("loginDetails--------",loginDetails )
         setDesignation(loginDetails?.Designation)
         let columKey = loginDetails?.Designation == "Supervisor" ? "" : "";

      })()
   }, [])


   // console.log("designation showSearchWiseStore showsearchwise_dummy SUP_StorewisePJP --> ", designation, showSearchWiseStore, showsearchwise_dummy, props?.SUP_StorewisePJP)

  

   return (
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS == 'ios' ? true : false)}>
         {processing && <CustomLoader fullHeight={true} title={loaderTitle} />}
         <CustomHeader {...props} title={(isAdhocScreen == true ? ST.Adhoc + ' ' + ST.StoreList : ST.StoreList)} />
         {_render_StoreVisitModal()}
         {_render_GeoTagModal()}
         {_render_DistanceModal()}
         {_render_CancelCheckinModal()}
         {_OpenCaptureImage_Modal()}
         {ConfirmSaveAlert(props, showAlert, onSaveCancel, getLocOnCheckout, ST.Doyoureallywanttocheckout)}
         {/* <CustomCamera cameraType={'front'} onImageCaptured={(imgData) => { ChangeShowCamera(false); getImage(imgData) }} showCamera={showCamera} onHideCamera={() => { ChangeShowCamera(false); }} /> */}

         {console.log("setCheckOutImageModal==>", CheckOutImageModal)}
         {/* <CustomCamera
            cameraType={'front'}
            onImageCaptured={(imgData) => { ChangeShowCamera(false); getImage(imgData); setCheckOutImageModal(false) }}
            showCamera={showCamera}
            onHideCamera={() => { ChangeShowCamera(false); }}
         /> */}

           <CustomCamera cameraType={'front'} onImageCaptured={(imgData) => { setCheckOutImageModal(true); ChangeShowCamera(false); getImage(imgData) }} showCamera={showCamera} onHideCamera={() => { ChangeShowCamera(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]}>

                  {/* {designation != 'Supervisor' && showSearchWiseStore == true && (
                     <>
                        <TouchableOpacity style={customStyle.storel_searchBtnMain} onPress={() => gotoStoreSearch()}>
                           <AntDesign name="search1" size={20} color={PageTheme.$accent_color} />
                           <Text style={customStyle.storel_searchBtnMainText}>
                              {showStoreSearchLabel ? showStoreSearchLabel : 'Store Search'}
                           </Text>
                        </TouchableOpacity>

                        <View style={customStyle.storel_headCon}>
                           <Text style={customStyle.storel_headingText}>Added Stores</Text>
                        </View>
                     </>
                  )} */}

                  {designation == 'Supervisor' &&
                     <View style={customStyle.storeTab_Con}>
                        <ScrollView style={customStyle.storeTab_MenuCon} contentContainerStyle={customStyle.storeTab_Menu} horizontal={true}>
                           <TouchableOpacity disabled={(!isAdhocScreen && !isNPNDScreen) ? true : false} style={[customStyle.storeTab_pill, (!isAdhocScreen && !isNPNDScreen ? customStyle.storeTab_pillActive : {})]} onPress={() => { props.navigation.pop(); props.navigation.push('StoreList', { 'showSearchWiseStore': showSearchWiseStore, 'empData': EmpData, 'isAdhoc': false, isNPND: false }) }}>
                              <Text style={[customStyle.storeTab_pillText, (!isAdhocScreen && !isNPNDScreen ? customStyle.storeTab_pillActiveText : { color: PageTheme.$text_color })]}>{ST.Planned}</Text>
                           </TouchableOpacity>
                           <TouchableOpacity disabled={isAdhocScreen ? true : false} style={[customStyle.storeTab_pill, (isAdhocScreen ? customStyle.storeTab_pillActive : {})]} onPress={() => { props.navigation.pop(); props.navigation.push('StoreList', { 'showSearchWiseStore': showSearchWiseStore, 'empData': EmpData, 'isAdhoc': true, isNPND: false }) }}>
                              <Text style={[customStyle.storeTab_pillText, (isAdhocScreen ? customStyle.storeTab_pillActiveText : { color: PageTheme.$text_color })]}>{ST.Adhoc}</Text>
                           </TouchableOpacity>
                           {props.ShowNPND == true &&
                              <TouchableOpacity style={[customStyle.storeTab_pill, (isNPNDScreen ? customStyle.storeTab_pillActive : {})]} onPress={() => { props.navigation.pop(); props.navigation.push('StoreList', { 'showSearchWiseStore': showSearchWiseStore, 'empData': EmpData, 'isAdhoc': false, isNPND: true }) }}>
                                 <Text style={[customStyle.storeTab_pillText, (isNPNDScreen ? customStyle.storeTab_pillActiveText : { color: PageTheme.$text_color })]}>{props.ShowNPNDLabel}</Text>
                              </TouchableOpacity>
                           }
                        </ScrollView>
                     </View>}


                  {designation != 'Supervisor' && storewisePjp.StorewisePJP == false && storewisePjp.StoreSearch == false &&
                     <View style={customStyle.storeTab_Con}>
                        <ScrollView style={customStyle.storeTab_MenuCon} contentContainerStyle={customStyle.storeTab_Menu} horizontal={true}>
                           <TouchableOpacity disabled={(!isAdhocScreen && !isNPNDScreen) ? true : false} style={[customStyle.storeTab_pill, (!isAdhocScreen && !isNPNDScreen ? customStyle.storeTab_pillActive : {})]} onPress={() => { props.navigation.pop(); props.navigation.push('StoreList', { 'showSearchWiseStore': showSearchWiseStore, 'empData': EmpData, 'isAdhoc': false, isNPND: false }) }}>
                              <Text style={[customStyle.storeTab_pillText, (!isAdhocScreen && !isNPNDScreen ? customStyle.storeTab_pillActiveText : { color: PageTheme.$text_color })]}>{ST.Planned}</Text>
                           </TouchableOpacity>
                           <TouchableOpacity disabled={isAdhocScreen ? true : false} style={[customStyle.storeTab_pill, (isAdhocScreen ? customStyle.storeTab_pillActive : {})]} onPress={() => { props.navigation.pop(); props.navigation.push('StoreList', { 'showSearchWiseStore': showSearchWiseStore, 'empData': EmpData, 'isAdhoc': true, isNPND: false }) }}>
                              <Text style={[customStyle.storeTab_pillText, (isAdhocScreen ? customStyle.storeTab_pillActiveText : { color: PageTheme.$text_color })]}>{ST.Adhoc}</Text>
                           </TouchableOpacity>
                           {props.ShowNPND == true &&
                              <TouchableOpacity style={[customStyle.storeTab_pill, (isNPNDScreen ? customStyle.storeTab_pillActive : {})]} onPress={() => { props.navigation.pop(); props.navigation.push('StoreList', { 'showSearchWiseStore': showSearchWiseStore, 'empData': EmpData, 'isAdhoc': false, isNPND: true }) }}>
                                 <Text style={[customStyle.storeTab_pillText, (isNPNDScreen ? customStyle.storeTab_pillActiveText : { color: PageTheme.$text_color })]}>{props.ShowNPNDLabel}</Text>
                              </TouchableOpacity>
                           }
                        </ScrollView>
                     </View>}









                  {designation !== 'Supervisor' && (
                     <>
                        {/* Case 1 & 2: props?.SUP_StorewisePJP doesn't matter, show search when showSearchWiseStore = true */}
                        {showSearchWiseStore == true && (
                           <>
                              <TouchableOpacity style={customStyle.storel_searchBtnMain} onPress={() => gotoStoreSearch()}>
                                 <AntDesign name="search1" size={20} color={PageTheme.$accent_color} />
                                 <Text style={customStyle.storel_searchBtnMainText}>
                                    {showStoreSearchLabel ? showStoreSearchLabel : 'Store Search'}
                                 </Text>
                              </TouchableOpacity>

                              <View style={customStyle.storel_headCon}>
                                 <Text style={customStyle.storel_headingText}>Added Stores</Text>
                              </View>
                           </>
                        )}

                        {/* Case 3: props?.SUP_StorewisePJP = true & showSearchWiseStore = false */}
                        {/* {console.log("Rendering store tabs::",storewisePjp.StorewisePJP)} */}
                        {storewisePjp.StorewisePJP == true && storewisePjp.StoreSearch == false && (
                           <View style={customStyle.storeTab_Con}>
                              <ScrollView
                                 style={customStyle.storeTab_MenuCon}
                                 contentContainerStyle={customStyle.storeTab_Menu}
                                 horizontal={true}
                              >
                                 <TouchableOpacity disabled={(!isAdhocScreen && !isNPNDScreen) ? true : false} style={[customStyle.storeTab_pill, !isAdhocScreen && !isNPNDScreen ? customStyle.storeTab_pillActive : {}]}
                                    onPress={() => { props.navigation.pop(); props.navigation.push('StoreList', { showSearchWiseStore, empData: EmpData, isAdhoc: false, isNPND: false }) }}>
                                    <Text style={[customStyle.storeTab_pillText, !isAdhocScreen && !isNPNDScreen ? customStyle.storeTab_pillActiveText : { color: PageTheme.$text_color }]}>
                                       {ST.Planned}
                                    </Text>
                                 </TouchableOpacity>

                                 <TouchableOpacity disabled={isAdhocScreen ? true : false} style={[customStyle.storeTab_pill, isAdhocScreen ? customStyle.storeTab_pillActive : {}]}
                                    onPress={() => {
                                       props.navigation.pop(); props.navigation.push('StoreList', {
                                          showSearchWiseStore, empData: EmpData, isAdhoc: true, isNPND: false
                                       })
                                    }} >
                                    <Text style={[customStyle.storeTab_pillText, isAdhocScreen ? customStyle.storeTab_pillActiveText : { color: PageTheme.$text_color }]} >
                                       {ST.Adhoc}
                                    </Text>
                                 </TouchableOpacity>

                                 {props.ShowNPND == true && (
                                    <TouchableOpacity
                                       style={[
                                          customStyle.storeTab_pill,
                                          isNPNDScreen ? customStyle.storeTab_pillActive : {}
                                       ]}
                                       onPress={() => { props.navigation.pop(); props.navigation.push('StoreList', { showSearchWiseStore, empData: EmpData, isAdhoc: false, isNPND: true }) }}>
                                       <Text style={[customStyle.storeTab_pillText, isNPNDScreen ? customStyle.storeTab_pillActiveText : { color: PageTheme.$text_color }]}>
                                          {props.ShowNPNDLabel}
                                       </Text>
                                    </TouchableOpacity>
                                 )}
                              </ScrollView>
                           </View>
                        )}
                     </>
                  )}



                  <View style={customStyle.storel_searchbar}>
                     <TextInput
                        style={[customStyle.storel_searchInput]}
                        placeholder={ST.Searchby + ` ${ST.StoreName}, ${ST.StoreId}, ${ST.StoreCode}`}
                        placeholderTextColor={PageTheme.$placeholder_color}
                        value={searchedItem}
                        onChangeText={(val) => { setSearchedItem(val); FilterStores(val) }}
                        autoComplete='off'
                     />
                     <TouchableOpacity style={customStyle.storel_searchBtn} onPress={() => { FilterStores(searchedItem) }}>
                        <AntDesign style={customStyle.storel_searchBtnIcon} name='search1' size={20} color={PageTheme.$accent_color} />
                     </TouchableOpacity>
                  </View>


                  {nodataFound &&
                     <View style={customStyle.noDataCon}>
                        {
                           showSearchWiseStore == true ?
                              <Text style={customStyle.noDataText}>{`${ST.NoDataAvailable}\n Tap on Store Search on top.`}</Text>
                              :
                              <Text style={customStyle.noDataText}>{ST.NoDataAvailable}</Text>

                        }
                     </View>
                  }
                  {(props.isDataDownloaded == true && !nodataFound) &&
                     <View style={customStyle.storel_Con}>
                        <FlatList
                           data={state.storeList}
                           extraData={rerenderdata}
                           style={customStyle.listcon}
                           initialNumToRender={4}
                           contentContainerStyle={customStyle.iteml_con}
                           renderItem={({ item, index, separators }) => {
                              return (
                                 <StoreItem  {...props} item={item} EmpData={EmpData} index={index} isAdhocScreen={isAdhocScreen} isNPNDScreen={isNPNDScreen} setShowStoreVisitModal={setShowStoreVisitModal} setCurrentStore={setCurrentStore} onCheckOut={onCheckOut} storeList={state.storeList} setLoaderTitle={setLoaderTitle} setProcessing={setProcessing} setShowCancelCIModal={setShowCancelCIModal} setCancelCheckOutStore={setCancelCheckOutStore} IsSearchedStore={showSearchWiseStore} />
                              );
                           }}
                        />
                     </View>
                  }
               </View>


            </View>
         </LinearGradient>

      </Container>
   );
}



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