<?php 
/**
 *
 * @package     Foodbook
 * @author      ThemeLooks
 * @copyright   2020 ThemeLooks
 * @license     GPL-2.0-or-later
 *
 *
 */

/**
 * [foodbook_getOptionData description]
 * @return [type] [description]
 */
function foodbook_getOptionData( $key, $defaultValue = '' ) {

  $data = get_option( 'foodbook_options' );
  return !empty( $data[$key] ) ? $data[$key] : $defaultValue;
}

/**
 * [foodbook_get_productCategories description]
 * @return array
 */
function foodbook_get_productCategories() {

  $taxonomies = foodbook_get_terms('product_cat');
  
  $output = '';

  if ( !empty( $taxonomies ) ) {
      
      foreach( $taxonomies as $category ) {
        if( $category->parent == 0 ) {
            $output.= foodbook_product_cat_html( $category, 'fb_product_category', '' );
            foreach( $taxonomies as $subcategory ) {
                if($subcategory->parent == $category->term_id) {
                $output.= foodbook_product_cat_html( $subcategory, 'fb_product_category', 'item-sub-category' );
                }
            }
        }
      }
  }

  return $output;

}

/**
 * [foodbook_product_cat_html description]
 * @param  [type] $cat [description]
 * @return html
 */
function foodbook_product_cat_html( $cat, $name, $class = '' ) {
  ob_start()
  ?>
  <li class="fb_category_item <?php echo esc_attr( $class ); ?>">
    <div class="fb_category_link">
        <span class="fb_custom_checkbox">
          <label>
            <input type="radio" value="<?php echo esc_attr( $cat->slug ); ?>" name="<?php echo esc_attr( $name ); ?>"/>
            <span class="fb_category_name"><?php echo esc_html( $cat->name ) ?></span>
            <span class="fb_custom_checkmark"></span>
          </label>
        </span>
    </div>
    <?php 
    if( !empty( $cat->count ) ) {
      echo '<div class="fb_category_quantity"><span>'.esc_html( $cat->count ).'</span></div>';
    }
    ?>
  </li>
  <?php
  return ob_get_clean();
}


/**
 * [foodman_getSpecialOffer description]
 * @return array
 */
function foodbook_getSpecialOffer() {

    $terms = foodbook_get_terms('specialoffer');

    $output = '';
    if( !empty( $terms ) ){
      foreach( $terms as $term ){
        $output.= foodbook_product_cat_html( $term, 'fb_product_specialoffer', '' );
      }
    }

  return $output;
}

/**
 * [foodbook_get_specialOffer_terms description]
 * @return array
 */
function foodbook_get_terms( $taxonomy ) {
  $terms = get_terms( array(
      'taxonomy' => $taxonomy,
      'hide_empty' => true,
  ) );
  return $terms;
}

/**
 * [foodbook_get_pages description]
 * @return array
 */
function foodbook_get_pages() {

  $pages = get_pages();

  $getPages = [];

  foreach( $pages as $page ) {
    $getPages[$page->post_name] = $page->post_title;
  }

  return $getPages;
  
}

/**
 * [foodbook_rating_reviews description]
 * @param  string  $rating [description]
 * @param  boolean $echo   [description]
 * @return html          [description]
 */
function foodbook_rating_reviews( $rating, $echo = true ) {

  $starRating = '';

	$j = 0;

    for( $i = 0; $i <= 4; $i++ ) {
      $j++;

      if( $rating  >= $j   || $rating  == '5'   ) {

        $starRating .= '<i class="fas fa-star"></i>';

      }elseif( $rating < $j && $rating  > $i )
      {
        $starRating .= '<i class="fas fa-star-half-alt"></i>';

      } else {

        $starRating .= '<i class="far fa-star"></i>';

      }

    }

    if( $echo == true ) {
      echo $starRating;
    } else {
      return $starRating;
    }


}

/**
 * [foodbook_db_format_date_time description]
 * @param  string  $date [description]
 * @param  boolean $time [description]
 * @return [type]        [description]
 */
function foodbook_db_format_date_time( $date = '', $time = false ) {
  $format = $time ? "Y-m-d H:i:s" : "Y-m-d";
  return $date ? wp_date( $format, strtotime( $date ) ) : current_time( $format );
}

/**
 * [foodbook_getStatusText description]
 * @return [type] [description]
 */
function foodbook_getStatusText() {

  return [

    'no'    => foodbook_getOptionData( 'new-order-text', esc_html__( 'New Order', 'foodbook' ) ),
    'op'    => foodbook_getOptionData( 'order-placed-text', esc_html__( 'Order Placed', 'foodbook' ) ),
    'po'    => foodbook_getOptionData( 'pre-order-text', esc_html__( 'Pre Order', 'foodbook' ) ),
    'oc'    => foodbook_getOptionData( 'order-cancel-text', esc_html__( 'Order Cancel', 'foodbook' ) ),
    'of'    => foodbook_getOptionData( 'order-failed-text', esc_html__( 'Order Failed', 'foodbook' ) ),
    'p'     => foodbook_getOptionData( 'processing-text', esc_html__( 'Processing', 'foodbook' ) ),
    'ac'    => foodbook_getOptionData( 'accepted-cooking-text', esc_html__( 'Accepted Cooking', 'foodbook' ) ),
    'stc'   => foodbook_getOptionData( 'send-to-cooking-text', esc_html__( 'Send To Cooking', 'foodbook' ) ),
    'wfka'  => foodbook_getOptionData( 'waiting-for-kitchen-accept-text', esc_html__( 'Waiting For Kitchen Accept', 'foodbook' ) ),
    'cc'    => foodbook_getOptionData( 'cooking-completed-text', esc_html__( 'Cooking Completed', 'foodbook' ) ),
    'rtd'   => foodbook_getOptionData( 'ready-to-delivery-text', esc_html__( 'Ready To Delivery', 'foodbook' ) ),
    'otw'   => foodbook_getOptionData( 'on-the-way-text', esc_html__( 'On The Way', 'foodbook' ) ),
    'owd'   => foodbook_getOptionData( 'way-to-delivery-text', esc_html__( 'On The Way To Delivery', 'foodbook' ) ),
    'dc'    => foodbook_getOptionData( 'delivery-completed-text', esc_html__( 'Delivery Completed', 'foodbook' ) ),
    'cp'    => foodbook_getOptionData( 'cooking-processing-text', esc_html__( 'Cooking Processing', 'foodbook' ) )

  ];

}

/**
 * [foodbook_tracking_status description]
 * Order Tracking Status list
 * @return array
 */
function foodbook_tracking_status() {

  $statusText = foodbook_getStatusText();

  $stc = $statusText['stc'];

  if( foodbook_is_user_role('kitchen_manager') ) {
    $stc = $statusText['wfka'];
  } 

  return [

    'OP'    => $statusText['op'],
    'PO'    => $statusText['po'],
    'OC'    => $statusText['oc'],
    'OF'    => $statusText['of'],
    'PROC'  => $statusText['p'],
    'AC'    => $statusText['ac'],
    'STC'   => $stc,
    'CC'    => $statusText['cc'],
    'RD'    => $statusText['rtd'],
    'OWD'   => $statusText['owd'],
    'DC'    => $statusText['dc']

  ];

}

/**
 * [foodbook_converted_tracking_status description]
 * Order Tracking Status convert
 * @param  string $val [description]
 * @return string      
 */
function foodbook_converted_tracking_status( $val ) {

  $status = foodbook_tracking_status();

  switch( $val ) {
    case  "OP" :
      return $status['OP'];
      break;
      case  "PO" :
      return $status['PO'];
      break;
      case  "OC" :
      return $status['OC'];
      break;
      case  "OF" :
      return $status['OF'];
      break;
      case  "PROC" :
      return $status['PROC'];
      break;
      case  "AC" :
      return $status['AC'];
      break;
      case  "STC" :
      return $status['STC'];
      break;
      case  "CC" :
      return $status['CC'];
      break;
      case  "RD" :
      return $status['RD'];
      break;
      case  "OWD" :
      return $status['OWD'];
      break;
      case  "DC" :
      return $status['DC'];
      break;
  }

}

/**
 * [foodbook_branch_list description]
 * @return [type] [description]
 */
function foodbook_branch_list() {

  $args = array(
    'posts_per_page' => '-1',
    'post_type' => 'branches',
  );

  $getBranch = get_posts( $args );

  $options = [];

  foreach( $getBranch as $branch ) {
      $options[$branch->ID] = $branch->post_title;
  }

  return $options;
}

/**
 * [foodbook_branch_list_html description]
 * branch list with select box option html
 * @return [type] [description]
 */
function foodbook_branch_list_html( $beforeText = '', $beforeValue = '', $selectedVal = '' ) {

  $args = array(
    'posts_per_page' => '-1',
    'post_type' => 'branches',
  );

  $getBranch = get_posts( $args );

  if( !empty( $beforeText ) ) {
    $output = '<option value="'.esc_attr( $beforeValue ).'">'.esc_html( $beforeText ).'</option>';
  } else {
    $output = '';
  }

  foreach( $getBranch as $branch ) {
    $output .= '<option value="'.esc_attr( $branch->ID ).'" '.selected( $selectedVal, $branch->ID, false ).'>'.esc_html( $branch->post_title ).'</option>';
  }

  return $output;
}

/**
 * [foodbook_get_current_branch_id_by_manager description]
 * Get current branch ID
 * @return array
 */
function foodbook_get_current_branch_id_by_manager() {

   $currentUser = get_current_user_id();

    // User data
    $user_meta = get_userdata( $currentUser );

    $user_roles = $user_meta->roles;

    //
    $meta_key = '';

    // is branch manager
    if( $user_roles[0] == 'branch_manager' ) {

      $meta_key = 'foodbookbranch_manager';
     
    }
    // is kitchen manager
    if( $user_roles[0] == 'kitchen_manager' ) {

      $meta_key = 'foodbookkitchen_manager';
     
    }
    // is delivery boy
    if( $user_roles[0] == 'delivery_boy' ) {

      $meta_key = 'foodbookdelivery_boy';
     
    }

    // Get branch
    $args = array (
        'post_type'        => 'branches',
        'post_status'      => 'publish',
        'meta_key'         => $meta_key,
        'meta_value'       => esc_html( $currentUser ),
        'meta_compare' => 'LIKE'
    );

  $getBranchesId = get_posts( $args );
  $getBranchesId = array_column( $getBranchesId, 'ID' );
  $getBranchesId = !empty( $getBranchesId[0] ) ? $getBranchesId[0] : '';
  return $getBranchesId;
}

/**
 * [foodbook_get_users_role_delivery_manager description]
 * Get delivery users
 * @return array
 */
function foodbook_get_users_role_delivery_manager() {

  $users = get_users( [ 'role__in' => [ 'delivery_boy' ] ] );

  $getUser = [ '0' => 'Select Delivery Boy' ];

  foreach( $users as $user ) {

    $getUser[$user->ID] = $user->display_name;

  }

  return $getUser;

}

/**
 * [foodbook_get_branch_delivery_boy description]
 * Get branch delivery boy
 * @param  string $branch_id [description]
 * @return array
 */
function foodbook_get_branch_delivery_boy( $branch_id = '' ) {
  //
  if( foodbook_is_multi_branch() )  {

    if( empty( $branch_id ) ) {
      $branch_id = foodbook_get_current_branch_id_by_manager();
    }  

    $dIDs = get_post_meta( absint( $branch_id ), 'foodbookdelivery_boy', true );

    // User data
    $boy = [];

    if( !empty( $dIDs ) ) {

      foreach( $dIDs as $id ) {

        $user_meta = get_userdata( $id );

        $boy[$user_meta->ID] =  $user_meta->user_login;

      }

    }

  } else {
    $boy = foodbook_get_users_role_delivery_manager();
  }

  return $boy;

}

/**
 * [foodbook_current_date ]
 * @return string date
 */
function foodbook_current_date( $is_wpdate = false ) {

  if( $is_wpdate ) {
    $zone = new DateTimeZone('UTC');
    $currentDate = wp_date( 'M d, Y', null, $zone );
  } else {
    $currentDate = \FoodBook\Date_Time_Map::getDateTime();
    $currentDate = $currentDate->format('M d, Y');
  }
  //
  return $currentDate;

}

function foodbook_display_date( $date ) {

  $getDateFormat = get_option('date_format');
  $zone = new DateTimeZone('UTC');
  return wp_date( $getDateFormat, strtotime( $date ), $zone );
}

/**
 * [foodbook_time_elapsed_string description]
 * time elapsed string
 * @param  [type]  $datetime [description]
 * @param  boolean $full     [description]
 * @return string            [description]
 */
function foodbook_time_elapsed_string( $datetime, $full = false ) {
    
    $getCurrentDateTime = \FoodBook\Date_Time_Map::getDateTime();
    $getCurrentDateTime->format( "Y-m-d h:i:s" );
    $getDateTimeDiff    = \FoodBook\Date_Time_Map::getDateTime();
    //
    if( empty( $datetime ) ) {
      return;
    }
    //
    $dateTimeExplode = explode(' ', $datetime);
    $getOrderDate = $dateTimeExplode[0];
    $getOrderDate = explode('-', $getOrderDate);
    //
    $getOrderTime = $dateTimeExplode[1];
    $getOrderTime = explode(':', $getOrderTime);

    // Set order date and time
    $getDateTimeDiff->setDate( $getOrderDate[0], $getOrderDate[1], $getOrderDate[2] );
    $getDateTimeDiff->setTime( $getOrderTime[0], $getOrderTime[1], $getOrderTime[2] );

    $diff = $getCurrentDateTime->diff($getDateTimeDiff);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = array(
        'y' => esc_html__( 'year', 'foodbook' ),
        'm' => esc_html__( 'month', 'foodbook' ),
        'w' => esc_html__( 'week', 'foodbook' ),
        'd' => esc_html__( 'day', 'foodbook' ),
        'h' => esc_html__( 'hour', 'foodbook' ),
        'i' => esc_html__( 'minute', 'foodbook' ),
        's' => esc_html__( 'second', 'foodbook' ),
    );
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
        } else {
            unset($string[$k]);
        }
    }

    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) .' '.esc_html__( 'ago', 'foodbook' ) : esc_html__( 'just now', 'foodbook' );
}

/**
 * [foodbook_page_permission description]
 * @param  [type] $role [description]
 * @return url       [description]
 */
function foodbook_page_permission( $role ) {

  $url = home_url('/');

  if( is_user_logged_in() ) {

    $user = wp_get_current_user();

    $roles = $user->roles;

    if( $roles[0] != $role ) {
      wp_safe_redirect( $url );
    }

  } else {
    wp_safe_redirect( $url );
    exit;

  }

}

/**
 * foodbook_is_user_role
 * @return bool
 */
function foodbook_is_user_role( $role ) {

  if( is_user_logged_in() ) {

    $user = wp_get_current_user();

    $roles = $user->roles;

    if( $roles[0] == $role ) {
      return true;
    } else {
      return false;
    }

  }

}

/**
 * foodbook_is_multi_branch 
 * check is set multi branch
 * @return bool
 */

function foodbook_is_multi_branch() {

  if( ! foodbook_is_active_multi_branch() ) {
    return false;
  }

  $options = get_option('foodbook_options');

  if( !empty( $options['brunch-type'] ) && $options['brunch-type'] == 'multi' ) {
    return true;
  } else {
    return false;
  }

}


/**
 * foodbook_is_active_multi_branch 
 * check is set active multi branch
 * @return bool
 */

function foodbook_is_active_multi_branch() {

  if( ! class_exists('FoodbookMultibranch') ) {
    return false;
  } else {
    return true;
  }

}

/**
 * foodbook_is_active_inrestaurant 
 * check is set active inrestaurant order
 * @return bool
 */

function foodbook_is_active_inrestaurant() {

  if( ! class_exists('Fbiro') ) {
    return false;
  } else {
    return true;
  }

}

/**
 * foodbook_currency_symbol_position
 * currency symbol position
 * @return 
 */

function foodbook_currency_symbol_position( $price , $format = true ) {

  $currencyPos = get_option( 'woocommerce_currency_pos' );

  $currency   = get_woocommerce_currency_symbol();

  if( !$price ) {
    return;
  }

  if( $format ) {
    $price = foodbook_woo_custom_number_format( $price );
  }

  
  $getPrice = $currency.$price;

  if( $currencyPos != 'left' ) {

    switch( $currencyPos ) {

      case 'right':
        $getPrice =  $price.$currency;
      break;
      case 'left_space':
        $getPrice =  $currency.' '.$price;
      break;
      case 'right_space':
        $getPrice =  $price.' '.$currency;
      break;
      default :
        $getPrice = $currency.$price;
      break;

    }

  }

  return $getPrice;
  
}

/**
 * foodbook_bootstrap_column_map
 * bootstrap grid column maping
 * @return 
 */

function foodbook_bootstrap_column_map( $col ) {

  
  switch( $col ) {

    case '2' :
      $setCol = '6';
      break;
    case '3' :
      $setCol = '4';
      break;
    case '4' :
      $setCol = '3';
      break;
      default: 
        $setCol = '4';
      break;
  }

  return $setCol;


}
function foodbookgetlkey() {
  return get_option( "foodbook_plugin_lic_Key", "" );
}
/**
 * foodbook_woo_custom_number_format
 * custom number format decimal, thousand separator  and Number of decimals set 
 * @return 
 */

function foodbook_woo_custom_number_format( $number ) {

  if( empty( $number ) ) {
    return;
  }
  
  $decimal_separator  = wc_get_price_decimal_separator();
  $thousand_separator = wc_get_price_thousand_separator();
  $decimals           = wc_get_price_decimals();

  return number_format( $number, $decimals, $decimal_separator, $thousand_separator);

}

/**
 * This function combine with currency symbol position and number formating
 * @param  [type] $price [description]
 * @return [type]        [description]
 */
function  foodbook_price_number_formating($price, $format = true ) {
  return foodbook_currency_symbol_position( $price, $format );
}

/**
 * foodbook_extra_option_price_filter
 * @param  [type] $data [description]
 * @return [type]       [description]
 */
function foodbook_extra_option_price_filter( $data ) {

  $explodeData = explode(':', $data);
  $arrayEnd = end($explodeData);
  return preg_replace('/[^0-9-.]+/', '', $arrayEnd );
}

/**
 * [foodbook_date_format description]
 * @param  string $format [description]
 * @param  [type] $date   [description]
 * @return string         [description]
 */
function foodbook_date_format( $date, $format = '' ) {
  $format = !empty( $format ) ? $format : 'M-d-Y';
  return date( $format, strtotime( $date ) );
}

function foodbook_is_location_type_address() {

  $options = get_option('foodbook_options');

  return !empty( $options['location_type'] ) && $options['location_type'] == 'address' ? true : false;

}
function foodbookgetG() {
  global $lstatus;
  if( !foodbookgetlkey() ) {
    return;
  }
  return $lstatus["getlst"];
}

/**
 * [foodbook_time_format description]
 * @return string
 */
function foodbook_time_format() {

  $options = get_option('foodbook_options');

  $timeFormat = 'h:ia';
  if( !empty( $options['delivery-time-format'] ) && $options['delivery-time-format'] == '24' ) {
    $timeFormat = 'H:i';
  }
  return $timeFormat;

}
/**
 * Convert php date format to js date format 
 * @param  $format php date
 * @return string
 */
function foodbook_datepicker_format($format) {

  $assoc = array(
      'Y' => 'yy',
      'y' => 'yy',
      'F' => 'MM',
      'm' => 'mm',
      'l' => 'DD',
      'd' => 'dd',
      'D' => 'D',
      'j' => 'd',
      'M' => 'M',
      'n' => 'm',
      'z' => 'o',
      'N' => '',
      'S' => '',
      'w' => '',
      'W' => '',
      't' => '',
      'L' => '',
      'o' => '',
      'a' => '',
      'A' => '',
      'B' => '',
      'g' => '',
      'G' => '',
      'h' => '',
      'H' => '',
      'i' => '',
      's' => '',
      'u' => ''
  );

  $keys = array_keys($assoc);

  $indeces = array_map(function($index) {
      return '{{' . $index . '}}';
  }, array_keys($keys));

  $format = str_replace($keys, $indeces, $format);

  return str_replace($indeces, $assoc, $format);

}

/**
 * [foodbook_get_weekday description]
 * @return array
 */
function foodbook_get_weekday() {
  
  global $wp_locale;
  $days = [];
  for ( $day_index = 0; $day_index <= 6; $day_index++ ) {
    $days[$day_index] = $wp_locale->get_weekday( $day_index );
  }
  return $days;

}

/**
 * [foodbook_get_the_day description]
 * @return string
 */
function foodbook_get_the_day( $number ) {
  $weekday = foodbook_get_weekday();
  return !empty( $weekday[$number] ) ? $weekday[$number] : '';
}

/**
 * [foodbook_get_day_number description]
 * @return [type] [description]
 */
function foodbook_get_day_number( $dayName ) {
  
  global $wp_locale;
  $days = [];
  for ( $day_index = 0; $day_index <= 6; $day_index++ ) {
    $days[$wp_locale->get_weekday( $day_index )] = $day_index;
  }
  return $days[$dayName];
}
/**
 * [foodbook_get_day_by_date description]
 * @param  [type] $date [description]
 * @return string
 */
function foodbook_get_day_by_date( $date ) {

  $dayByDate = \FoodBook\Date_Time_Map::getDay( $date );
  $dayNumber = foodbook_get_day_number( $dayByDate );
  return foodbook_get_the_day( $dayNumber );

}
/**
 * [foodbook_display_day_by_date description]
 * @param  [type] $date [description]
 * @return [type]       [description]
 */
function foodbook_display_day_by_date( $date ) {
  return \FoodBook\Date_Time_Map::getDay( $date );
}

/**
 * [foodbook_time_solt_options_html description]
 * @param  [type] $timeList [description]
 * @return [type]           [description]
 */
function foodbook_time_solt_options_html( $timeList ) {

  if( !empty( $timeList ) ) {

    $text = FoodBook\Inc\Text::getText();
    //
    $options = get_option('foodbook_options');
    if( !empty( $options['active-asap-timeslot'] ) ) {
      echo '<option value="'.esc_attr('ASAP').'">'.esc_html( $text['asap_text'] ).'</option>';
    }

    foreach ( $timeList as $time ) {

      $a = [ $time['times'], $time['slot_order_status'], $time['break_time'] ];
      $v = implode( ',', $a );

        echo '<option value="'.esc_html( $v ).'">'.esc_html( $time['times'].foodbook_time_slot_status( $time ) ).'</option>';
    }
  }

}

/**
 * [foodbook_time_slot_order_count description]
 * @param  string $date [description]
 * @param  string $time [description]
 * @return [type]       [description]
 */
function foodbook_time_slot_order_count( $date = '', $time = '' ) {
  // 02/20/2021 10:30am
  
  if( $date && $time ) {
    $args = array(
      'limit'         => '-1',
      'date_created'  => esc_html( $date ),
      'pickup_time'   => esc_html( $time )
    );
    $orders = wc_get_orders( $args );
    return count( $orders );
  }
}
/**
 * [foodbook_time_slot_status description]
 * @return [type] [description]
 */
function foodbook_time_slot_status( $status ) {
  $text = FoodBook\Inc\Text::getText();
  if( $status['slot_order_status'] == 'no' ) {
    return ' - '.$text['slot_full_text'];
  }

  if( $status['break_time'] == 'true' ) {
    return ' - '.$text['valid_break_time'];
  }

}

/**
 * [foodbook_wc_before_cart_hook description]
 * @return [type] [description]
 */
function foodbook_wc_before_cart_hook() {
  ob_start();
  do_action( 'woocommerce_before_cart' );
  return ob_get_clean();
}

/**
 * [foodbook_radius_based_delivery_fee description]
 * @return [type] [description]
 */
function foodbook_radius_based_delivery_fee() {

  $options = get_option('foodbook_options');
  $deliveryFee = '';
  // Delivery fee based on kilometer for multi branch
  if( foodbook_is_multi_branch() && isset( $_COOKIE['fb_branch_id'] ) ) {

    $deliveryFee = get_post_meta( $_COOKIE['fb_branch_id'], 'foodbookdelivery_fee_on_branch', true );

    if( get_option('foodbook_multideliveryfees_option') ) {

      if( isset( $_COOKIE['fb_location_distance'] ) && isset( $_COOKIE['fb_branch_id'] ) ) {

        $feeRange = get_post_meta( $_COOKIE['fb_branch_id'], 'foodbookdelivery_fee_on_km', true );

        if( !empty( $feeRange ) ) {

          $cacheKM = 0;

          foreach( $feeRange as $val ) {

            if( $cacheKM < $_COOKIE['fb_location_distance'] && $val['km'] >= $_COOKIE['fb_location_distance'] ) {
              $deliveryFee = $val['fee'];
            }

            $cacheKM = $val['km'];

          }

        }

      }

    }

  } else {

    $deliveryFee    = isset( $options['delivery-fee'] ) ? $options['delivery-fee'] : '';

    // Delivery fee based on kilometer for single branch
    
    if( isset( $options['delivery-fee-km'] ) && !empty( $options['delivery-fee-km'] )  ) {

      if( isset( $_COOKIE['fb_location_distance'] ) ) {

        $feeRange = $options['delivery-fee-km'];

        if( !empty( $feeRange ) ) {

          $cacheKM = 0;

          foreach( $feeRange as $val ) {

            if( $cacheKM < $_COOKIE['fb_location_distance'] && $val['km'] >= $_COOKIE['fb_location_distance'] ) {
              $deliveryFee = $val['fee'];
            }

            $cacheKM = $val['km'];

          }

        }

      }

    }

  }

  return $deliveryFee;

}

/**
 * foodbook_radius_based_delivery_fee description
 * @return string
 */
function foodbook_zipcode_based_delivery_fee() {

  $options = get_option('foodbook_options');
  $deliveryFee = '';
  
  // Delivery fee based on kilometer for multi branch
  if( foodbook_is_multi_branch() && isset( $_COOKIE['fb_branch_id'] ) ) {

    $deliveryFee = get_post_meta( $_COOKIE['fb_branch_id'], 'foodbookdelivery_fee_on_branch', true );

    if( get_option('foodbook_multideliveryfees_option') ) {

      if( isset( $_COOKIE['fb_selected_zipcode'] ) && isset( $_COOKIE['fb_branch_id'] ) ) {

        $zip = get_post_meta( $_COOKIE['fb_branch_id'], 'foodbookbranch_zipcode_with_fee', true );

        if( !empty( $zip ) ) {

          foreach( $zip as $val ) {

            if( $val['code'] == $_COOKIE['fb_selected_zipcode'] ) {
              $deliveryFee = $val['fee'];
            }

          }

        }

      }

    }

  } else {

    $deliveryFee    = isset( $options['delivery-fee'] ) ? $options['delivery-fee'] : '';

    // Delivery fee based on kilometer for single branch
    
    if( isset( $options['zip-delivery-fee'] ) && !empty( $options['zip-delivery-fee'] )  ) {

      if( isset( $_COOKIE['fb_selected_zipcode'] ) ) {

        $zipCodes = $options['zip-delivery-fee'];

        if( !empty( $zipCodes ) ) {

          foreach( $zipCodes as $val ) {

            if( $val['code'] == $_COOKIE['fb_selected_zipcode'] ) {
              $deliveryFee = $val['fee'];
            }

          }

        }

      }

    }

  }

  return $deliveryFee;

}

/**
 * foodbook_get_zipcodes get zipcode from settings or branch
 * @return array
 */
function foodbook_get_zipcodes() {

  $options = get_option('foodbook_options');
  $multideliveryfees = get_option('foodbook_multideliveryfees_option');
  $zipCodes = '';

  // Check multi branch and selected branch ID
  if( foodbook_is_multi_branch() && !empty( $_COOKIE['fb_branch_id'] ) ) {

      // checkout page check
      if( is_checkout() ) {
        // Check multideliveryfees option
        if( !empty( $multideliveryfees ) ) {
          $getZipCodes = get_post_meta( $_COOKIE['fb_branch_id'], 'foodbookbranch_zipcode_with_fee', true );
          $getZipCodes = !empty( $getZipCodes ) ? $getZipCodes : [];
          $zipCodes = array_column( $getZipCodes, 'code');
        } else {
          $zipCodes = get_post_meta( $_COOKIE['fb_branch_id'], 'foodbookbranch_zipcode', true );
        }
      }

  } else {

    // Check multideliveryfees option
    if( !empty( $multideliveryfees ) ) {
      
      $zipCodes = !empty( $options['zip-delivery-fee'] ) ? $options['zip-delivery-fee'] : [];
      $zipCodes = array_column( $zipCodes, 'code' );

    } else {
      $zipCodes = !empty( $options['delivery_zip'] ) ? $options['delivery_zip'] : '';
    }

  }

  return $zipCodes;

}