import React, { useState, useEffect, useCallback } from 'react';
import Container from '../components/container';
import { useRoute, useFocusEffect } from '@react-navigation/native';
import { globalStyles, customStyles, GetPageTheme } from "../styles/Global";
import { StatusBar, Image, TextInput, View, Text, ScrollView, TouchableOpacity, Platform, PermissionsAndroid, FlatList, Alert } from 'react-native';
import { ReactReduxContext, connect, useSelector, useDispatch } from 'react-redux';
import { mapStateToProps, mapDispatchToProps } from '../reducers/contextProvider';
import { notify } from '../components/notify';
import moment from 'moment';
import { getDownloadJson, getKPIFields, goToMenuPage } from '../controller/functions';
import { get_item, set_item, clear_item } from '../components/localStorage';
import { version, sloganline, appname, testurl, db, colors_Arr, HierarchyTbls } from '../constants/constants';
import CustomHeader from '../components/customHeader';
import { AntDesign, FontAwesome } from '../components/icons';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import { AppTables } from '../constants/tableConstants';
import { checkFilledSurveys, getAvailblQuery, getIfAvlbl, getIfKPIDone, getQuery, Q_GetAvailabityDefaultData, Q_GetAvailablePrds, Q_getCategoryforAdditional, Q_getdefaltShareofSelf, Q_getMyStoresMenuList, Q_getpaidvisibility, Q_getpromotionmappingList, Q_getSamplingData, Q_getSurveys, Q_MenuList } from '../constants/ConstantQueries';

import grey_bg_image from '../assets/performics/circle_grey.svg';
import CustomModal from '../components/CustomModal';

function StoreDailyMenu(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 [processing, setProcessing] = useState(true);
  const [loaderTitle, setLoaderTitle] = useState();
  const [isAdhocScreen, setIsAdhocScreen] = useState(false);
  const [isNonMerchan, setIsNonMerchan] = useState(false);
  const [isNonProg, setIsNonProg] = useState(false);
  const [isStoreSearch, setIsStoreSearch] = useState(false);
  const [isBeatPlan, setIsBeatPlan] = useState(false);
  const [storeData, setStoreData] = useState({});
  const [dailyMenu, setDailyMenu] = useState([]);

  const [refreshMenuRender, setRefreshMenuRender] = useState(0);
  const [isLoaded, setIsLoaded] = useState(false);
  const [showAlert, setShowAlert] = useState(false);
  const [BgNavigateData, setBgNavigateData] = useState({});
  const [BgScreenName, setBgScreenName] = useState('');
  const [BgScreenMenu, setBgScreenMenu] = useState({});
  const [IsBackstate, setIsBackstate] = useState(false);
  ///grooming
  const [showGroomingPicModal, setShowGroomingPicModal] = useState(false);

  useEffect(() => {
    setLoaderTitle(ST.Loading + '...')
    let params = props.route.params ? props.route.params : {};
    let storeData1 = params.storeData || {};
    let isAdhoc = params.isAdhoc || false;
    let isBeat = params.isBeat != null ? params.isBeat : false;
    let isNonMerchan1 = params.isNonMerchans != null ? params.isNonMerchans : false;
    let isNonProgam = params.isNonProgs != null ? params.isNonProgs : false;
    let isStoreSearch = params.isStoreSearch != null ? params.isStoreSearch : false;
    console.log('isAdhoc in sdmenu:', isAdhoc)
    setIsAdhocScreen(isAdhoc);
    setIsBeatPlan(isBeat);
    setIsNonMerchan(isNonMerchan1)
    setIsNonProg(isNonProgam)
    setIsStoreSearch(isStoreSearch)
    setStoreData(storeData1);
    getDailyMenu(storeData1, false, isAdhoc, isBeat, isNonMerchan1, isNonProgam, isStoreSearch);
    const willFocusSubscription = props.navigation.addListener('focus', () => {
      console.log('storedailymenu onfocus');
      setIsBackstate(true)
      getDailyMenu(storeData1, false, isAdhoc, isBeat, isNonMerchan1, isNonProgam, isStoreSearch, true);
    });
    return willFocusSubscription;
  }, []);

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


  useEffect(() => {
    console.log('AutoGoToPrev dailmenu onchange', props.AutoGoToPrev);
    if (props.AutoGoToPrev == true) {
      getDailyMenu(storeData, true, isAdhocScreen, isBeatPlan, isNonMerchan, isNonProg, isStoreSearch);
    }
  }, [props.AutoGoToPrev]);

  function _render_Alert() {
    let BgNavScreenName = (BgScreenName && BgScreenName.ScreenName) || '';
    let BgNavFlag = false
    if (BgNavScreenName == 'SURVEY') {
      BgNavFlag = true
    } else if (BgNavScreenName == 'STOREIMG') {
      BgNavFlag = true
    } else if (BgNavScreenName == 'ORDERSTATUS') {
      BgNavFlag = true
    }


    console.log("test000000000", BgNavFlag, BgNavigateData)
    let sname = Object.keys(BgScreenMenu).length > 0 && BgScreenMenu.MenuId != "" ? BgScreenMenu.MenuName : (BgScreenName.ScreenName != null ? BgScreenName.ScreenName : '');
    return (
      <CustomModal
        style={customStyle.storelVisitM_Style}
        titleStyle={customStyle.storeDaily_titleStyle}
        title={`You have unsaved changes in ${sname}`}
        message={'Please save your last changes'}
        showModal={showAlert}
      >
        <View style={customStyle.storelVisitM_options}>
          {/* <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={()=>{setShowAlert(false)}}>
              <Text style={customStyle.storelVisitM_op_btnText}>Cancel</Text>
            </TouchableOpacity> */}
          <TouchableOpacity style={customStyle.storelVisitM_op_btn} onPress={() => { setShowAlert(false); gotoKPITaskScreen(BgScreenName, BgNavFlag, BgNavigateData, BgScreenMenu); }}>
            <Text style={customStyle.storelVisitM_op_btnText}>Ok</Text>
          </TouchableOpacity>
        </View>
      </CustomModal>
    )
  }


  async function getGroomingPicsData() {
    try {
      db.transaction((txn) => {
        const menuQuery = `SELECT * FROM Master_GroomingImages `;
        // First: Fetch Menu
        txn.executeSql(menuQuery, [], (txn2, txnres) => {
          const len = txnres.rows.length;
          const groomingArr = [];
          for (let i = 0; i < len; i++) {
            let data = txnres.rows.item(i);
            console.log("data--------", data)
            if (data.GroomingImages) {
              data['GroomingImages'] = JSON.parse(data?.GroomingImages || [])
            }
            groomingArr.push(data);
          }
          const now = new Date();
          const currentTime = now.toTimeString().slice(0, 8);
          const isTimeBetween = (current, start, end) =>
            current >= start && current <= end;
          const filtered = groomingArr.filter(item => {
            const hasImages = item?.GroomingImages && item?.GroomingImages?.length > 0;
            const inTime = isTimeBetween(currentTime, item.StartTime, item.EndTime);
            return inTime && !hasImages; // ✅ include if time matches OR images exist
          });
          console.log("filtered-----", filtered)
          ///need to check grooming images popup
          if (filtered && filtered.length > 0 && props.GroomingObj && Object.keys(props.GroomingObj || {}).length > 0 && props.GroomingObj !== undefined) {
            setShowGroomingPicModal(true)
          }
        }, (txn2, err2) => {
          console.error("Menu fetch error:", err2);
        });
      });
    } catch (err) {
      console.error("getData error:", err);
    }
  }

  function _render_GroomingPicturesModal(item) {
    return (
      <CustomModal
        style={[
          customStyle.storelVisitM_Style,
          {
            borderRadius: 20,       // ✅ more rounded
            padding: 20,
            backgroundColor: 'white',
            shadowColor: '#000',
            shadowOffset: { width: 0, height: 2 },
            shadowOpacity: 0.25,
            shadowRadius: 4,
            elevation: 5,           // Android shadow
          },
        ]}
        title={
          <Text style={{ fontWeight: 'bold', color: 'red', fontSize: 18 }}>
            {props.GroomingObj?.GroomingTitle || 'Grooming Picture'}
          </Text>
        }

        titleStyle={customStyle.storelVisitM_titleStyle}
        showModal={!processing && showGroomingPicModal}
      >
        <View style={{ flexDirection: 'column', alignItems: 'center', marginVertical: 10 }}>
          <Text style={{ color: 'black', fontSize: 16, textAlign: 'center', marginHorizontal: 20 }}>
            {props.GroomingObj?.GroomingMsg || 'Please click your full-length photograph.'}
          </Text>
        </View>

        {/* Proceed Button at bottom center */}
        <View style={{ alignItems: 'center', marginTop: 20 }}>
          <TouchableOpacity
            style={{
              backgroundColor: '#4CAF50',
              paddingVertical: 10,
              paddingHorizontal: 30,
              borderRadius: 10,
            }}
            onPress={() => {
              // 👉 Handle Proceed Action
              props.navigation.navigate('GroomingPictures', { storeData: storeData, 'isAdhoc': isAdhocScreen, 'isBeat': isBeatPlan, "isNonMerchans": isNonMerchan, isNonProgs: isNonProg, 'isStoreSearch': isStoreSearch, '_fromStoreWise': true });
              setShowGroomingPicModal(false); // or your handler
            }}
          >
            <Text style={{ color: 'white', fontWeight: 'bold', fontSize: 16 }}>
              Proceed
            </Text>
          </TouchableOpacity>
        </View>
      </CustomModal>

    )
  }


  async function getDailyMenu(storeData1, isAutoBack = false, isAdhoc, isBeat, isNonMerchan1, isNonProgam, isStoreSearch, IsBacksta = false) {
    setProcessing(true);
    console.log('getDailyMenu');
    try {
      let d1 = new Date();
      let d2 = moment(d1).format('MM/DD/YYYY');
      let { StoreId } = storeData1;
      //Check If Restore Last Visit Closing stock reuired or not
      let isInsertLastVisitValid = await checkInsertLastVisitValid(storeData1);
      if (isInsertLastVisitValid) {
        //If Last Visit cLosing stock is available and OPS is not already filled then Restore values from LVStock to OPS
        let isInserted = await InsertLastClosingStock(storeData1);
      }
      let q = await Q_getMyStoresMenuList(isAdhoc, storeData1, null, isBeat, isNonMerchan1, isNonProgam, isStoreSearch, props);
      console.log('My menu q:', q);
      await db.transaction(async function (txn) {
        await txn.executeSql(q, [], async function (txn2, txnres) {
          if (txnres.rows.length > 0) {
            let arr = [];
            let allDone = true;
            for (var i = 0; i < txnres.rows.length; i++) {
              let data = txnres.rows.item(i);
              console.log("data---------1", data)
              data.PSAllow = data.PSAllow == true || data.PSAllow == 'true' || data.PSAllow == 1 ? true : false;
              let { KPIAVBL, DataRowCount, PSAllow, PSTableName, ScreenName, DataDoneCount, DataRowAvlblCount } = data;
              DataRowAvlblCount = DataRowAvlblCount == null ? 0 : DataRowAvlblCount;

              // console.log("Menu PSAllow:",ScreenName,PSAllow,PSTableName);
              console.log("ScreenName KPIAVBL:", PSAllow, ScreenName, KPIAVBL, DataRowCount, DataDoneCount, DataRowAvlblCount)
              let isAvlbl = parseInt(KPIAVBL) > 0;
              let isDone = false;
              let hasSomeData = false;
              if (props.PartialSaveAllow == true && PSAllow != null && PSAllow == true) {
                isDone = parseInt(KPIAVBL) > 0 && parseInt(DataRowCount) > 0 && DataDoneCount >= DataRowAvlblCount;
                hasSomeData = parseInt(KPIAVBL) > 0 && parseInt(DataRowCount) > 0;
              }
              else {
                isDone = parseInt(KPIAVBL) > 0 && parseInt(DataRowCount) > 0;
                hasSomeData = isDone;
              }

              data['isAvlbl'] = isAvlbl;
              data['isKPI_Done'] = isDone;
              data['hasSomeData'] = hasSomeData;
              arr.push(data);
              if (isAvlbl && !isDone) {
                allDone = false;
              }
              if (i == (txnres.rows.length - 1)) {
                // Background Window Functionality
                let windData = await get_item('storeData')
                if (windData != null && windData != '') {
                  let StoreJson = JSON.parse(windData)
                  let { storeBGData, menuName, StoreId1, BgMenuID, NavData, visiteDate } = StoreJson
                  if (StoreId1 == StoreId && IsBacksta == false && visiteDate == d2) {
                    let bgMenuData = arr.find((val) => val.ScreenName == menuName);
                    // setBgScreenName(bgMenuData)
                    setBgNavigateData(NavData)
                    console.log("StoreJson-----S", StoreJson)
                    if (BgMenuID != null && BgMenuID != "") {
                      let bgMenuIndex = arr.findIndex(i => i.MenuId == BgMenuID);
                      if (bgMenuIndex >= 0) {
                        let bgMenu = arr[bgMenuIndex];
                        setBgScreenName(bgMenu)
                        setBgScreenMenu(bgMenu);
                      }
                    }
                    else {
                      let bgMenuIndex = arr.findIndex(i => i.ScreenName == menuName);
                      if (bgMenuIndex >= 0) {
                        let bgMenu = arr[bgMenuIndex];
                        setBgScreenName(bgMenu)
                        setBgScreenMenu(bgMenu);
                      }
                    }
                    
                    setShowAlert(true);
                  }
                }
                setDailyMenu(arr);
                setIsLoaded(true);
                setProcessing(false);
                console.log('isAllKPIDone dailymenu :', allDone, props.AutoGoToPrev, isAutoBack)
                if (allDone == true && props.AutoGoToPrev == true && isAutoBack == true) {
                  // props.set_autoback({'AutoGoToPrev':true});
                  setTimeout(() => {
                    props.navigation.goBack();
                  }, 3000);
                }
              }
            }
          }
          else {
            setProcessing(false);
          }
        }, function (txnE, txnerr) { console.log(txnerr); setProcessing(false); },);

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


  async function checkInsertLastVisitValid(storeData1) {
    let { StoreId } = storeData1;
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        //check if already stock exists or not
        let chk_q = `Select * from ${AppTables.STOCK_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}'`;
        //check if last visit stock exists or not
        let chk_q2 = `Select * from LastVisit_ClosingStock WHERE StoreId='${StoreId}'`;
        txn.executeSql(chk_q, [], async function (txn2, txnres) {
          console.log('stock count:', txnres.rows.length);
          //If data does not already exists
          if (txnres.rows.length <= 0) {
            //check if last visit stock exists or not
            txn.executeSql(chk_q2, [], async function (txn2, txnres2) {
              console.log('last visit stock count:', txnres2.rows.length);
              //If last visit ops exists
              if (txnres2.rows.length > 0) {
                resolve(true);
              }
              else {
                resolve(false);
              }
            }, function (txnE, txnerr) { console.log(txnerr); resolve(false) },);
          }
          else {
            resolve(false);
          }
        }, function (txnE, txnerr) { console.log(txnerr); resolve(false) },);
      });
    }).catch((e) => {
      console.log(e);
      return false;
    })
  }

  async function getSeq() {
    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        // select autogenerated seq from Header Table.
        let seq_q = `select seq from sqlite_sequence where name="${AppTables.INSERT_OPENINGHEADER_DATA}" `;
        await txn.executeSql(seq_q, [], async function (txn2, txnres) {
          if (txnres.rows.length > 0) {
            let data = txnres.rows.item(0);
            let seq = data.seq;
            resolve(seq);
          }
          else {
            resolve(0);
          }
        }, function (txnE, txnerr) { console.log(txnerr); resolve(0); },);
      });
    }).catch((e) => {
      console.log(e);
      return 0;
    });
  }


  async function InsertLastClosingStock(storeData1) {
    let { StoreId, StateId, ChainId, StoreCategoryId, StoreClassId, StoreTypeId } = storeData1;
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');

    let seq = await getSeq();
    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {

        let q = `DELETE FROM ${AppTables.STOCK_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
        let q2 = `DELETE FROM ${AppTables.INSERT_OPENINGHEADER_DATA} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;

        //  remove old data
        await txn.executeSql(q, [], async function (txn2, txnres) {
          console.log('ops stock data deleted');
        }, function (txnE, txnerr) { console.log(txnerr); },);

        await txn.executeSql(q2, [], async function (txn2, txnres) {
          console.log('ops stock header data deleted');
        }, function (txnE, txnerr) { console.log(txnerr); },);


        function insertValues(hdrValues, OpsValues) {
          let add_StockHdr = `INSERT INTO ${AppTables.INSERT_OPENINGHEADER_DATA} (STORE_ID,VISIT_DATE,CATEGORY,CATEGORY_ID,MSL,IMAGE,IMAGEPATH,ADDED_DATE) VALUES ${hdrValues} `;
          let add_Stock = `INSERT INTO ${AppTables.STOCK_DATA} (COMMON_ID,STORE_ID,VISIT_DATE,CATEGORY_ID,CATEGORY,BRAND_ID,BRAND,PRODUCT_ID,PRODUCT,MSL,OPENING_STOCK,MIDDAY_STOCK,CLOSING_STOCK,EXPIRY_ISOPEN,EXPIRY_STK,EXPIRYSTOCK1,EXPIRYSTOCK2,EXPIRYSTOCK3,EXPIRYSTOCK4,ADDED_DATE) VALUES ${OpsValues} `;

          txn.executeSql(add_StockHdr, [], async function (txn2, txnres) {
            console.log('last visit OPs hdr inserted successfully');
            txn.executeSql(add_Stock, [], async function (txn2, txnres) {
              console.log('last visit OPs inserted successfully');
              resolve(true);
            }, function (txnE, txnerr) { console.log(txnerr); resolve(false) },);
          }, function (txnE, txnerr) { console.log(txnerr); resolve(false) },);

        }

        let join = ' INNER join Product_Master p on c.CategoryId=p.CategoryId ';
        let join2 = ` INNER join Mapping_ProductAssortmentStorewise mp on p.ProductId=mp.ProductId `;
        let skuq = `SELECT DISTINCT c.CategoryId,c.CategoryName,'' as MSL from Master_Category c ${join} ${join2}  where mp.StoreId='${StoreId}' order by p.CategorySequence`;

        txn.executeSql(skuq, [], async function (txn2, txnres2) {
          if (txnres2.rows.length > 0) {
            let stock_values = '', values = '', insertCouunt = 0, prdLoadedForCatCount = 0;
            for (let i = 0; i < txnres2.rows.length; i++) {
              let catdata = txnres2.rows.item(i);

              seq++;
              //build insert values  for hdr(Categories)
              values += values != '' ? ' , ' : '';
              values += ` ('${StoreId}','${d2}','${catdata.CategoryName}','${catdata.CategoryId}','${catdata.MSL}','','','${d2}') `;



              // get all product with Last Visit Stock values if available
              let join6 = '', selectl_lv = '';
              selectl_lv = ` ,lv.ClosingStock as LV_ClosingStock,lv.CLS_ExpiryStock1 as LV_CLS_ExpiryStock1,lv.CLS_ExpiryStock2 as LV_CLS_ExpiryStock2,lv.CLS_ExpiryStock3 as LV_CLS_ExpiryStock3,lv.CLS_ExpiryStock4 as LV_CLS_ExpiryStock4`;
              join6 = `  Left Outer join LastVisit_ClosingStock lv on lv.ProductId=p.ProductId and lv.StoreId='${StoreId}' `;
              let join = `  inner join Mapping_ProductAssortmentStorewise m on p.ProductId=m.ProductId `;
              let join2 = `  inner join Master_Category mc on mc.CategoryId=p.CategoryId `;
              let sku_q2 = `select distinct p.ProductName,p.ProductId,p.BrandName,p.BrandId,m.MSL,p.SubCategoryName, p.SubCategoryId,p.BrandName,p.BrandId ${selectl_lv} from Product_Master p  ${join} ${join2} ${join6} where m.StoreId='${StoreId}' and (p.CategoryId='${catdata.CategoryId}' or p.CategoryId= ${catdata.CategoryId}) and (CompanyId='1' or CompanyId= 1) order by p.ProductSequence`;

              txn.executeSql(sku_q2, [], async function (txn2, txnres3) {
                if (txnres3.rows.length > 0) {
                  let hdrseq = seq;
                  for (var i = 0; i < txnres3.rows.length; i++) {
                    let data = txnres3.rows.item(i);

                    //prefil values
                    let stock = data.LV_ClosingStock != null && data.LV_ClosingStock != 'undefined' ? data.LV_ClosingStock : '0';
                    let lvCLS1 = data.LV_CLS_ExpiryStock1 != null && data.LV_CLS_ExpiryStock1 != 'undefined' ? data.LV_CLS_ExpiryStock1 : '0';
                    let lvCLS2 = data.LV_CLS_ExpiryStock2 != null && data.LV_CLS_ExpiryStock2 != 'undefined' ? data.LV_CLS_ExpiryStock2 : '0';
                    let lvCLS3 = data.LV_CLS_ExpiryStock3 != null && data.LV_CLS_ExpiryStock3 != 'undefined' ? data.LV_CLS_ExpiryStock3 : '0';
                    let lvCLS4 = data.LV_CLS_ExpiryStock4 != null && data.LV_CLS_ExpiryStock4 != 'undefined' ? data.LV_CLS_ExpiryStock4 : '0';
                    //build insert values for products

                    stock_values += stock_values != '' ? ' , ' : '';
                    stock_values += ` ('${hdrseq}','${StoreId}','${d2}','${catdata.CategoryId}','${catdata.CategoryName}','${data.BrandId}','${data.BrandName}','${data.ProductId}','${data.ProductName}','${data.MSL}','${stock}','','','0','0','${lvCLS1}','${lvCLS2}','${lvCLS3}','${lvCLS4}','${d2}') `;
                    insertCouunt++;
                    if (i == txnres3.rows.length - 1) {
                      prdLoadedForCatCount++;
                      if (prdLoadedForCatCount == txnres2.rows.length) {
                        console.log("insertCouunt:", insertCouunt);
                        insertValues(values, stock_values);
                      }
                    }
                  }

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


  async function checkAvailability(storeData1, data) {
    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        let q2 = getAvailblQuery(data.ScreenName, storeData1);
        if (data.ScreenName == 'ADDITIONALVISI') {
          console.log('POSM query:', q2);
        }
        if (q2 != '' && q2 != null) {
          await txn.executeSql(q2, [], async function (txn2, txnres2) {
            if (data.ScreenName == 'ADDITIONALVISI') {
              console.log('POSM count:', txnres2.rows.length);
              for (var n = 0; n < txnres2.rows.length; n++) {
                let dkeh = txnres2.rows.item(n);
                console.log(dkeh);
              }
            }
            let isAvlbl = getIfAvlbl(data.ScreenName, txnres2, storeData1);

            resolve(isAvlbl);
          }, function (txnE, txnerr) { console.log(txnerr); resolve(false); },);
        }
        else {
          let isAvlbl = getIfAvlbl(data.ScreenName, {}, storeData1);
          resolve(isAvlbl);
        }
      });
    }).then((val) => {
      return val;
    }).catch((err) => {
      console.log(err);
      return false;
    });
  }

  async function updateStatus(storeData1, data, isAvlbl) {
    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        let q2 = getQuery(data.ScreenName, storeData1);
        if (q2 != '' && q2 != null && isAvlbl == true) {
          await txn.executeSql(q2, [], async function (txn2, txnres2) {
            let isDone = await getIfKPIDone(data.ScreenName, txnres2, storeData1);
            resolve(isDone);
          }, function (txnE, txnerr) { console.log(txnerr); resolve(false); },);
        }
        else {
          resolve(false);
        }
      });
    }).then((val) => {
      return val;
    }).catch((err) => {
      console.log(err);
      return false;
    });

  }


  function getQuery2(ScreenName, extraData, AllKPIFields = []) {
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    let q = ``;
    let cols = '', condition = '';
    switch (ScreenName) {
      case 'OPSTOCK':
        //pick row where either MDS is filled or CLS is filled
        // q=`SELECT DISTINCT MIDDAY_STOCK FROM ${AppTables.STOCK_DATA} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}'`;
        cols = ' ,s.MIDDAY_STOCK ', condition = ` and ((s.MIDDAY_STOCK is not null and s.MIDDAY_STOCK!='') or (s.CLOSING_STOCK is not null and s.CLOSING_STOCK!=''))`;
        q = Q_GetAvailablePrds(ScreenName, storeData, AllKPIFields, cols, condition, AppTables.STOCK_DATA);
        return q;
      case 'MDSTOCK':
        if (extraData.checkOpeningStock == '1') {
          // q=`SELECT DISTINCT OPENING_STOCK FROM  ${AppTables.STOCK_DATA} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}'`;
          cols = ' ,s.OPENING_STOCK ', condition = ` and (s.OPENING_STOCK is null or s.OPENING_STOCK='undefined' or s.OPENING_STOCK='')`;
        }
        else {
          // q=`SELECT DISTINCT CLOSING_STOCK FROM ${AppTables.STOCK_DATA} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}'`;
          cols = ' ,s.CLOSING_STOCK ', condition = ` and (s.CLOSING_STOCK is not null and s.CLOSING_STOCK!='')`;
        }
        q = Q_GetAvailablePrds(ScreenName, storeData, AllKPIFields, cols, condition, AppTables.STOCK_DATA);
        console.log("MDS check CLOSING_STOCK q:", q)
        return q;
      case 'CLSSTOCK':
        if (extraData.checkOpeningStock == '1') {
          // q=`SELECT DISTINCT OPENING_STOCK FROM  ${AppTables.STOCK_DATA} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}'`;
          cols = ' ,s.OPENING_STOCK ', condition = ` and (s.OPENING_STOCK is null or s.OPENING_STOCK='undefined' or s.OPENING_STOCK='')`;
        }
        else {
          // q=`SELECT DISTINCT MIDDAY_STOCK FROM ${AppTables.STOCK_DATA} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}'`;
          cols = ' ,s.MIDDAY_STOCK ', condition = ` and (s.MIDDAY_STOCK is null or s.MIDDAY_STOCK='undefined' or s.MIDDAY_STOCK='')`;
        }
        q = Q_GetAvailablePrds(ScreenName, storeData, AllKPIFields, cols, condition, AppTables.STOCK_DATA);

        return q;
      case 'SALE':
        console.log("extraData------------", extraData)
        if (extraData.checkOpeningStock == '1') {
          cols = ' ,s.OPENING_STOCK ', condition = ` and (s.OPENING_STOCK is null or s.OPENING_STOCK='undefined' or s.OPENING_STOCK='')`;
          q = Q_GetAvailablePrds(ScreenName, storeData, AllKPIFields, cols, condition, AppTables.STOCK_DATA);
        }
        else if (extraData.checkStock == '1') {
          cols = ' ,s.STOCK ', condition = ` and (s.STOCK is null or s.STOCK='undefined')`;
          q = Q_GetAvailablePrds(ScreenName, storeData, AllKPIFields, cols, condition, AppTables.STOCK2_DATA);
          console.log("SALW", q)
        }
        else {
          cols = ' ,s.MIDDAY_STOCK ', condition = ` and (s.MIDDAY_STOCK is null or s.MIDDAY_STOCK='undefined' or s.MIDDAY_STOCK='')`;
          q = Q_GetAvailablePrds(ScreenName, storeData, AllKPIFields, cols, condition, AppTables.STOCK_DATA);
        }
        return q;

      case 'PROMOTIONONEAPP':
        if (extraData.checkOpeningStock == '1') {
          q = `SELECT DISTINCT OPENING_STOCK FROM  ${AppTables.STOCK_DATA} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}'`;
        }
        return q;
      case 'PROMOTIONONEAPP_IR':
        if (extraData.checkOpeningStock == '1') {
          q = `SELECT DISTINCT OPENING_STOCK FROM  ${AppTables.STOCK_DATA} WHERE STORE_ID='${storeData.StoreId}' and VISIT_DATE='${d2}'`;
        }
        return q;
      default: return '';
    }
  }

  async function checkForData(ScreenName, callback = () => { }, extraData = {}, AllKPIFields = []) {
    try {
      await db.transaction(async function (txn) {
        let q2 = getQuery2(ScreenName, extraData, AllKPIFields);
        if (q2 != '' && q2 != null) {
          await txn.executeSql(q2, [], async function (txn2, txnres2) {
            callback(txnres2);
          }, function (txnE, txnerr) { console.log(txnerr); },);
        }
      });
    } catch (err) {
      console.log(err);
    }
  }

  async function gotoKPITaskScreen(item, BgNav = false, BgNavData = {}, BgMenu = "") {

    let AllKPIFields = await getKPIFields(item);
    console.log("BgNavData------", BgNavData)

    let isOPStockEnable = AllKPIFields.findIndex(i => i.KPIFieldName == 'PromoStock_ShowOPStockProduct')
    let isOPStockEnableKPIObj = isOPStockEnable >= 0 ? AllKPIFields[isOPStockEnable] : {};
    let isOPStockEnableFlag = isOPStockEnable >= 0 ? isOPStockEnableKPIObj['KPIFieldEnable'] : false;

    switch (item.ScreenName) {
      case 'STOCK': {
        gotoPage('Stock', item);
      }
        return;
      case 'STOCKWITHCATEGORY': {
        gotoPage('StockCat', item);
      }
        return;
      case 'STOCKWITHPROMO': {
        gotoPage('StockPromo', item);
      }
        return;

      case 'ONEAPPSTOCKQRSCAN': {

        gotoPage('StockUniqueQRCode', item);
      }
        return;

      case 'ONEAPPSALEQRSCAN': {
        gotoPage('SaleQRCode', item);
      }
        return;

      case 'KYCONEAPP': {
        gotoPage('StoreKycForm', item);
      }
        return;

      case 'OPSTOCK': {
        async function OPScb_middayfilledCheck(txnres2) {
          let isFilled = false;
          //pick row where either MDS is filled or CLS is filled
          if (txnres2.rows.length > 0) {
            isFilled = true;
          }

          if (isFilled) {
            notify("Midday Stock or Closing Stock has been updated, Opening stock cannot be changed now!", 'SHORT');
          }
          else {
            gotoPage('OpeningStock', item);
          }
        }

        let middayKpiIndex = dailyMenu.findIndex(i => i.ScreenName == 'MDSTOCK');
        let clsKpiIndex = dailyMenu.findIndex(i => i.ScreenName == 'CLSSTOCK');
        if (middayKpiIndex >= 0 || clsKpiIndex >= 0) { await checkForData(item.ScreenName, OPScb_middayfilledCheck, {}, AllKPIFields); }
        else { gotoPage('OpeningStock', item); }

      }
        return;
      case 'BACKSTOCK': {
        gotoPage('BackroomStock', item);
      }
        return;
      case 'MDSTOCK': {
        // gotoPage('MiddayStock',item);return;
        let extraData = { checkOpeningStock: '1' };
        let clsKpiIndex = dailyMenu.findIndex(i => i.ScreenName == 'CLSSTOCK');
        async function MDScb_closings_filledCheck(txnres2) {
          let isCSFilled = false;
          if (txnres2.rows.length > 0) {
            isCSFilled = true;
          }

          if (isCSFilled == true) {
            notify(ST.ClosingStockhasbeenupdatedMiddayStockDatacannotbechangednow, 'LONG');
          } else {
            gotoPage('MiddayStock', item);
          }
        }

        async function MDScb_osfilledCheck(txnres2) {
          let isOSFilled = true;
          if (txnres2.rows.length > 0) {
            isOSFilled = false;
          }

          if (isOSFilled == false) {
            notify(ST.FillOpenningStockfirst, 'SHORT');
          } else {
            clsKpiIndex >= 0 ? await checkForData(item.ScreenName, MDScb_closings_filledCheck, {}, AllKPIFields) : gotoPage('MiddayStock', item);
          }
        }

        await checkForData(item.ScreenName, MDScb_osfilledCheck, extraData, AllKPIFields);

      }
        return;
      case 'CLSSTOCK': {
        // gotoPage('ClosingStock',item);return;
        let OPSTOCKKpiIndex = dailyMenu.findIndex(i => i.ScreenName == 'OPSTOCK');
        let middayKpiIndex = dailyMenu.findIndex(i => i.ScreenName == 'MDSTOCK');
        let extraData = { checkOpeningStock: '1' };

        async function CLScb_middays_filledCheck(txnres2) {
          let isCSFilled = true;
          if (txnres2.rows.length > 0) {
            isCSFilled = false;
          }
          if (isCSFilled == false) {
            notify(ST.FillMiddayStockfirst, 'SHORT');
          } else {
            gotoPage('ClosingStock', item);
          }
        }

        async function CLScb_osfilledCheck(txnres2) {
          let isOSFilled = true;
          if (txnres2.rows.length > 0) {
            isOSFilled = false;
          }

          if (isOSFilled == false) {
            notify(ST.FillOpenningStockfirst, 'SHORT');
          } else {

            if (middayKpiIndex >= 0) { await checkForData(item.ScreenName, CLScb_middays_filledCheck, {}, AllKPIFields); }
            else {
              gotoPage('ClosingStock', item);
            }
          }
        }



        if (OPSTOCKKpiIndex >= 0) {
          await checkForData(item.ScreenName, CLScb_osfilledCheck, extraData, AllKPIFields);
        }
        else if (middayKpiIndex >= 0) {
          await checkForData(item.ScreenName, CLScb_middays_filledCheck, {}, AllKPIFields);
        }
        else {
          gotoPage('ClosingStock', item);
        }


      }
        return;
      case 'SOS': {
        gotoPage('ShareOfShelf', item);
      }
        return;
      case 'PAIDVISI': {
        gotoPage('PaidVisibility', item);
      }
        return;

      case 'WAREHOUSEDEPLOY': {
        gotoPage('WarehousePaidVi', item);
      }
        return;

      case 'WAREHOUSECAMPAIGN': {
        gotoPage('WareHouseCampaignWise', item);
      }
        return;
      case 'ADDITIONALVISI': {
        gotoPage('AdditionalVisibility', item);
      }
        return;
      case 'ADDITIONALVISI_IR': {
        gotoPage('AdditionalVisibilityIR', item);
      }
        return;
      case 'ADDITIONALVISI_IR_ONLY': {
        gotoPage('AdditionalVisibilityIR_Only', item);
      }
        return;
      case 'COMPVISI': {
        gotoPage('CompetitionVisibility', item);
      }
        return;
      case 'COMPVISI_IR': {
        gotoPage('CompetitionVisibilityIR', item);
      }
        return;
      case 'PROMOTION': {
        gotoPage('Promotion', item);
      }
        return;
      case 'COMPROMO': {
        gotoPage('CompetitionPromotion', item);
      }
        return;
      case 'CONCOV': {
        gotoPage('ContactConversion', item);
      }
        return;
      case 'SALE': {
        let OPSTOCKKpiIndex = dailyMenu.findIndex(i => i.ScreenName == 'OPSTOCK');
        let middayKpiIndex = dailyMenu.findIndex(i => i.ScreenName == 'MDSTOCK');
        let StockKpiIndex = dailyMenu.findIndex(i => i.ScreenName == 'STOCK');
        let extraData = { checkOpeningStock: '1' };

        async function SALEcb_middays_filledCheck(txnres2) {
          let isCSFilled = true;
          if (txnres2.rows.length > 0) { // get data if there is any row of stock having values null / undefined / blank
            isCSFilled = false;
          }

          if (isCSFilled == false) {
            notify(ST.FillMiddayStockfirst, 'SHORT');
          } else {
            gotoPage('Sale', item);
          }
        }

        async function SALEcb_osfilledCheck(txnres2) {
          let isOSFilled = true;
          if (txnres2.rows.length > 0) { // get data if there is any row of stock having values null / undefined / blank
            isOSFilled = false;
          }

          if (isOSFilled == false) {
            notify(ST.FillOpenningStockfirst, 'SHORT');
          } else {
            if (middayKpiIndex >= 0) { await checkForData(item.ScreenName, SALEcb_middays_filledCheck, {}, AllKPIFields); }
            else { gotoPage('Sale', item); }
          }
        }

        async function SALEcb_StockfilledCheck(txnres2) {
          let isStockFilled = true;
          if (txnres2.rows.length > 0) { // get data if there is any row of stock having values null / undefined / blank
            isStockFilled = false;
          }

          if (isStockFilled == false) {
            notify('Fill Stock first!', 'SHORT');
          }
          else {
            gotoPage('Sale', item);
          }
        }

        if (OPSTOCKKpiIndex >= 0) {
          await checkForData(item.ScreenName, SALEcb_osfilledCheck, extraData, AllKPIFields);
        }
        else if (middayKpiIndex >= 0) {
          await checkForData(item.ScreenName, SALEcb_middays_filledCheck, {}, AllKPIFields);
        }
        else if (StockKpiIndex >= 0) {
          extraData = { checkStock: '1' };
          await checkForData(item.ScreenName, SALEcb_StockfilledCheck, extraData, AllKPIFields);
        }
        else {
          gotoPage('Sale', item);
        }
      }
        return;
      case 'SURVEY': {
        gotoPage('SurveyList', item, BgNav, BgNavData, BgMenu);
      }
        return;
      case 'POSSALEONEAPP': {
        gotoPage('POSSale', item);
      }
        return;

      case 'WINDOW': {
        gotoPage('Window', item, false, {}, BgMenu);
      }
        return;
      case 'WINDOW_IR': {
        gotoPage('WindowIR', item, false, {}, BgMenu);
      }
        return;
      case 'POSM': {
        gotoPage('POSM', item);
      }
        return;
      case 'FEEDBACK': {
        gotoPage('Feedback', item);
      }
        return;
      case 'PROMOTION2': {
        gotoPage('SimplePromotion', item);
      }
        return;
      case 'STOREIMG': {
        gotoPage('StoreImages', item, BgNav, BgNavData);
      }
        return;
      case 'SHELFTALKER': {
        gotoPage('ShelfTalker', item);
      }
        return;
      case 'PROMOTIONONEAPP': {
        let extraData = { checkOpeningStock: '1' };
        async function cb_OPStock_filledCheck(txnres2) {
          let isFilled = true;
          if (txnres2.rows.length > 0) {
            for (var i = 0; i < txnres2.rows.length; i++) {
              let data = txnres2.rows.item(i);
              if (data.OPENING_STOCK !== 0 && (data.OPENING_STOCK == null || data.OPENING_STOCK == '')) {
                isFilled = false;
              }
              if (i == txnres2.rows.length - 1) {
                if (isFilled) {
                  gotoPage('PromotionOneApp', item);
                }
                else {
                  notify(ST.FillOpenningStockfirst, 'SHORT');
                }
              }
            }
          }
          else {
            gotoPage('PromotionOneApp', item);
          }
        }

        if (isOPStockEnableFlag == true || isOPStockEnableFlag == "true" || isOPStockEnableFlag == 1) {
          await checkForData(item.ScreenName, cb_OPStock_filledCheck, extraData, AllKPIFields);
        } else {
          gotoPage('PromotionOneApp', item);
        }
      }
        return;

      case 'PAIDVISIONEAPP': {
        gotoPage('PaidVisibilityOneApp', item, false, {}, BgMenu);
      }
        return;
      case 'PAIDVISIONEAPP_IR': {
        gotoPage('PaidVisibilityOneAppIR', item, false, {}, BgMenu);
      }
        return;
      case 'PAIDVISIONEAPP_IR_ONLY': {
        gotoPage('PaidVisibilityOneAppIR_Only', item, false, {}, BgMenu);
      }
        return;
      case 'SOSONEAPP': {
        gotoPage('ShareOfShelfOneApp', item);
      }
        return;
      case 'SOSONEAPP_IR': {
        gotoPage('ShareOfShelfOneAppIR', item);
      }
        return;
      case 'SOSONEAPP_IR_ONLY': {
        gotoPage('ShareOfShelfOneAppIR_Only', item);
      }
        return;
      case 'CATEXEONEAPP': {
        gotoPage('CategoryExec', item);
      }
        return;
      case 'STORESCORE': {
        gotoPage('StoreScore', item);
      }
        return;
      case 'ORDER': {
        gotoPage('Order', item);
      }
        return;
      case 'ORDERSTATUS': {
        gotoPage('OrderStatus', item, BgNav, BgNavData);
      }
        return;
      case 'TRAININGONEAPP': {
        gotoPage('Training', item);
      }
        return;
      case 'SAMPLINGONEAPP': {
        gotoPage('SamplingList', item);
      }
        return;
      case 'PROGRAMONEAPP': {
        gotoPage('ProgramQuestions', item, false, {}, BgMenu);
      }
        return;
      case 'TGBASEDONEAPP': {
        gotoPage('TGBaseVisiCooler', item, false, {}, BgMenu);
      }
        return;
      case 'STOREDYNAMICSCORE': {
        gotoPage('DynamicStoreScore', item, false, {}, BgMenu);
      }
        return;
      case 'ONEAPPMISSEDCALL': {
        gotoPage('MissedCallView', item);
        // gotoPage('MissedCallList',item);
      }
        return;
      case 'SOSEYELEVELONEAPP': {
        gotoPage('SOSEyeLevel', item);
      }
        return;
      case 'BREAKTIME': {
        gotoPage('BreakTime', item);
      }
        return


      case 'RETURNSTOCKONEAPP': {
        gotoPage('ReturnStock', item);
      }
        return

      case 'ORDERSIMPLIFYONEAPP': {
        gotoPage('OrderSimplify', item);
      }
        return


      default: return;
    }
  }

  function gotoPage(screenname = '', item, BgNav = false, BgNavData = {}, BgMenu = "") {
    props.set_autoback({ 'AutoGoToPrev': false });
    console.log("gotoPage in storeDailyMenu", BgNav, BgNavData);
    let MenuItem = ((showAlert == true && BgMenu != null && BgMenu != "" && BgMenu.MenuId != null && BgMenu.MenuId != "") ? BgMenu : item);
    console.log("gotoPage item.PSAllow:", props.PartialSaveAllow, typeof (item.PSAllow), item.PSAllow, screenname);
    if (props.PartialSaveAllow == true && item.PSAllow != null && item.PSAllow == true) {
      props.navigation.navigate("KPICategories", { screenname: screenname, storeData: storeData, menu: MenuItem, 'isAdhoc': isAdhocScreen, 'isBeat': isBeatPlan, 'isNonMerchans': isNonMerchan, isNonProgs: isNonProg, isStoreSearch: isStoreSearch, 'redirect': BgNav, 'BgNavData': BgNavData, ExtraData: item })
    }
    else {
      let obj = { props, 'storeData': storeData, 'screenname': screenname, 'MenuItem': MenuItem, 'BgNav': BgNav, 'BgNavData': BgNavData, 'isAdhocScreen': isAdhocScreen, 'isBeatPlan': isBeatPlan, 'isNonMerchan': isNonMerchan, 'isNonProg': isNonProg, 'isStoreSearch': isStoreSearch, ExtraData: item };
      goToMenuPage(obj);
    }
  }


  function _renderLeftMenuItem(index, RowContent) {
    return (
      <View style={customStyle.dialyMenu_Rows} key={index}>
        {RowContent[0]}
      </View>
    )
  }


  function _renderRightMenuItem(item, index, RowContent) {
    return (
      <View style={customStyle.dialyMenu_Rows} key={index}>
        {RowContent[0]}
        {_renderMenuItem(item, index)}
      </View>
    )

  }

  function _renderMenuItem(item, index) {
    let newi = index > 2 ? ((index % 3)) : index;
    let firstitem = (index % 2 == 0) ? true : false;
    let arr = colors_Arr[newi] ? colors_Arr[newi].bg : colors_Arr["0"].bg;
    let unavlbl_bg = ['#bfbfbf', '#bfbfbf'];
    let arr_new = item.isAvlbl == false ? unavlbl_bg : arr;
    let iconColor = colors_Arr[newi] ? colors_Arr[newi].color : colors_Arr["0"].color;
    const imgPath = item.MenuPath + (item.isAvlbl == false ? item.GreyIcon : item.NormalIcon);

    let MBgimage = colors_Arr[newi] ? colors_Arr[newi].bgImage : colors_Arr["0"].bgImage;
    MBgimage = item.isAvlbl == false ? grey_bg_image : MBgimage;


    let hasSomeData = item.hasSomeData
    return (
      <TouchableOpacity activeOpacity={(item.isAvlbl == false ? 1 : 0.7)} style={[customStyle.daily_menu_outer, firstitem ? customStyle.daily_menu_first : {}]} key={index} onPress={() => { if (item.isAvlbl != false) { gotoKPITaskScreen(item) } }}>
        <View style={customStyle.daily_menu_tilebgShadow}>
          <LinearGradient colors={arr_new} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.daily_menu}>
          </LinearGradient>
          <View style={[customStyle.daily_menu_innerImgCon]}>
            <MBgimage width={90} height={90} style={customStyle.daily_menu_bgImg} />
          </View>
          <View style={[customStyle.daily_menu_inner2]}>
            {(imgPath != null && imgPath != '') && <Image source={{ uri: imgPath }} style={customStyle.daily_menu_Icon} />}
          </View>

          <Text style={customStyle.daily_menu_title}>{item.MenuName}</Text>
          {item.isKPI_Done == true &&
            <View style={customStyle.daily_menu_done}><AntDesign color={'green'} size={30} name='checkcircle' /></View>
          }
          {item.hasSomeData == true && !item.isKPI_Done &&
            <View style={customStyle.daily_menu_hasData}><FontAwesome color={'green'} size={20} name='dot-circle-o' /></View>
          }
          {props.PartialSaveAllow == true && item.PSAllow != null && item.PSAllow == true &&
            <Text style={customStyle.daily_menu_Count}>{`(${item.DataDoneCount}/${item.DataRowAvlblCount})`}</Text>
          }

        </View>
      </TouchableOpacity>
    )
  }


  function _renderDailyMenu() {
    var RowContent = [];
    return (
      <View style={customStyle.dailymenu_listcon}>
        <View style={customStyle.dailymenu_list}>
          {refreshMenuRender == refreshMenuRender && dailyMenu.length > 0 &&
            dailyMenu.map((item, index) => {
              let firstitem = (index % 2 == 0) ? true : false;

              if (firstitem) {
                var content = _renderMenuItem(item, index);
                RowContent = [content];
                if (index == dailyMenu.length - 1) {
                  return _renderLeftMenuItem(index, RowContent);
                }
              }
              else {
                return _renderRightMenuItem(item, index, RowContent);
              }

            })
          }

        </View>
      </View>
    );
  }



  return (
    <Container {...props} pt={0} avoidSafeArea={(Platform.OS == 'ios' ? true : false)}>
      {processing && <CustomLoader fullHeight={true} title={loaderTitle} />}
      <CustomHeader {...props} showaddstore={true} title={ST.DailyMenu} />
      {_render_Alert()}
      {_render_GroomingPicturesModal()}
      <LinearGradient colors={[PageTheme.$gradient1, PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
        <View style={[customStyle.pageContentWrapper]}>
          {Object.keys(storeData).length > 0 &&
            <ScrollView contentContainerStyle={[customStyle.geotag_scroll]} style={{}}>

              <View style={[customStyle.storel, customStyle.storeInfo_wrap]}>

                <View style={customStyle.storel_card_outer}>
                  <View style={customStyle.storel_card}>
                    <View style={customStyle.storel_card_content}>
                      <Text style={customStyle.storel_card_title}>{storeData.StoreName}</Text>
                      <View style={customStyle.storel_card_subtitle}>
                        <Text style={customStyle.storel_card_subtitleTxt}>{storeData.StoreType}</Text>
                      </View>
                    </View>
                  </View>
                  <View style={customStyle.storel_details}>
                    <View style={customStyle.storel_code}>
                      <View style={[customStyle.storel_codeCon, customStyle.storel_codeBorder]}>
                        <Text style={customStyle.storel_codeLbl}>{ST.StoreId + ':'}</Text>
                        <Text style={customStyle.storel_codeText}>{storeData.StoreId}</Text>
                      </View>
                      <View style={[customStyle.storel_codeCon]}>
                        <Text style={customStyle.storel_codeLbl}>{ST.StoreCode + ':'}</Text>
                        <Text style={customStyle.storel_codeText}>{storeData.StoreCode}</Text>
                      </View>
                    </View>
                  </View>
                </View>

              </View>
              {isLoaded == true && _renderDailyMenu()}
            </ScrollView>
          }
        </View>
      </LinearGradient>
    </Container>
  );
}



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