
import React, { useState, useEffect, memo, useRef, useCallback } from 'react';
import Container from '../components/container';
import { useFocusEffect, useRoute } from '@react-navigation/native';
import { globalStyles, customStyles, GetPageTheme } from "../styles/Global";
import { StatusBar, Image, TextInput, View, Text, ScrollView, TouchableOpacity, TouchableHighlight, Platform, PermissionsAndroid, FlatList } from 'react-native';
import { ReactReduxContext, connect, useSelector, useDispatch } from 'react-redux';
import { mapStateToProps, mapDispatchToProps } from '../reducers/contextProvider';
import SQLite from 'react-native-sqlite-2';
import { notify } from '../components/notify';
import moment from 'moment';
import { getDownloadJson, AddStore, checkRange, UploadData2, UploadData, UpdateStoreStatus, getKPIS, marktext1, marktext2, UploadFormData, getDownloadJson1, fetchProjectConfig } from '../controller/functions';
import { get_item, set_item, clear_item } from '../components/localStorage';
import { version, sloganline, appname, testurl, db, AppVersion } from '../constants/constants';
import CustomHeader from '../components/customHeader';
import { Card } from 'react-native-paper';
import { AntDesign, Entypo, EvilIcons, Feather, FontAwesome, Fontisto, Ionicons, MaterialCommunityIcons } from '../components/icons';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import NoDataComponent from '../components/NoDataComponent';
import { SvgXml } from 'react-native-svg';
import MapIcon from '../assets/performics/map_icon.svg';
import CustomModal from '../components/CustomModal';
import { AppTables } from '../constants/tableConstants';
import { _checkLocationPermission } from '../components/geolocation';
import Geolocation from 'react-native-geolocation-service';
import { getAvailblQuery, getIfAvlbl, getIfKPIDone, getQuery, Q_MenuList } from '../constants/ConstantQueries';
import { ConfirmSaveAlert } from '../components/alert';
import { getFolderName, getMethodName, METHODS } from '../constants/methodNames';
import { uploadAllData, uploadAllImages, uploadStoreStatus } from '../constants/uploadData';
import { PrimaryTheme } from '../styles/Themes';
import NetworkStatusBar from '../components/NetworkStatusBar';
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 SearchStoreList(props) {
  const route = useRoute();

  const ST = props.StaticText || {};

  // get all theme styles acc to current theme set 
  const PageTheme = GetPageTheme(props.DarkMode, route.name);
  const customStyle = customStyles(props.DarkMode, route.name);
  const [loaderTitle, setLoaderTitle] = useState();
  const [processing, setProcessing] = useState(false);
  const [isAdhocScreen, setIsAdhocScreen] = useState(false); // change 18 april (night)
  const [nodataFound, setNodataFound] = useState(false);
  const [nodataMsg, setnodataMsg] = useState("");
  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 [isNPNDScreen, setisNPNDScreen] = useState(false);

  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 [CheckInStoreIds, setCheckInStoreIds] = useState([]);
  const [showSearchWiseStore, setShowSearchWiseStore] = useState(false);

  const [EmpData, setEmpData] = useState([]);
  const [storeData, setStoreData] = useState([]);
  const [StoreObj, setStoreObj] = useState({});

  const storeRef = useRef({ storeList: [] })

  // emp data


  const [empidataofteam, setEmpIdOFTeam] = useState('');


  // serach

  const searchRef = useRef('');

  const empidRef = useRef('');



  useEffect(() => {

    let params = props.route.params ? props.route.params : {};
    const teamlistEmpData = params.teamlistEmpData || {};
    const isAdhoc = params?.isAdhoc ? params?.isAdhoc : false;
    const isNPND = params?.isNPND ? params?.isNPND : false;

    console.log("isAdhoc", isAdhoc, "isNPND", isNPND)

    // console.log("teamlistEmpData=====",teamlistEmpData?.EmpId || '');
    setIsAdhocScreen(isAdhoc);
    setisNPNDScreen(isNPND);
    setEmpIdOFTeam(teamlistEmpData?.EmpId);
    setEmpData(teamlistEmpData)
    empidRef.current = teamlistEmpData?.EmpId;


    // let empData1 = params.empData || {};
    // let showSearchWiseStore1 = params.showSearchWiseStore != null && params.showSearchWiseStore != '' ? params.showSearchWiseStore : false;
    //let ShowStoreSearch = props?.ShowStoreSearch != null ? props.ShowStoreSearch : false;
   // setShowSearchWiseStore(ShowStoreSearch);
    if (props.isDataDownloaded == true && !props.isAttendanceMarked) {
      props.navigation.pop(); props.navigation.push('Attendance');
    }
    else {

      const unsubscribe = props.navigation.addListener('beforeRemove', onBeforeRemove);

      // getData();
      return function cleanup() {

        unsubscribe();
      };
    }
  }, []);


  useFocusEffect(
    useCallback(async () => {
      // 🔥 This runs every time screen comes into focus (e.g. on back)
      // isDoneCheck();
      console.log(empidRef.current, searchRef.current, "// DownloadPJP(searchQuery);")

      if (searchRef.current != "") {
        DownloadPJP(searchRef.current, empidRef.current);
      }
      return () => {
        // cleanup logic if required
      };
    }, [])
  );

  async function isDoneCheck() {
    console.log("AutoGoToPrev-----")
    let AllStores = storeRef.current?.storeList || []
    const allDone = AllStores.length > 0
      ? await Promise.all(
        AllStores.map(async (store) => {
          console.log('Processing store:', store); // ✅ Logs each store
          return getDailyMenu(store, true, false);
        })
      )
      : true;
    let newList = AllStores.map((itm, i) => ({ ...itm, allDone: allDone[i] }))
    setState({ storeList: newList });
    console.log("newList=====", newList)
    storeRef.current = { storeList: newList }

  }

  async function getAlreadyCheckedInStores(isAdhoc, isNPND) {
    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:", q);
      db.transaction(async function (txn) {


        // await txn.executeSql(`delete from ${join_tbl}`,[],async function (txn2, txnres2) { 
        //   console.log("store data deleted")
        // },function(txn2,txnerr){console.log(txnerr);resolve([]);});

        // await txn.executeSql(`delete from ${tb2}`,[],async function (txn2, txnres2) { 
        //   console.log("checkin data deleted")
        // },function(txn2,txnerr){console.log(txnerr);resolve([]);});

        // await txn.executeSql(`delete from ${AppTables.COVERAGE_DATA}`,[],async function (txn2, txnres2) { 
        //   console.log("COVERAGE_DATA data deleted")
        // },function(txn2,txnerr){console.log(txnerr);resolve([]);});

        await 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('storelist len2', txnres2.rows.length);
            for (var i = 0; i <= txnres2.rows.length; i++) {
              let sdata = txnres2.rows.item(i);
              let { InTime, OutTime, UploadStatus, StoreId, MID } = sdata;
              let time = sdata.CheckInTime != null && sdata.CheckInTime != '' ? moment(new Date(sdata.CheckInTime)).format('HH:mm:ss') : '';
              let time2 = sdata.CheckOutTime != null && sdata.CheckOutTime != '' ? moment(new Date(sdata.CheckOutTime)).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("UploadStatus=========", UploadStatus)

              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 getCheckedInData(isAdhoc, isNPND) {
    console.log("getCheckedInData");
    setLoaderTitle("Loading...");
    setProcessing(true);
    try {
      let AllStores = await getAlreadyCheckedInStores(isAdhoc, isNPND);
      console.log('AllStores:', AllStores.length);
      // console.log("console 3")
      setState({ storeList: AllStores });
      storeRef.current = { storeList: AllStores }
      console.log("6", storeRef.current);
      setGlobalStorelist(AllStores);
      if (AllStores.length > 0) {
        setNodataFound(false);
      }
      else {
        setNodataFound(true);
      }
      setProcessing(false);
    } catch (err) {
      console.log("err in getCheckedInData:");

    }
  }

  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.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.STORE_IMAGES} where STORE_ID='${StoreId}' and EMP_ID='${MerchandiserId}' `,
      `Delete from ${AppTables.SURVEY} 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 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 = '';
    let loginInfo = await get_item('loginInfo');
    const loginDetails = JSON.parse(loginInfo);
    //  const storewisePjp = await fetchProjectConfig(props.ManagerAppConfig);
    const { StorewisePJP: storewisePjp, StoreSearch: storeSearch } = await fetchProjectConfig(props.ManagerAppConfig);
    console.log("storewisePjpSearchStoreCanc::", storeSearch, 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 = '';

            if (storeSearch) {
              data = { "StoreId": StoreId, UploadStatus: "N", tbname: "Sup_JourneyPlan", EmpId: MerchandiserId };
            }
            else if (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);
              notify(ST.CheckInRemoved);

              if (showSearchWiseStore) {
                getCheckedInData();
                DownloadPJP(searchRef.current, empidRef.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);
      });

  }


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

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

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


  async function getData() {
    setLoaderTitle("loading...")
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');

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


      let q = `select StoreId from Sup_JourneyPlan where VisitDate='${d2}' and UploadStatus!='N' `;
      db.transaction(async function (txn) {
        await txn.executeSql(q, [], async function (txn2, txnres2) {
          console.log('storelist len', txnres2.rows.length);
          if (txnres2.rows.length > 0) {
            // show from local
            let arr = [];
            for (var i = 0; i < txnres2.rows.length; i++) {
              let sdata = txnres2.rows.item(i);

              arr.push(sdata)

              if (i == (txnres2.rows.length - 1)) {
                setCheckInStoreIds(arr);
                setProcessing(false);
              }
            }
          }
          else {
            setProcessing(false);
          }
        }, function (txn2, txnerr) { console.log(txnerr); setProcessing(false); });
      });
    }).catch((err) => {
      setProcessing(false);
    })

  }



  async function calLocatDistance() {
    if (currentStore.Latitude != '' && currentStore.Latitude != null) {
      const hasPermission = await _checkLocationPermission();
      if (hasPermission == true) {
        Geolocation.getCurrentPosition(
          async (position) => {
            let loc = { lat: position.coords.latitude, lng: position.coords.longitude };

            var distance = checkRange(loc.lat, loc.lng, currentStore.Latitude, currentStore.Longitude);
            // console.log('distance:',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': true });
            }
          },
          (error) => {
            notify(ST.Cannotgetuserposition);
          },
          { enableHighAccuracy: true, distanceFilter: 0, interval: 1000, fastestInterval: 2000 }
        );
      }
      else {
        notify(ST.Pleaseallowlocationpermission);
      }
    }
    else {
      notify(ST.Storelocationnotavailable);
    }

  }

  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);
        // console.log('Executing query check availability:', q2);
        if (q2 != '' && q2 != null) {

          await txn.executeSql(q2, [], async function (txn2, txnres2) {
            let isAvlbl = getIfAvlbl(data.ScreenName, txnres2, storeData1);
            console.log(data.ScreenName, "isAvlbl:", isAvlbl); // for check the avaliable screen
            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 getMenuList(isAdhoc, isNPND, checkPosale = false) {
    let { StoreId, ChannelId, RegionId, StoreTypeId } = storeData;
    return new Promise((resolve, reject) => {

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

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

              console.log(data, "data of menu'ss")

              let isAvlbl = await checkAvailability(storeData, data, checkPosale);
              console.log("checkAvailability--------2", isAvlbl)
              // if(isAvlbl==true||isAvlbl=="true"){
              arr.push(data);
              // }

              if (i == (txnres.rows.length - 1)) {
                console.log("checkAvailability--------3", arr)
                resolve(arr);
              }
            }
          }
          else {
            resolve([])
          }
        }, function (txn2, txnerr) { console.log(txnerr); resolve([]); },);
      });
    }).then((val) => {
      return val;
    }).catch((err) => {
      console.log('err--------', err)
      return []
    })
  }


  async function SearchStore(searchQuery) {
    console.log('SEARCH QUEARYYYYYYY', searchQuery);

    if (searchQuery.trim().length >= 3) {
      DownloadPJP(searchQuery, empidRef.current);
    }
    else {
      notify("Please enter atleat 3 letters to search!")
    }
  }


  async function updateStatus(storeData1, data, isAvlbl) {
    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        let q2 = getQuery(data.ScreenName, storeData1, data);

        // console.log(q2, "isdoneKPi called--->")

        if (q2 != '' && q2 != null && ((isAvlbl == true) || (isAvlbl && (isAvlbl.isAvlbl == true)))) {
          await txn.executeSql(q2, [], async function (txn2, txnres2) {
            let isDone = await getIfKPIDone(data.ScreenName, txnres2, storeData1, isAvlbl, data);
            // console.log("isDone--->", isDone)
            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 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);

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

          if (txnres.rows.length > 0) {
            let allDone = true;
            for (var i = 0; i < txnres.rows.length; i++) {
              let data = txnres.rows.item(i);
              let isAvlbl = await checkAvailability(storeData1, data, 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;
    });

  }

  // for show checked in btn 

  async function getAlreadyCheckedInStores(isAdhoc, isNPND) {
    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:", q);
      db.transaction(async function (txn) {


        await 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('storelist len2', txnres2.rows.length);
            for (var i = 0; i <= txnres2.rows.length; i++) {
              let sdata = txnres2.rows.item(i);
              let { InTime, OutTime, UploadStatus, StoreId, MID } = sdata;
              let time = sdata.CheckInTime != null && sdata.CheckInTime != '' ? moment(new Date(sdata.CheckInTime)).format('HH:mm:ss') : '';
              let time2 = sdata.CheckOutTime != null && sdata.CheckOutTime != '' ? moment(new Date(sdata.CheckOutTime)).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(searchQuery, empid) {
    setLoaderTitle("Searching...");
    setProcessing(true);


    console.log("searchQuery, empid", searchQuery, empid)

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

    let data = {};
    data = {
      Downloadtype: "Sup_JourneyPlanSearch",
      Username: loginDetails.UserId,
      Param1: searchQuery,
      Param2: empidataofteam ? empidataofteam : empid,
    };

    console.log(url, data);
    await getDownloadJson1(url, data)
      .then(async (res) => {
        // console.log("DownloadPJP res:",res);
        if (res.Sup_JourneyPlanSearch != null || res.Sup_JourneyPlanSearch != "" && typeof res.Sup_JourneyPlanSearch == "object") {
          let AllStores = res.Sup_JourneyPlanSearch || [];
          let allMenuList = await getMenuList(true, false, true);

          const allDone = AllStores.length > 0
            ? await Promise.all(
              AllStores.map(async (store) =>
                getDailyMenu(store, true, false)
              )
            )
            : true;
          let newList = AllStores.map((itm, i) => ({ ...itm, MenuList: allMenuList, allDone: allDone[i] }))
          setNodataFound(false);
          setnodataMsg("");
          setState({ storeList: newList });
          storeRef.current = { storeList: [...newList] }
          console.log("7", storeRef.current);

        }
        // pass to the next download key if data does not exists for this Key
        else if (res != null && typeof (res) == 'object' && (res[0] != null && res[0].Result != null && res[0].Result == "No Data")) {
          setState({ storeList: [] });
          storeRef.current = { storeList: [] }
          console.log("1", storeRef.current);
          setNodataFound(true);
          setnodataMsg("No results found for your search!");

        }
        // Stop Downloading and report error
        else {
          setState({ storeList: [] });
          storeRef.current = { storeList: [] }
          console.log("2", storeRef.current);
          setNodataFound(true);
          setnodataMsg("" + res + ". Please ensure you are connected to the internet!");

        }

      }).then((res) => {
        setProcessing(false);
      })
      .catch((err) => {
        setState({ storeList: [] });
        storeRef.current = { storeList: [] }
        console.log("3", storeRef.current);

        setNodataFound(true);
        setnodataMsg("Cannot search data!");
      });
  }

  // // Insert PJP before check in 
  // async function InsertPJP(storeData1){

  //   console.log("Insert PJP store data=======>",storeData1)

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

  //         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}=storeData1;
  //         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}`;

  //         let q=`select * from ${tbname} where VisitDate='${d2}' and StoreId='${StoreId}' and  MerchandiserId='${MerchandiserId}' `;

  //         db.transaction(async function (txn) { 
  //         await txn.executeSql(q,[],async function (txn2, txnres) {
  //             if(txnres.rows.length>0){
  //                 // This store has already been added in storelistPJP!!
  //                 console.log("This store has already been added in storelistPJP!!");
  //                 // notify("This store has already been visited!")
  //                 resolve(false);
  //             }
  //             else{
  //                 // This store is not added in storelistPJP yet!! then add store
  //                 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;
  //     })

  // }



  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)
      setState({ ...state, storeArr });
      storeRef.current = { ...state, storeArr }
      console.log("4", storeRef.current);
      setGlobalStorelist(storeArr);
      setrerenderdata(!rerenderdata);
    }
  }

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

    if (currentStore.GeoTag == 'N') {
      setShowGeoTagModal(true);
    }
    else if (currentStore.UploadStatus == 'N' || currentStore.UploadStatus == '') {
      calLocatDistance();
    }
    else {

    }
  }

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




  async function executeQuery(q, type = '1') {
    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        await txn.executeSql(q, [], async function (txn2, txnres2) {
          if (type == '1') {
            resolve(true);
          }
          else {
            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 _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.replace('GeoTag', { storeData: currentStore, empData: EmpData, 'isAdhoc': isAdhocScreen, 'IsSearchedStore': true }); }}>
            <Text style={customStyle.storelVisitM_op_btnText}>{ST.OK}</Text>
          </TouchableOpacity>
        </View>
      </CustomModal>
    )

  }


  async function onDistanceM_OK() {
    // const storewisePjp = await fetchProjectConfig(props.ManagerAppConfig);
    const { StorewisePJP: storewisePjp, StoreSearch: storeSearch } = await fetchProjectConfig(props.ManagerAppConfig);
    console.log("storewisePjponDistanceM_OK:", 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': true });
        }
      }
      else {
        setShowDistanceModal(false); props.navigation.navigate('StoreCheckin', { storeData: currentStore, empData: storeData, 'isAdhoc': isAdhocScreen, 'IsSearchedStore': true });
      }
    }

    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': true });
        }
      }
    }
  }


  function closeImageModal() {
    setCheckOutImageModal(false);
  }

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

  async function openCamera() {
    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);
            }
          }
        });
    }
  }

  async function onCheckOut(storeData1) {
    console.log("storeData1--------", storeData1)
    setStoreObj(storeData1)
    let isAlldone = await getDailyMenu(storeData1, true, false);
    // let isAlldone=await getDailyMenu(storeData1,EmpData,isAdhocScreen,isNPNDScreen);
    if (isAlldone == true) {
      setCheckOutStore(storeData1);
      setShowAlert(true);
    }
    else {
      notify(ST.PleasefillallKPI, false);
    }
  }


  function _OpenCaptureImage_Modal() {
    console.log('CheckOutImagePath:', CheckOutImageModal);
    const isImageCap = (CheckOutImagePath == '' || CheckOutImagePath == null) ? false : true;
    console.log('isImageCap:', isImageCap);


    return (
      <CustomModal
        style={customStyle.nonWCapImgModal}
        title={ST.CheckOutImage}
        message={ST.Pleaseclickselfieinfrontofstore}
        titleStyle={customStyle.nonWCapImgModal_title}
        messageStyle={customStyle.nonWCapImgModal_subtitle}
        showModal={CheckOutImageModal && !showCamera}
      >
        {
          !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>
    )

  }
  function onSaveCancel() {
    setShowAlert(false);
  }

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

        await 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}' `;
        await 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 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 loginInfo = await get_item('loginInfo');
    const loginDetails = JSON.parse(loginInfo);

    let d = new Date();
    let d2 = moment(d).format('MM/DD/YYYY');
    let d3 = moment(d).format('MM/DD/YYYY HH:mm:ss');
    let data1 = '';
    //const storewisePjp = await fetchProjectConfig(props.ManagerAppConfig);
    const { StorewisePJP: storewisePjp, StoreSearch: storeSearch } = await fetchProjectConfig(props.ManagerAppConfig);

    console.log("storewisePjp:", 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);

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

              if (showSearchWiseStore) {
                datan = { StoreId: StoreId, UploadStatus: 'C', tbname: 'Sup_JourneyPlan', EmpId: MerchandiserId };
              }
              else if (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 };
              }
              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);
              }
              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 getPJPStoresData(tbname, Stores = [], d2) {
    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        let join, qt;
        qt = `Select * from ${AppTables.COVERAGE_DATA} t1 where t1.VISIT_DATE='${d2}' and t1.STATUS in ('C','P','D','L')`
        console.log('qt', qt);
        await 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);
              let tempDATa = JSON.parse(data?.STORE_OBJ)
              data["MerchandiserId"] = tempDATa?.MerchandiserId
              data["StoreId"] = data?.STORE_ID
              data["EmpId"] = tempDATa?.EmpId
              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 uploadAfter_P_status(index, AllStores, data, MenuList, allKPIs, JCP_TYPE) {
    let { StoreName } = data;
    if (MenuList.length > 0) {
      // Upload data with Images
      let allFilesToUpload = await uploadAllData(props, data, allKPIs, props.UserId, JCP_TYPE, true, 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 UploadOnCheckOut(loc) {
    try {
      console.log('UploadOnCheckOut');
      let d1 = new Date();
      let d2 = moment(d1).format('MM/DD/YYYY');
      let token = await get_item('loginToken');
      let loginInfo = await get_item('loginInfo');
      const loginDetails = JSON.parse(loginInfo);

      let PJPStores = '', PJPStores1 = '', AllStores = '';


      AllStores = await getPJPStoresData('Sup_JourneyPlan', [], d2);

      // COVERAGE_DATA

      await db.transaction(async function (txn) {
        console.log('stores to upload:', AllStores.length);
        if (AllStores.length > 0) {
          for (var i = 0; i < AllStores.length; i++) {
            let data = AllStores[i];
            const index = i;
            let { StoreId, StoreName, EmpId, UploadStatus, MerchandiserId, MID, STATUS, Status, VisitDate, REASON_ID, IMAGE, JCP_TYPE, ChannelId, StoreTypeId, STORE_OBJ, ChainId, CHECKOUT_IMAGE } = data;
            let Deviation = 1

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

            let MenuList = await getMenuList(data, true, false, true);
            console.log("checkAvailability--------4", MenuList)
            let allKPIs = await getKPIS(MenuList);
            console.log("checkAvailability--------5", allKPIs)

            let StoreObj = JSON.parse(STORE_OBJ)
            // get all checkout ids data
            // let allKPIs=['Stocks','BRS','SOS','PaidVis','AddVis','CompVis','Promotion','CompPromo','Contacts','Sale','Survey'];
            let pdata = '';
            console.log("checkAvailability--------6", STATUS)
            if (STATUS == 'C') {
              // pdata={
              //   "Mid":MID,
              //   "EmpId":MerchandiserId,
              //   "StoreId":StoreId,
              //   "VisitDate":d2,
              //   "Latitude":loc.lat,
              //   "Longitude":loc.lng,
              //   "ReasonId":REASON_ID!=''?REASON_ID:0,
              //   "Remark":"",
              //   "ImageName":IMAGE,
              //   "Appversion":AppVersion,
              //   "UploadStatus":'P',
              //   "CheckoutImage":IMAGE,
              //   "UserName":loginDetails.UserId,
              // };

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

              console.log("checkAvailability--------7", pdata)
              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
              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 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 });
      // storeRef.current={storeList:newList} //add by m
      console.log("5", storeRef.current);
      setGlobalStorelist(storeArr);
      setrerenderdata(!rerenderdata);
    }
  }

  async function UploadDataWithImages(index, AllStores, data, MenuList, allKPIs, JCP_TYPE, allFilesToUpload) {
    let { StoreName } = data;
    console.log("data============", data?.STORE_OBJ?.StoreName);
    const storeObj = JSON.parse(data.STORE_OBJ);

    console.log(storeObj?.StoreName, "StoreName")

    if (allFilesToUpload.length > 0) {
      setLoaderTitle(ST.UploadingImages + '...');
      console.log('set loader title');
      let isAllUploaded = await uploadAllImages(props, data, allFilesToUpload, JCP_TYPE, EmpData);

      if (isAllUploaded == true) {
        await updateStoreStatuslocal('U', data);
        notify(ST.Alldataandimagesuploadedfor + ' ' + storeObj?.StoreName, 'SHORT');
        if (index == AllStores.length - 1) {
          setProcessing(false);
        }
      } else {
        notify(ST.Cannotuploadimagesfor + ' ' + storeObj?.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 + ' ' + storeObj?.StoreName, 'SHORT');
      }
      if (index == AllStores.length - 1) {
        setProcessing(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 }
    );
  }

  // console.log("state.storeList on",state.storeList)
  const isAlreadyCheckedIn = state?.storeList.some(item => item.UploadStatus == "I");

  // if (isAlreadyCheckedIn) {
  //   notify(ST.Youarealreadycheckedintotheotherstore,'LONG');
  // }

  // "UploadStatus": "I",

  console.log("isAdhocScreen", isAdhocScreen);

  return (
    <Container {...props} pt={0} avoidSafeArea={(Platform.OS == 'ios' ? true : false)}>
      {processing && <CustomLoader fullHeight={true} title={loaderTitle} />}
      <CustomHeader {...props} title={'Search Stores'} />
      {_render_StoreVisitModal()}
      {_render_GeoTagModal()}
      {_render_DistanceModal()}
      {_render_CancelCheckinModal()}
      {_OpenCaptureImage_Modal()}
      {ConfirmSaveAlert(props, showAlert, onSaveCancel, getLocOnCheckout, ST.Doyoureallywanttocheckout)}
     
      {console.log("showCamera--->", CheckOutImageModal)}
      {/* <CustomCamera cameraType={'front'} onImageCaptured={(imgData) => { ChangeShowCamera(false); getImage(imgData) }} showCamera={showCamera} onHideCamera={() => { ChangeShowCamera(false); }} /> */}
      
     <CustomCamera
            cameraType={'front'}
            onImageCaptured={(imgData) => { ChangeShowCamera(false); getImage(imgData); setCheckOutImageModal(true) }}
            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]}>



            <View style={customStyle.SSt_searchbar}>
              <TextInput
                style={[customStyle.SSt_searchInput]}
                placeholder={ST.Searchby + ` ${ST.StoreName}`}
                placeholderTextColor={PageTheme.$placeholder_color}
                value={searchedItem}
                onChangeText={(val) => { setSearchedItem(val), searchRef.current = val; }}
                autoComplete='off'
              />
              <TouchableOpacity style={customStyle.SSt_searchBtn} onPress={() => { SearchStore(searchedItem) }}>
                <AntDesign style={customStyle.SSt_searchBtnIcon} name='search1' size={20} color={PageTheme.$accent_color} />
              </TouchableOpacity>
            </View>

            <View style={[customStyle.storel_headCon, customStyle.mt10]}>
              <Text style={customStyle.storel_headingText}>Stores matching your search</Text>
            </View>

            {nodataFound &&
              <View style={customStyle.noDataCon}>
                <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 isAlreadyCheckedIn={isAlreadyCheckedIn} {...props} item={item} EmpData={EmpData} index={index} isAdhocScreen={isAdhocScreen} setShowStoreVisitModal={setShowStoreVisitModal} setCurrentStore={setCurrentStore} onCheckOut={onCheckOut} storeList={state.storeList} setLoaderTitle={setLoaderTitle} setProcessing={setProcessing} setShowCancelCIModal={setShowCancelCIModal} setCancelCheckOutStore={setCancelCheckOutStore} IsSearchedStore={true} CheckInStoreIds={CheckInStoreIds} />
                    );
                  }}
                />
              </View>
            }
          </View>


        </View>
      </LinearGradient>

    </Container>
  );
}

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