<?php
if (!function_exists('isUserLoggedIN')) {
  function isUserLoggedIN()
  {
    // Always allow for now (no user session required)
    return true;
  }
}

$GLOBALS['HALALFEST_BADGE_NUM'] = '1';
$GLOBALS['HALALFEST_LISTING_NUM'] = '16';
$GLOBALS['URBCAN_POINTS'] = '10'; //The number of points a user gets for checking in.
$GLOBALS['FACEBOOK_USER_FIELDS'] = array( //The user data we want to collect from the API
  'id',
  'email',
  'first_name',
  'last_name',
  'about',
  'age_range',
  'birthday',
  'education',
  'picture',
  'timezone',
  'gender',
  'middle_name',
  'name',
);

$GLOBALS['MOMENTS_URL'] = 'moments/uh_';
$GLOBALS['TIPS_URL'] = 'tips/uh_';
$GLOBALS['CERTS_URL'] = 'certs/uh_';
$GLOBALS['listing_img'] = "https://s3-us-west-1.amazonaws.com/urban-halal/static_assets/landing_page/listing-default.png";

function api_preRequestCustomFunctionality($user, $schemaFields)
{
  if (isset($_REQUEST['read']) && isset($schemaFields['membersNum']) && @$_REQUEST['_user_friends_only'] == '1' && $user) {
    $_REQUEST['membersNum_match'] = urbcan_getFriendNumsFriendMeta($user);
  }
}


function api_postRequestCustomFunctionality($user, $data = array(), $meta, $errorsAndAlerts, $success = "")
{

  $pointSettings = mysql_get('points_system', '1');
  $shareTexts = mysql_get('share_texts', '1');

  //Add badge for halal fest.
  //If we're creating a check in record.
  if (isset($data[0]['membersNum'])) {
    foreach ($data as $dataKey => $row) {
      if ($row['membersNum']) {
        $imageRecords = mysql_select('photo_uploads', "`membersNum` = {$row['membersNum']} AND `for_photo` = 'photo' AND `flagged` = 0 ORDER BY `createdDate` DESC LIMIT 0,3", "`num`");
        foreach ($imageRecords as $key => $imageRecord) {
          $imageFiles = getUploadRecords('photo_uploads', 'photos', $imageRecord['num']);
          foreach ($imageFiles as $file) {
            $data[$dataKey]['members.recent_photos'][] = $file;
          }
        }
      }
    }
  }

  //Add the first 3 images for a listing if the records returned have a listings num field.
  if (isset($data[0]['listingsNum'])) {
    foreach ($data as $dataKey => $row) {
      if ($row['listingsNum']) {
        $imageRecords = mysql_select('photo_uploads', "`listingsNum` = {$row['listingsNum']} AND `for_photo` = 'photo' AND `flagged` = 0 ORDER BY `createdDate` DESC LIMIT 0,3", "`num`");
        foreach ($imageRecords as $key => $imageRecord) {
          $imageFiles = getUploadRecords('photo_uploads', 'photos', $imageRecord['num']);
          foreach ($imageFiles as $file) {
            $data[$dataKey]['listings.recent_photos'][] = $file;
          }
        }
      }
    }
  }



  if (isset($_REQUEST['create']) && @$_REQUEST['_section'] == 'check_ins') {



    //If check in wasn't cancelled.
    if (!$errorsAndAlerts) {

      //Update the users points
      mysql_update('check_ins', $data['num'], null, array('points' => $pointSettings['location_check_in']));
      api_updateUsersPoints($user);
      $success = $pointSettings['checkin_alert'] . "\r\n";
      $checkins_count = mysql_count('check_ins', "`membersNum` = " . intval($user['num']));
      mysql_update('members', $user['num'], null, array('check_ins' => $checkins_count));

      if (@$data['listingsNum']) {
        $totalPoints = 0;
        $totalCheckIns = 0;
        $checkIns = mysql_select('check_ins', "`listingsNum` = '" . $data['listingsNum'] . "'", "`points`");
        foreach ($checkIns as $checkIn) {
          $totalPoints += intval($checkIn['points']);
          $totalCheckIns++;
        }
        mysql_update('listings', intval($data['listingsNum']), null, array('points' => $totalPoints, 'checkins' => $totalCheckIns));
      }

      // Abhishek : check_ins notification
      list($listing, $meta) = getRecords(array(
        'tableName' => 'listings',
        'where' => "`num` = {$data['listingsNum']}",
        'loadUploads' => false,
        'allowSearch' => false,
        'loadCreatedBy' => false,
        'loadListDetails' => false,
        'limit' => 1
      ));

      $listing = api_addOpenCloseDetailsToListing($listing[0]);

      if (empty($user['email_actions']) || !in_array('checkins', explode(',', $user['email_actions']))) {
        sendFirstCheckInEmail($listing, $user);
      }

      $day = strtolower(date("l"));
      $listingOpenTime = $listing[$day . "_open:label"];
      $listingCloseTime = $listing[$day . "_close:label"];

      if ($listing['restaurant_status'] == 'closed') {
        $day = strtolower(date("l", strtotime(date("Y-m-d") . " +1 day")));
        $listingOpenTime = $listing[$day . "_open:label"];
        $listingCloseTime = $listing[$day . "_close:label"];
      }

      $is_rated = mysql_count('ratings', "`membersNum` = {$user['num']} AND `listingsNum` = {$data['listingsNum']}") ? "1" : "0";
      $is_foodie_exp = mysql_count('foodie_experience', "`membersNum` = {$user['num']} AND `listingsNum` = {$data['listingsNum']}") ? "1" : "0";

      $placeholders = array("#userName" => $user['username'], "#listingName" => $listing['name']);
      $msg = str_replace(array_keys($placeholders), array_values($placeholders), $shareTexts['checkin_notify_text']);
      // $msg = "[".$user['facebook_first_name']."] Share your foodie experience for ".$listing['name'];

      $notifyData = ['listingsNum' => $data['listingsNum'], 'last_check_in' => $data['createdDate'], 'notification_type' => 'check_ins', 'listingName' => $listing['name'], 'listingAddress' => $listing['address_1'], 'userName' => $user['username'], 'firstName' => $user['facebook_first_name'], 'average_rating' => $listing['average_rating'], 'is_rated' => $is_rated, 'is_foodie_exp' => $is_foodie_exp, 'listingOpenTime' => $listingOpenTime, 'listingCloseTime' => $listingCloseTime, 'listingStatus' => $listing['restaurant_status'], 'userId' => $user['num']];

      createNotification($msg, "check_ins", $notifyData, 'userNum', $user['num'], 'urbanhalal.com');

    }
  }

  //Add points for a review
  if (isset($_REQUEST['create']) && @$_REQUEST['_section'] == 'reviews') {
    mysql_update('reviews', $data['num'], null, array('points' => $pointSettings['leave_a_tip']));
    api_updateUsersPoints($user);
    $user = mysql_get('members', $user['num']);
    urbcan_updateMember($user, $user['rank'], false);
    $successMessage = str_replace("<pointvalue>", intval($pointSettings['leave_a_tip']), $pointSettings['tip_alert']);
    $success .= $successMessage . "\r\n";
    //Abhishek : update listing reviews count
    $reviews = mysql_count('reviews', "`flagged` = 0 AND `listingsNum` = " . intval($data['listingsNum']));
    mysql_update('listings', intval($data['listingsNum']), null, array('reviews' => $reviews));

    $reviews = mysql_count('reviews', "`flagged` = 0 AND `membersNum` = " . intval($user['num']));
    mysql_update('members', intval($user['num']), null, array('reviews' => $reviews));

    if (empty($user['email_actions']) || !in_array('reviews', explode(',', $user['email_actions']))) {
      sendFirstRatingReviewEmail($data, $user);
    }

    $errorsAndAlerts .= permalink_add($GLOBALS['TIPS_URL'] . time(), 'reviews', $data['num'], true);
  }

  //Add points for a survey
  if (isset($_REQUEST['create']) && @$_REQUEST['_section'] == 'order_survey') {
    mysql_update('order_survey', $data['num'], null, array('points' => $pointSettings['order_survey']));
    api_updateUsersPoints($user);
    $user = mysql_get('members', $user['num']);
    urbcan_updateMember($user, $user['rank'], false);

  }

  //Add ponts for a successful rating.
  if (isset($_REQUEST['create']) && @$_REQUEST['_section'] == 'ratings') {
    mysql_update('ratings', $data['num'], null, array('points' => $pointSettings['rate_a_place']));
    api_updateUsersPoints($user);
    $user = mysql_get('members', $user['num']);
    urbcan_updateMember($user, $user['rank'], false);
    $successMessage = str_replace("<pointvalue>", intval($user['ratings']) * intval($pointSettings['rate_a_place']), $pointSettings['rate_alert']);
    $success .= $successMessage . "\r\n";
    //Abhishek : update listing rating count  
    $total_ratings = mysql_count('ratings', "`listingsNum` = " . intval($data['listingsNum']));
    mysql_update('listings', intval($data['listingsNum']), null, array('total_ratings' => $total_ratings));

    $total_ratings = mysql_count('ratings', "`membersNum` = " . intval($user['num']));
    mysql_update('members', intval($user['num']), null, array('ratings' => $total_ratings));

    if (empty($user['email_actions']) || !in_array('ratings', explode(',', $user['email_actions']))) {
      sendFirstRatingReviewEmail($data, $user);
    }

    $avgRating = updateListingAvgRating($data['listingsNum']);

    $data['average_rating'] = strval($avgRating);

    $data = [$data]; // data require in array on app side
  }

  //Add poitns for following a listing.
  if (isset($_REQUEST['create']) && @$_REQUEST['_section'] == 'listings_follows') {
    mysql_update('listings_follows', $data['num'], null, array('points' => '0'));
    api_updateUsersPoints($user);
    $user = mysql_get('members', $user['num']);
    urbcan_updateMember($user, $user['rank'], false);
    $success .= "\r\n";
    //Abhishek : update listing rating count  
    $total_follows = mysql_count('listings_follows', "`listingsNum` = " . intval($data['listingsNum']));
    mysql_update('listings', intval($data['listingsNum']), null, array('followers' => $total_follows));
  }

  //Add points for a successful upload for a photo or certificate.
  if (isset($_REQUEST['save_upload']) && @$_REQUEST['_section'] == 'photo_uploads' && $_REQUEST['fieldName'] == 'photos' && $_REQUEST['num']) {

    $record = mysql_get('photo_uploads', @$_REQUEST['num'], null, "`num`, `for_photo`, `listingsNum`");
    if (@$record['for_photo'] == 'certificate') {
      mysql_update('photo_uploads', $record['num'], null, array('points' => $pointSettings['halal_certificate_upload']));
      api_updateUsersPoints($user);
      $user = mysql_get('members', $user['num']);
      urbcan_updateMember($user, $user['rank'], false);
      $successMessage = str_replace("<pointvalue>", intval($pointSettings['halal_certificate_upload']), $pointSettings['halal_certificate_upload_alert']);
      $success .= $successMessage . "\r\n";
    } else {
      mysql_update('photo_uploads', $record['num'], null, array('points' => $pointSettings['snap_a_photo']));
      api_updateUsersPoints($user);
      $user = mysql_get('members', $user['num']);
      urbcan_updateMember($user, $user['rank'], false);
      $successMessage = str_replace("<pointvalue>", intval($pointSettings['snap_a_photo']), $pointSettings['photo_upload_alert']);
      $success .= $successMessage . "\r\n";

      //Abhishek : update listing photos count
      $photo_count = mysql_count('photo_uploads', "`flagged` = 0 AND `listingsNum` = '" . intval($record['listingsNum']) . "'");
      mysql_update('listings', intval($record['listingsNum']), null, array('photo_count' => $photo_count));

      $photo_count = mysql_count('photo_uploads', "`flagged` = 0 AND `membersNum` = '" . intval($user['num']) . "'");
      mysql_update('members', intval($user['num']), null, array('photo_count' => $photo_count));

      $errorsAndAlerts .= permalink_add($GLOBALS['MOMENTS_URL'] . time(), 'photo_uploads', @$_REQUEST['num'], true);

      if (empty($user['email_actions']) || !in_array('photo', explode(',', $user['email_actions']))) {
        sendFirstPhotoEmail($data, $user);
      }
    }

  }

  //Add points for liking a photo
  if (isset($_REQUEST['create']) && @$_REQUEST['_section'] == 'photo_likes') {
    mysql_update('photo_likes', $data['num'], null, array('points' => $pointSettings['like_a_photo']));
    api_updateUsersPoints($user);
    $user = mysql_get('members', $user['num']);
    urbcan_updateMember($user, $user['rank'], false);
    $successMessage = str_replace("<pointvalue>", intval($pointSettings['like_a_photo']), $pointSettings['photo_like_alert']);
    $success .= $successMessage . "\r\n";

    // Updating photo likes
    $likeCount = mysql_count('photo_likes', "`photo_uploadsNum` = '{$data['photo_uploadsNum']}'");
    mysql_update('photo_uploads', $data['photo_uploadsNum'], null, array('likes' => $likeCount));

    //Get the insert data
    $values = $_REQUEST['insertData'];
    $photoNum = @$values['photo_uploadsNum'];
    if ($photoNum) {
      $photo = mysql_get('photo_uploads', $photoNum, null, "`num`, `membersNum`, `likes`");
      $member = mysql_get('members', @$photo['membersNum'], null, "`facebook_picture`, `facebook_email`,`facebook_first_name`, `username`, `isAdmin`, `facebook_last_name`");

      if ($member && !$member['isAdmin']) {

        $photoUpload = mysql_get('uploads', null, "`recordNum` = {$photo['num']}", "`urlPath`");
        // $photoLikes  = mysql_count('photo_likes', "`photo_uploadsNum` = ".intval($photo['num']));
        $membersLikedPhoto = mysql_select_join('photo_likes', 'members', "`photo_uploadsNum` = " . intval($photo['num']), "membersNum", array('facebook_picture'), 3);

        $membersPhotos = '';
        foreach ($membersLikedPhoto as $memberLikedPhoto) {
          $membersPhotos .= '<div class="like_user_img" style="float: right;border-radius: 50%;margin-right: 5px;border: 1.5px solid #fff;">
              <img src="' . $memberLikedPhoto['facebook_picture'] . '" style="width: 25px;height: 25px;border-radius: 50%;"></div>';
        }
        $likedBy['username'] = $user['username'];
        $likedBy['facebook_first_name'] = $user['facebook_first_name'];
        $likedBy['facebook_picture'] = $user['facebook_picture'];
        $likedBy['check_ins'] = $user['check_ins'];
        $likedBy['reviews'] = $user['reviews'];
        $likedBy['photo_count'] = $user['photo_count'];

        $unsubUrl = $GLOBALS['SETTINGS']['websiteUrl'] . '/unsubscribe.php?e=' . $member['facebook_email'];
        $placeholders = array_merge(array_keys_prefix('likedBy.', $likedBy), array_keys_prefix('photoBy.', $member), array('likedPhoto' => @$photoUpload['urlPath'], 'likesCount' => $likeCount, 'membersLikedPhoto' => $membersPhotos, 'unsubscribe_url' => $unsubUrl));

        // USER-PHOTO-LIKED
        $emailHeaders = emailTemplate_loadFromDB(array(
          'template_id' => 'USER-PHOTO-LIKED',
          'placeholders' => $placeholders,
        ));
        $mailErrors = sendMessage($emailHeaders);
        if ($mailErrors) {
          $errorsAndAlerts .= "Mail Error: $mailErrors";
        }
      }
    }
  }

  if (isset($_REQUEST['create']) && @$_REQUEST['_section'] == 'user_follows') {
    //Get the insert data
    $values = $_REQUEST['insertData'];
    $followingNum = @$values['followingNum'];
    //Abhishek : increase following count for user
    $following_count = mysql_count('user_follows', "`membersNum` = " . intval($user['num']));
    mysql_update('members', $user['num'], null, array('following' => $following_count));

    $member = mysql_get('members', $followingNum, null, "`username`, `facebook_first_name`, `facebook_email`, `facebook_picture`");

    $unsubUrl = $GLOBALS['SETTINGS']['websiteUrl'] . '/unsubscribe.php?e=' . $member['facebook_email'];

    if ($member) {
      $placeholders = array(
        'following.facebook_first_name' => $member['facebook_first_name'],
        'following.facebook_email' => $member['facebook_email'],
        'following.facebook_picture' => $member['facebook_picture'],
        'following.username' => $member['username'],
        'followedBy.facebook_first_name' => $user['facebook_first_name'],
        'followedBy.facebook_last_name' => $user['facebook_last_name'][0],
        'followedBy.facebook_picture' => $user['facebook_picture'],
        'followedBy.username' => $user['username'],
        'followedBy.photo_count' => $user['photo_count'],
        'followedBy.check_ins' => $user['check_ins'],
        'followedBy.reviews' => $user['reviews'],
        'unsubscribe_url' => $unsubUrl
      );
      // USER-PHOTO-LIKED
      $emailHeaders = emailTemplate_loadFromDB(array(
        'template_id' => 'USER-FOLLOWING',
        'placeholders' => $placeholders,
      ));

      $mailErrors = sendMessage($emailHeaders);
      if ($mailErrors) {
        $errorsAndAlerts .= "Mail Error: $mailErrors";
      }
    }

  }

  //Add points for inviting a friend.
  if (isset($_REQUEST['sms_promote'])) {
    api_updateUsersPoints($user);
    $user = mysql_get('members', $user['num']);
    urbcan_updateMember($user, $user['rank'], false);
    $successMessage = str_replace("<pointvalue>", intval($pointSettings['invite_a_friend']), $pointSettings['invite_friend_alert']);
    $success .= $successMessage . "\r\n";
  }


  //listing_detail Get the open and close times for each listing.
  if ((@$_REQUEST['_section'] == 'listings' && isset($_REQUEST['read'])) || isset($_REQUEST['search']) || isset($_REQUEST['web_search']) || isset($_REQUEST['get-listings-for-order']) || isset($_REQUEST['banner-listings'])) {
    foreach ($data as $key => $listing) {

      if (is_null($listing['_distance']) || empty($listing['_distance'])) {
        $listing['_distance'] = '0.0';
      }
      if (is_null($listing['reviews']) || empty($listing['reviews'])) {
        $listing['reviews'] = '';
      }
      if (is_null($listing['photo_count']) || empty($listing['photo_count'])) {
        $listing['photo_count'] = '';
      }

      //Add the opening and closing time for the listing.
      $data[$key] = api_addOpenCloseDetailsToListing($listing);

      $days = array('monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday');
      foreach ($days as $day) {
        if (($data[$key][$day . "_open"] === NULL || $data[$key][$day . "_open"] === '') && ($data[$key][$day . "_close"] === NULL || $data[$key][$day . "_close"] === '')) {
          $data[$key][$day . "_open"] = '';
          $data[$key][$day . "_close"] = '';
          $data[$key][$day . "_open:label"] = '';
          $data[$key][$day . "_close:label"] = '';
        }
      }

      // Abhishek return status closed if listing set offline in cms for orders listings
      if (isset($_REQUEST['get-listings-for-order'])) {

        if (!$listing['is_online'] || $data[$key]['restaurant_status'] === "closing_soon") {
          $data[$key]['restaurant_status'] = 'closed';
        }

      }

      // add latest order users
      list($latestOrdersMembersText, $ordersCount) = getListinglatestOrdersCountAndText($listing['num']);
      $data[$key]["latest_orders_members"] = $latestOrdersMembersText;
      $data[$key]['orders_count'] = $ordersCount;

      if (!empty($data[$key]['amenities'])) {
        $data[$key]['amenities'] = getAmenities($data[$key]['amenities']);
      } else {
        $data[$key]['amenities'] = [];
      }

      $data[$key]['latestClikedPhotoByUser'] = '';

      $data[$key]['compliance'] = '';

      $data[$key]['slaughter_method'] = is_null($data[$key]['slaughter_method']) ? "" : $data[$key]['slaughter_method'];

      $data[$key]['cuisine'] = startsWith("\t", $data[$key]['cuisine']) ? $data[$key]['cuisine'] : "\t" . $data[$key]['cuisine'] . "\t";

      //Abhishek: convert cuisines to uppercase
      $data[$key]['cuisine'] = implode("\t", array_map(function ($v) {
        return strtoupper($v); }, explode("\t", $data[$key]['cuisine'])));

      //Add last checkin for a user.
      $data[$key]['last_check_in_by_user']['createdDate'] = ""; // to handle case if there is no check in by user
      $data[$key]['is_first_checkin_given'] = "0";
      if (isUserLoggedIN($user) && $last_check_in_by_user = mysql_get('check_ins', null, "`membersNum` = {$user['num']} AND `listingsNum` = {$listing['num']} ORDER BY `createdDate` DESC", "`num`, `createdDate`")) {
        $data[$key]['last_check_in_by_user'] = $last_check_in_by_user;
        $data[$key]['is_first_checkin_given'] = $checkin_count ? "1" : "0";
      }

      //Abhishek get menu categories

      $data[$key]['menu_categories'] = mysql_select_query("SELECT `cmsb_menu_categories`.num, UPPER(category_name) as category_name FROM cmsb_menu_categories INNER JOIN cmsb_menu ON `cmsb_menu`.category =  `cmsb_menu_categories`.num WHERE `cmsb_menu`.listingsNum = {$listing['num']} GROUP BY `cmsb_menu_categories`.num ORDER BY `cmsb_menu_categories`.dragSortOrder DESC");

      $data[$key]['is_ramadan'] = "0";
      foreach ($data[$key]['menu_categories'] as $cat) {
        if ($cat['category_name'] == "RAMADAN") {
          $data[$key]['is_ramadan'] = "1";
          break;
        }
      }

      $data[$key]['latest_reviews'] = mysql_select('reviews', "`listingsNum` = " . intval($listing['num']) . " AND `flagged` = 0 ORDER BY `createdDate` DESC LIMIT 0,2");
      foreach ($data[$key]['latest_reviews'] as $reviewKey => $review) {
        if ((int) $review['membersNum'] === 0) {
          $data[$key]['latest_reviews'][$reviewKey]['isYelpReview'] = 1;
          $data[$key]['latest_reviews'][$reviewKey]['facebook_first_name'] = $review['yelp_userName'];
          $data[$key]['latest_reviews'][$reviewKey]['facebook_last_name'] = '';
          $data[$key]['latest_reviews'][$reviewKey]['member_picture'] = $review['yelp_userImage'];
          $data[$key]['latest_reviews'][$reviewKey]['share_text'] = str_replace(["#userName", "#listingName", "#link"], [$review['yelp_name'], $listing['name'], $data[$key]['latest_reviews'][$reviewKey]['short_url']], $shareTexts['tip_text']);
          $data[$key]['latest_reviews'][$reviewKey]['is_following'] = "0";
          $data[$key]['latest_reviews'][$reviewKey]['is_follower'] = "0";
        } else {
          $member = mysql_select_query("SELECT `facebook_first_name`, `facebook_last_name`, `facebook_picture` FROM `" . getTableNameWithPrefix('members') . "` WHERE `num` = " . intval($review['membersNum']));
          $data[$key]['latest_reviews'][$reviewKey]['facebook_first_name'] = @$member[0]['facebook_first_name'];
          $data[$key]['latest_reviews'][$reviewKey]['facebook_last_name'] = @$member[0]['facebook_last_name'];
          $data[$key]['latest_reviews'][$reviewKey]['member_picture'] = @$member[0]['facebook_picture'];
          $data[$key]['latest_reviews'][$reviewKey]['share_text'] = str_replace(["#userName", "#listingName", "#link"], [@$member[0]['username'], $listing['name'], $data[$key]['latest_reviews'][$reviewKey]['short_url']], $shareTexts['tip_text']);
          $data[$key]['latest_reviews'][$reviewKey]['is_following'] = (isUserLoggedIN($user) && mysql_count("user_follows", "`membersNum` = {$user['num']} AND `followingNum` = {$review['membersNum']}")) ? "1" : "0";
          $data[$key]['latest_reviews'][$reviewKey]['is_follower'] = (isUserLoggedIN($user) && mysql_count("user_follows", "`membersNum` = {$review['membersNum']} AND `followingNum` = {$user['num']}")) ? "1" : "0";
          $data[$key]['latest_reviews'][$reviewKey]['isYelpReview'] = 0;
        }
        $data[$key]['latest_reviews'][$reviewKey]['short_url'] = $GLOBALS['SETTINGS']['shortUrl'] . $review['permalink'];

        unset($data[$key]['latest_reviews'][$reviewKey]['yelp_reviewId']);
        unset($data[$key]['latest_reviews'][$reviewKey]['yelp_userName']);
        unset($data[$key]['latest_reviews'][$reviewKey]['yelp_userImage']);
      }

      // Abhishek : setting key for photos data. Needed on app side
      $latest_photos = addMemberPhotoLikesToPhotoUp(mysql_select('photo_uploads', "`listingsNum` = " . intval($listing['num']) . " AND `for_photo` = 'photo' AND `flagged` = 0 ORDER BY RAND() LIMIT 0,3", "`num`, `membersNum`, `tag_ids`, `listingsNum`, `views`, `permalink`"), 'photo_likes');

      foreach ($latest_photos as $photoKey => $photo) {
        $latest_photos[$photoKey]['photos'] = getUploadRecords('photo_uploads', 'photos', $photo['num']);

        // $photo_listing = mysql_get('listings', $photo['listingsNum']);
        // if($photo_listing){
        $latest_photos[$photoKey]['listings']['name'] = $listing['name'];
        $latest_photos[$photoKey]['listings']['num'] = strval($listing['num']);
        // }

        $photoShareText = $shareTexts['moment_text'];

        $mem = mysql_get('members', null, "`num` = " . intval($photo['membersNum']), "`facebook_picture`, `facebook_first_name`, `facebook_last_name`, `username`, `isAdmin`, `num`");
        $latest_photos[$photoKey]['members'] = null;
        if ($mem) {
          $latest_photos[$photoKey]['members'] = $mem;
          if ($mem['isAdmin']) {
            $latest_photos[$photoKey]['members'] = setUploadedByListing($mem, $latest_photos, $photoKey);
            $photoShareText = $shareTexts['admin_moment_text'];
          }
        }

        $latest_photos[$photoKey]['tags'] = addPhotoTags($latest_photos, $photoKey);

        $latest_photos[$photoKey]['is_liked'] = "0";
        $latest_photos[$photoKey]['like_type'] = "";
        if (isUserLoggedIN($user)) {
          $photoLiked = mysql_get('photo_likes', null, "`flagged` = 0 AND `membersNum` = " . intval($user['num']) . " AND `photo_uploadsNum` = " . intval($photo['num']), "`like_type`");
          if ($photoLiked) {
            $latest_photos[$photoKey]['is_liked'] = "1";
            $latest_photos[$photoKey]['like_type'] = $photoLiked['like_type'];
          }
        }

        $latest_photos[$photoKey]['views'] = $latest_photos[$photoKey]['views'] ? $latest_photos[$photoKey]['views'] : "0";

        $latest_photos[$photoKey]['short_url'] = $GLOBALS['SETTINGS']['shortUrl'] . $latest_photos[$photoKey]['permalink'];

        $latest_photos[$photoKey]['share_text'] = str_replace(["#userName", "#listingName", "#link"], [@$latest_photos[$photoKey]['members']['username'], $listing['name'], $latest_photos[$photoKey]['short_url']], $photoShareText);
      }

      if (isset($_REQUEST['web_search']) || (isset($_REQUEST['api_type']) && $_REQUEST['api_type'] == 'web')) {
        // get any menu photo for listing
        $data[$key]['menu_photo'] = mysql_get_query("SELECT urlPath from cmsb_uploads as uploads INNER JOIN cmsb_menu as menu ON menu.num = uploads.recordNum AND uploads.tableName = 'menu' WHERE menu.listingsNum = {$listing['num']} ORDER BY RAND() LIMIT 1");
      }

      //Abhishek listing detail
      if (isset($_REQUEST['listings.api_type']) || isset($_REQUEST['api_type'])) {
        $data[$key]['urban_data_photo'] = $latest_photos;

        //Abhishek: add isMenu = true if listings has menu else false
        $data[$key]['has_menu'] = '0';

        //Abhishek: add coupons
        $data[$key]['coupons'] = mysql_select("coupons", "`listingsNum` = {$listing['num']} AND `is_approved` = 1 ORDER BY `createdDate` DESC LIMIT 0,3");

        if (count($data[$key]['coupons']) > 0) {
          foreach ($data[$key]['coupons'] as $cKey => $coupon) {
            $data[$key]['coupons'][$cKey]['category'] = strtoupper($coupon['category']);
            $imageFiles = getUploadRecords('coupons', 'image', $coupon['num']);
            foreach ($imageFiles as $file) {
              $data[$key]['coupons'][$cKey]['image'] = $file['urlPath'];
            }
            $data[$key]['coupons'][$cKey]['isDefaultCoupon'] = "0";
            $data[$key]['coupons'][$cKey]['is_redeemed'] = (isUserLoggedIN($user) && mysql_count("check_ins", "`couponsNum` = {$coupon['num']} AND `membersNum` = {$user['num']}")) ? "1" : "0";

            //Abhishek send global coupon time
            $data[$key]['coupons'][$cKey]['start_date'] = gmdate("Y-m-d H:i:s", strtotime($coupon['start_date'] . " " . $listing['timezone']));
            $data[$key]['coupons'][$cKey]['end_date'] = gmdate("Y-m-d H:i:s", strtotime($coupon['end_date'] . " " . $listing['timezone']));
          }
        } else {
          $data[$key]['coupons'][0]['isDefaultCoupon'] = "1";
          $data[$key]['coupons'][0]['name'] = $shareTexts['coupon_name'];
          $data[$key]['coupons'][0]['content'] = $shareTexts['coupon_description'];
          $imageFiles = getUploadRecords('share_texts', 'coupon_image', '1');
          $data[$key]['coupons'][0]['image'] = '';
          foreach ($imageFiles as $file) {
            $data[$key]['coupons'][0]['image'] = $file['urlPath'];
          }
        }

        $data[$key]['coupons_count'] = mysql_count('coupons', "`listingsNum` = {$listing['num']}");

        //Abhishek : add latest foodie experience members
        $membersNums = array();
        $latest_foodies = mysql_select('foodie_experience', "`listingsNum` = " . intval($listing['num']) . " ORDER BY `createdDate` DESC LIMIT 0,3", "`membersNum`");

        foreach ($latest_foodies as $check_in) {
          array_push($membersNums, $check_in['membersNum']);
        }

        $data[$key]['latest_foodie_members'] = [];
        $i = 0;
        foreach ($membersNums as $memberKey => $membersNum) {
          $member = mysql_get('members', $membersNum, null, "`facebook_picture`");
          if ($member) {
            $data[$key]['latest_foodie_members'][$i]['facebook_picture'] = $member['facebook_picture'];
            $i++;
          }
        }
        // sort halal_items
        if ($listing['halal_items']) {
          $halalItems = explode("\t", $listing['halal_items']);
          // $halalItems = array_reverse($halalItems);
          $data[$key]['halal_items'] = implode("\t", $halalItems);
        }

        //Abhishek change start and end datetime to date of festivcal listings
        if ($listing['type'] == "Festivals") {
          $data[$key]['start_date'] = date("Y-m-d", strtotime($listing['start_date']));
          $data[$key]['end_date'] = date("Y-m-d", strtotime($listing['end_date']));
        }

        //Abhishek: Check if the user is following the listing.
        $data[$key]['member_following_listing'] = '0';
        if (isUserLoggedIN($user) && $listings_follows_num = mysql_get('listings_follows', null, "`membersNum` = {$user['num']} AND `listingsNum` = {$listing['num']}", "`num`")) {

          $data[$key]['member_following_listing'] = '1';

          $data[$key]['listings_follows_num'] = $listings_follows_num['num'];
        }

        //Check if the user has reviewed the listings, add the review if they have.
        $data[$key]['is_first_review_given'] = "0";
        if (isUserLoggedIN($user) && mysql_count('reviews', "`flagged` = 0 AND `membersNum` = {$user['num']} AND `listingsNum` = {$listing['num']}")) {
          $data[$key]['is_first_review_given'] = "1";
        }

        //Abhishek Check if user has given rating for this listing
        $data[$key]['is_rated'] = (isUserLoggedIN($user) && mysql_count('ratings', "`membersNum` = {$user['num']} AND `listingsNum` = {$listing['num']}")) ? "1" : "0";

        //Abhishek Check if user has given experience for this listing
        $data[$key]['is_foodie_exp'] = (isUserLoggedIN($user) && mysql_count('foodie_experience', "`membersNum` = {$user['num']} AND `listingsNum` = {$listing['num']}")) ? "1" : "0";
        //
        $data[$key]['latest_certificates'] = getListingCerts($listing['num'], $user['num'], $shareTexts['cert_text'], $listing['name']);

        $data[$key]['certificates_count'] = strval(mysql_count('certs_uploads', "`listingsNum` = " . intval($listing['num'])));

        if ($_REQUEST['listings.api_type'] == 'web' || $_REQUEST['api_type'] == 'web') {
          addListingData($data, $key);
        }

      } else {
        $data[$key]['latest_photos'] = $latest_photos;
        // sort halal_items and send 3
        if ($listing['halal_items']) {
          $halalItems = array_filter(explode("\t", $listing['halal_items']));
          // $halalItems = array_reverse($halalItems);
          $halalItems = implode("\t", array_slice($halalItems, -3, 3));

          $data[$key]['halal_items'] = "\t" . $halalItems . "\t";
        }

        $data[$key]['coupons'] = [];
        $data[$key]['coupons_count'] = mysql_count('coupons', "`listingsNum` = {$listing['num']}");
      }
      //

      $data[$key]['short_url'] = $GLOBALS['SETTINGS']['shortUrl'] . $listing['permalink'];

      $data[$key]['share_text'] = $shareTexts['listing_text'];

      // Abhishek: adding pictures of members who liked recent listing's photo
      $data[$key]['latest_member_pictures'] = [];
      $data[$key]['likes_count'] = "0";
      if (count($latest_photos) > 0) {

        $photoLikes = mysql_select('photo_likes', "`photo_uploadsNum` = " . intval($latest_photos[0]['num']) . " ORDER BY `createdDate` DESC LIMIT 0,3", "`membersNum`");

        $i = 0;
        foreach ($photoLikes as $photoLike) {
          $member = mysql_get('members', $photoLike['membersNum'], null, "`facebook_picture`");
          if ($member) {
            $data[$key]['latest_member_pictures'][$i]['facebook_picture'] = $member['facebook_picture'];
            $i++;
          }
        }

        $data[$key]['likes_count'] = strval(mysql_count('photo_likes', "`photo_uploadsNum` = " . intval($latest_photos[0]['num'])));
      }//

      // Abhishek send menu data for single listing webpage
      if ($_REQUEST['listings.api_type'] == 'web' || $_REQUEST['api_type'] == 'web') {
        $orderSettings = mysql_get("order_settings", 1, null, "`offer_text`");
        $stripeListing = getListingDeliveryFeeSetup($listing['num']);
        $data[$key]['offer_text'] = $stripeListing['offer_text'] ? $stripeListing['offer_text'] : $orderSettings['offer_text'];

        $data[$key]['products'] = [];
        $data[$key]['order_menu_categories'] = mysql_select_query("SELECT `cmsb_menu_categories`.num, UPPER(category_name) as category_name FROM cmsb_menu_categories INNER JOIN cmsb_menu ON `cmsb_menu`.category = `cmsb_menu_categories`.num WHERE `cmsb_menu`.listingsNum = {$listing['num']} AND `cmsb_menu`.enable_order = 1 GROUP BY `cmsb_menu_categories`.num ORDER BY `cmsb_menu_categories`.dragSortOrder DESC");
        if (count($data[$key]['order_menu_categories']) > 0) {
          $products = mysql_select("menu", "`listingsNum` = {$listing['num']} AND category = {$data[$key]['order_menu_categories'][0]['num']} AND enable_order = 1 ORDER BY name");

          $data[$key]['products'] = processProductData($products);
          $data[$key]['productsCount'] = mysql_count("menu", "`listingsNum` = {$listing['num']} AND category = {$data[$key]['order_menu_categories'][0]['num']} AND enable_order = 1");
        }
      }

    }

    //Abhishek: check if user has earned invite user badge
    if (isUserLoggedIN($user)) {
      $user['invite_user_badge'] = '0';
      $badge = mysql_get("badges", null, "`badge_type` = 'CONNOISSUER'", "`num`");
      if ($badge) {
        $badgeEarned = mysql_count('user_badges', "`membersNum` = " . intval($user['num']) . " AND `badgesNum` = " . intval($badge['num']));
        $user['invite_user_badge'] = $badgeEarned ? '1' : '0';
      }
    }
  }
  if (isset($_REQUEST['get-products-for-order']) || isset($_REQUEST['get-recent-ordered-items']) || isset($_REQUEST['menu-items-search'])) {

    $data = processProductData($data);

  }
  if (isset($_REQUEST['get-products-by-listing-for-order'])) {
    // $timeFields    = array('monday_open', 'monday_close', 'tuesday_open', 'tuesday_close', 'wednesday_open', 'wednesday_close', 'thursday_open', 'thursday_close', 'friday_open', 'friday_close', 'saturday_open', 'saturday_close', 'sunday_open', 'sunday_close'); 
    // $readableTimes = getListOptions('listings', 'monday_open');
    foreach ($data as $key => $listing) {

      //Add the opening and closing time for the listing.
      $data[$key] = api_addOpenCloseDetailsToListing($listing);
      $listingClosed = true;
      if (isset($_REQUEST['order_enabled'])) {
        $data[$key]['restaurant_status'] = 'closed';
        $batchScreen = true;
        if ($_REQUEST['order_enabled']) {
          $data[$key]['restaurant_status'] = 'open';
          $listingClosed = false;
        }

      } elseif (!$listing['is_online'] || $data[$key]['restaurant_status'] === "closing_soon") {
        $data[$key]['restaurant_status'] = 'closed';
      }

      $data[$key]['compliance'] = '';
      $data[$key]['coupons'] = [];

      $data[$key]['cuisine'] = startsWith("\t", $data[$key]['cuisine']) ? $data[$key]['cuisine'] : "\t" . $data[$key]['cuisine'] . "\t";

      //Abhishek: convert cuisines to uppercase
      $data[$key]['cuisine'] = implode("\t", array_map(function ($v) {
        return strtoupper($v); }, explode("\t", $data[$key]['cuisine'])));

      $data[$key]['short_url'] = $GLOBALS['SETTINGS']['shortUrl'] . $listing['permalink'];
      $data[$key]['share_text'] = $shareTexts['listing_text'];

      $orderSettings = mysql_get("order_settings", 1, null, "`offer_text`");

      $stripeListing = getListingDeliveryFeeSetup($listing['num']);

      $data[$key]['offer_text'] = $stripeListing['offer_text'] ? $stripeListing['offer_text'] : $orderSettings['offer_text'];


      // set time fields for listing
      getListingReadableTime($data[$key]);

      //Abhishek get menu categories
      $data[$key]['menu_categories'] = mysql_select_query("SELECT `cmsb_menu_categories`.num, UPPER(category_name) as category_name FROM cmsb_menu_categories INNER JOIN cmsb_menu ON `cmsb_menu`.category = `cmsb_menu_categories`.num WHERE `cmsb_menu`.listingsNum = {$listing['num']} GROUP BY `cmsb_menu_categories`.num ORDER BY `cmsb_menu_categories`.dragSortOrder DESC");

      $data[$key]['is_ramadan'] = "0";
      foreach ($data[$key]['menu_categories'] as $catKey => $catVal) {

        $data[$key]['menu_categories'][$catKey]['filter_image'] = [
          "normal" => $GLOBALS['SETTINGS']['s3AssetsLink'] . "filter-images/" . str_replace(" ", "_", strtolower($catVal['category_name'])) . "_normal.png",
          "selected" => $GLOBALS['SETTINGS']['s3AssetsLink'] . "filter-images/" . str_replace(" ", "_", strtolower($catVal['category_name'])) . "_selected.png"
        ];

        if ($catVal['category_name'] === "RAMADAN") {
          $data[$key]['is_ramadan'] = "1";
        }

      }

      // sort halal_items
      if ($listing['halal_items']) {
        $halalItems = explode("\t", $listing['halal_items']);
        // $halalItems = array_reverse($halalItems);
        $data[$key]['halal_items'] = implode("\t", $halalItems);
      }

      $data[$key]['products'] = processProductData($listing['products'], $listingClosed, $batchScreen);

      // Abhishek : setting key for photos data. Needed on app side
      $latest_photos = mysql_select('photo_uploads', "`listingsNum` = " . intval($listing['num']) . " AND `for_photo` = 'photo' AND `flagged` = 0 ORDER BY `createdDate` DESC LIMIT 0,1", "`num`, `membersNum`, `tag_ids`, `listingsNum`, `views`, `permalink`");

      foreach ($latest_photos as $photoKey => $photo) {
        $latest_photos[$photoKey]['photos'] = getUploadRecords('photo_uploads', 'photos', $photo['num']);
      }
      $data[$key]['urban_data_photo'] = $latest_photos;

      $data[$key]['latest_certificates'] = getListingCerts($listing['num'], $user['num'], $shareTexts['cert_text'], $listing['name']);

      list($latestOrdersMembersText, $ordersCount) = getListinglatestOrdersCountAndText($listing['num']);
      $data[$key]["latest_orders_members"] = $latestOrdersMembersText;
      $data[$key]['orders_count'] = $ordersCount;

    }

  }
  //Add member details for photophoto_likes
  if (isset($_REQUEST['read']) && @$_REQUEST['_section'] == 'photo_likes') {
    // print_r($data);
    foreach ($data as $key => $photoLike) {

      if ($photoLike['photo_uploadsNum']) {
        if (mysql_count('photo_uploads', "`num` = {$photoLike['photo_uploadsNum']}")) {
          $data[$key]['photo_uploads'] = mysql_get('photo_uploads', $photoLike['photo_uploadsNum']);
        }
      }
    }
  }


  if ((@$_REQUEST['_section'] == 'reviews' && isset($_REQUEST['read']))) {
    $friends = array();
    $foodies = array();

    foreach ($data as $key => $review) {
      if ($review['listingsNum'] && isUserLoggedIN($user)) {
        if (mysql_count('ratings', "`membersNum` = {$user['num']} AND `listingsNum` = {$review['listingsNum']}")) {
          $data[$key]['rating_by_user'] = mysql_get('ratings', null, "`membersNum` = {$user['num']} AND `listingsNum` = {$review['listingsNum']} ORDER BY `createdDate` DESC");
        }
      }
      //Abhishek: check if logged in member is following current loop member
      $data[$key]['is_following'] = '0';
      if (isUserLoggedIN($user) && mysql_count('user_follows', "`membersNum` = '" . $user['num'] . "' AND `followingNum` = " . $data[$key]['membersNum'])) {
        $data[$key]['is_following'] = '1';
        array_push($friends, $data[$key]['membersNum']);
      }
      $data[$key]['is_follower'] = '0';
      if (isUserLoggedIN($user) && mysql_count('user_follows', "`membersNum` = '" . $data[$key]['membersNum'] . "' AND `followingNum` = " . $user['num'])) {
        $data[$key]['is_follower'] = '1';
        array_push($friends, $data[$key]['membersNum']);
      }
      if ($data[$key]['is_following'] == '0' && $data[$key]['is_follower'] == '0' && @$user['num'] != $data[$key]['membersNum']) {
        array_push($foodies, $data[$key]['membersNum']);
      }
      $data[$key]['_action_date'] = $data[$key]['createdDate'];
      $data[$key]['short_url'] = $GLOBALS['SETTINGS']['shortUrl'] . $review['permalink'];
      $data[$key]['share_text'] = $shareTexts['tip_text'];
    }
    //Abhishek: Added (friendsTotalRecords, foodiesTotalRecords, mineTotalRecords) params in meta data for pagination
    if (isset($_REQUEST['reviews.listingsNum'])) {

      $meta['friendsTotalRecords'] = "0";
      $meta['foodiesTotalRecords'] = "0";
      $meta['mineTotalRecords'] = "0";

      if (isUserLoggedIN($user) && count($data) > 0) {
        $meta['mineTotalRecords'] = strval(mysql_count('reviews', "`flagged` = 0 AND `membersNum` = {$user['num']} AND `listingsNum` = {$data[$key]['listingsNum']}"));
      }

      if (count($friends) > 0) {
        $meta['friendsTotalRecords'] = strval(mysql_count('reviews', "`flagged` = 0 AND `membersNum` IN (" . implode(",", $friends) . ") AND `listingsNum` = {$data[$key]['listingsNum']}"));
      }

      if (count($foodies) > 0) {
        $meta['foodiesTotalRecords'] = strval(mysql_count('reviews', "`flagged` = 0 AND `membersNum` IN (" . implode(",", $foodies) . ") AND `listingsNum` = {$data[$key]['listingsNum']}"));
      }
    }
  }
  if ((@$_REQUEST['_section'] == 'members' && isset($_REQUEST['read']))) {



    if (isUserLoggedIN($user)) {
      api_updateUsersPoints($user);
      $user = mysql_get('members', $user['num']);
      urbcan_updateMember($user, $user['rank'], false);
    }

    foreach ($data as $key => $member) {
      if ($member['num']) {

        //Abhishek;  load records from 'photo_uploads'
        if (!isset($_REQUEST['_api'])) {

          list($photos, $photosMeta) = getRecords(array(
            'tableName' => 'photo_uploads',
            'where' => "`membersNum` = {$member['num']} AND `flagged` = 0",
            'loadUploads' => true,
            'loadCreatedBy' => false,
            'allowSearch' => false,
            'orderBy' => "`createdDate` DESC",
            'limit' => "3"
          ));
          $photos = addMemberPhotoLikesToPhotoUp($photos, 'photo_likes');
          $photos = api_formatData($photos);
          // ABhishek: Adding member detail who uploaded photo in photo array
          foreach ($photos as $photoKey => $photo) {
            $mem = mysql_get('members', null, "`num` = " . intval($photo['membersNum']), '`facebook_picture`,`facebook_first_name`,`facebook_last_name`,`username`,`num`,`isAdmin`');

            $photos[$photoKey]['members'] = null;
            if ($mem) {

              $photos[$photoKey]['members'] = $mem;
            }

            $listing = mysql_get('listings', $photo['listingsNum'], null, '`name`,`num`');
            // echo"<pre>";print_r($listing);echo"</pre>";
            if ($listing) {
              $photos[$photoKey]['listings']['name'] = $listing['name'];
              $photos[$photoKey]['listings']['num'] = strval($listing['num']);
            }

            // check if photo liked

            $photos[$photoKey]['is_liked'] = "0";
            $photos[$photoKey]['like_type'] = "";

            if (isUserLoggedIN($user)) {
              $photoLiked = mysql_get('photo_likes', null, "`membersNum` = '" . intval($user['num']) . "' AND `photo_uploadsNum` = " . intval($photos[$photoKey]['num']), "`like_type`");
              if ($photoLiked) {
                $photos[$photoKey]['is_liked'] = "1";
                $photos[$photoKey]['like_type'] = $photoLiked['like_type'];
              }
            }

            $photos[$photoKey]['short_url'] = $GLOBALS['SETTINGS']['shortUrl'] . $photos[$photoKey]['permalink'];
            $photos[$photoKey]['share_text'] = $shareTexts['moment_text'];

            $photos[$photoKey]['tags'] = addPhotoTags($photos, $photoKey);

            $photos[$photoKey]['views'] = $photos[$photoKey]['views'] ? $photos[$photoKey]['views'] : "0";
          }//
          // Abhishek : setting key for photos data. Needed on app side
          if (isset($_REQUEST['api_type'])) {
            $data[$key]['urban_data_photo'] = $photos;
          } else {
            $data[$key]['photo_uploads'] = $photos;
          }

          //Abhishek: check if user has earned invite user badge
          if (isUserLoggedIN($user)) {
            $user['invite_user_badge'] = '0';
            $badge = mysql_get("badges", null, "`badge_type` = 'CONNOISSUER'", "`num`");
            if ($badge) {
              $badgeEarned = mysql_count('user_badges', "`membersNum` = " . intval($user['num']) . " AND `badgesNum` = " . intval($badge['num']));
              $user['invite_user_badge'] = $badgeEarned ? '1' : '0';
            }
          }
        }

        //Abhishek: check if logged in member is following current loop member
        $data[$key]['is_following'] = '0';
        if (isUserLoggedIN($user) && $user_follows_num = mysql_get('user_follows', null, "`membersNum` = '" . intval($user['num']) . "' AND `followingNum` = " . $member['num'], '`num`')) {
          $data[$key]['is_following'] = '1';

          $data[$key]['user_follows_num'] = $user_follows_num['num'];
        }

      }
    }

  }

  if ((@$_REQUEST['_section'] == 'photo_uploads' && isset($_REQUEST['read']))) {
    $data = addMemberPhotoLikesToPhotoUp($data, 'photo_likes');
    foreach ($data as $key => $upload) {
      // add if logged in user liked photo

      $data[$key]['is_liked'] = "0";
      $data[$key]['like_type'] = "";
      if (isUserLoggedIN($user)) {
        $photoLiked = mysql_get('photo_likes', null, "`membersNum` = '" . intval($user['num']) . "' AND `photo_uploadsNum` = " . intval($data[$key]['photos'][0]['recordNum']), "`like_type`");
        if ($photoLiked) {
          $data[$key]['is_liked'] = "1";
          $data[$key]['like_type'] = $photoLiked['like_type'];
        }
      }

      $data[$key]['short_url'] = $GLOBALS['SETTINGS']['shortUrl'] . $data[$key]['permalink'];
      $data[$key]['share_text'] = $shareTexts['moment_text'];

      $data[$key]['tags'] = addPhotoTags($data, $key);

      $data[$key]['views'] = $data[$key]['views'] ? $data[$key]['views'] : "0";

      $uploadUser = mysql_get('members', $data[$key]['membersNum'], null, "`isAdmin`");
      $data[$key]['members.isAdmin'] = $uploadUser['isAdmin'];
      if ($uploadUser['isAdmin']) {
        $data[$key]['members.facebook_first_name'] = $data[$key]['listings.name'];
        $data[$key]['members.facebook_last_name'] = '';
        $data[$key]['members.facebook_picture'] = $data[$key]['photos'][0]['thumbUrlPath3'];
        $data[$key]['members.username'] = $data[$key]['listings.name'];
        $data[$key]['members.num'] = $data[$key]['listings.num'];
        $data[$key]['share_text'] = $shareTexts['admin_moment_text'];
      }
    }
  }

  //If the user is unfollowing a check-in, listing, photo, or user, ensure the conrispoinding record is deleted from the feed.
  if (isset($_REQUEST['delete']) && (in_array(@$_REQUEST['_section'], ['check_ins', 'listings_follows', 'photo_likes', 'user_follows', 'photo_uploads', 'cert_photo_likes']))) {
    //Delete the related feed record.
    mysql_delete('feed', null, mysql_escapef("`section` = ? AND `recordNum` = ? ", $_REQUEST['_section'], intval($_REQUEST['num'])));
    if (in_array(@$_REQUEST['_section'], ['photo_likes', 'user_follow', 'video_likes', 'cert_photo_likes', 'faces_likes'])) {
      api_updateUsersPoints($user);
      $user = mysql_get('members', $user['num']);
      urbcan_updateMember($user, $user['rank'], false);
    }
  }

  // Abhishek: add is_earned param for badges
  if (isset($_REQUEST['read']) && @$_REQUEST['_section'] == 'badges') {

    $member = mysql_get('members', $_REQUEST['membersNum'], null, "`num`");

    foreach ($data as $key => $value) {

      $data[$key]['is_earned'] = "0";
      if ($member && mysql_count('user_badges', "`membersNum` = {$member['num']} AND `badgesNum` = {$value['num']}")) {
        $data[$key]['is_earned'] = "1";
      }

      if ($value['badge_type'] == "CONNOISSUER")
        $data[$key]['completed_image'] = $data[$key]['completed_image'];

      if (count($data[$key]['gif_badge']) <= 0)
        $data[$key]['gif_badge'] = [];
    }
  }

  //Abhishek: Add points for a foodie_experience
  if (isset($_REQUEST['create']) && @$_REQUEST['_section'] == 'foodie_experience') {
    mysql_update('foodie_experience', $data['num'], null, array('points' => $pointSettings['foodie_experience']));
    api_updateUsersPoints($user);
    $user = mysql_get('members', $user['num']);
    urbcan_updateMember($user, $user['rank'], false);
    $successMessage = str_replace("<pointvalue>", intval($pointSettings['foodie_experience']), $pointSettings['foodie_experience_alert']);
    $success .= $successMessage . "\r\n";
    $total_experiences = mysql_count('foodie_experience', "`listingsNum` = " . intval($data['listingsNum']));
    mysql_update('listings', intval($data['listingsNum']), null, array("total_foodie_experience" => $total_experiences));

    updateListingAvgFoodieExperirence($data['listingsNum']);
  }

  if (isset($_REQUEST['save_tag'])) {
    mysql_update('members', $user['num'], null, array("tags" => intval($user['tags']) + count($data['tag_ids'])));
    $user['tags'] = intval($user['tags']) + count($data['tag_ids']);
    api_updateUsersPoints($user);
    $user = mysql_get('members', $user['num']);
    urbcan_updateMember($user, $user['rank'], false);
    $successMessage = str_replace("<pointvalue>", count($data['tag_ids']) * intval($pointSettings['tags']), $pointSettings['tags_alert']);
    $success .= $successMessage . "\r\n";
  }

  //Abhishek counter views for photo
  if (isset($_REQUEST['create']) && @$_REQUEST['_section'] == 'photo_views') {
    $views = mysql_count('photo_views', "`photo_uploadsNum` = " . intval($data['photo_uploadsNum']));
    mysql_update('photo_uploads', intval($data['photo_uploadsNum']), null, array('views' => $views));
  }

  //Abhishek counter views for listing
  if (isset($_REQUEST['create']) && @$_REQUEST['_section'] == 'listing_views') {
    $views = mysql_count('listing_views', "`listingsNum` = " . intval($data['listingsNum']));
    mysql_update('listings', intval($data['listingsNum']), null, array('views' => $views));
  }

  //Abhishek counter views for profile
  if (isset($_REQUEST['create']) && @$_REQUEST['_section'] == 'profile_views') {
    $views = mysql_count('profile_views', "`viewerNum` = " . intval($data['viewerNum']));
    mysql_update('members', intval($data['viewerNum']), null, array('views' => $views));
  }

  //Abhishek counter views for video
  if (isset($_REQUEST['create']) && @$_REQUEST['_section'] == 'stories_views') {
    $views = mysql_count('stories_views', "`videosNum` = " . intval($data['videosNum']));
    mysql_update('videos', intval($data['videosNum']), null, array('views' => $views));
  }

  //Abhishek get listings_follows photos
  if (isset($_REQUEST['read']) && @$_REQUEST['_section'] == 'listings_follows') {
    foreach ($data as $key => $row) {

      $data[$key]['listings.recent_photos'][0]['photos'] = $data[$key]['listings.recent_photos'] ? [$data[$key]['listings.recent_photos'][0]] : [];

      $data[$key]['_action_date'] = $data[$key]['createdDate'];

      $data[$key]['is_following'] = "0";
      if (isUserLoggedIN($user) && mysql_count('listings_follows', "`membersNum` = '" . intval($user['num']) . "' AND `listingsNum` = " . $data[$key]['listingsNum'])) {
        $data[$key]['is_following'] = "1";
      }
    }
  }

  //Abhishek get listing reviews photos
  if (isset($_REQUEST['read']) && @$_REQUEST['_section'] == 'reviews') {
    foreach ($data as $key => $row) {

      $data[$key]['listings.recent_photos'][0]['photos'] = $data[$key]['listings.recent_photos'] ? [$data[$key]['listings.recent_photos'][0]] : [];

      $data[$key]['_action_date'] = $data[$key]['createdDate'];
    }
  }

  //Abhishek get listing checkin photos
  if (isset($_REQUEST['read']) && @$_REQUEST['_section'] == 'check_ins') {

    foreach ($data as $key => $row) {

      $data[$key]['listings.recent_photos'][0]['photos'] = $data[$key]['listings.recent_photos'] ? [$data[$key]['listings.recent_photos'][0]] : [];
      $listing = mysql_get('listings', $data[$key]['listingsNum'], null, "`timezone`,`monday_open`,`monday_close`,`tuesday_open`,`tuesday_close`,`wednesday_open`,`wednesday_close`,`thursday_open`,`thursday_close`,`friday_open`,`friday_close`,`saturday_open`,`saturday_close`,`sunday_open`,`sunday_close`");
      $listing = api_addOpenCloseDetailsToListing($listing);
      $data[$key]['listings.restaurant_status'] = $listing['restaurant_status'];
      $data[$key]['_action_date'] = $data[$key]['createdDate'];
    }
  }

  //Abhishek get listing checkin photos
  if (isset($_REQUEST['read']) && @$_REQUEST['_section'] == 'user_follows') {

    foreach ($data as $key => $row) {
      $data[$key]['is_following'] = "0";
      if (isUserLoggedIN($user)) {
        if (isset($_REQUEST['user_follows.membersNum'])) {
          $isFollowing = mysql_count('user_follows', "`membersNum` = " . intval($user['num']) . " AND `followingNum` = " . intval($data[$key]['followingNum']));
        } else {
          $isFollowing = mysql_count('user_follows', "`membersNum` = " . intval($user['num']) . " AND `followingNum` = " . intval($data[$key]['membersNum']));
        }
        $data[$key]['is_following'] = $isFollowing ? "1" : "0";
      }
      $data[$key]['_action_date'] = $data[$key]['createdDate'];
    }
  }

  //Abhishek update user
  if (isset($_REQUEST['update']) && @$_REQUEST['_section'] == 'members') {
    $user = mysql_get('members', $user['num']);
  }
  //Abhishek flag photo
  if (isset($_REQUEST['create']) && in_array(@$_REQUEST['_section'], ['flagged_photos', 'flagged_certificates'])) {

    $placeholders = array(
      'photo.num' => $data['recordNum'],
      'member.name' => $user['facebook_first_name'] . " " . $user['facebook_last_name'],
      'member.num' => $user['num'],
      'pageUrl' => realUrl("?menu=" . @$_REQUEST['_section'] . "&action=edit&num={$data['num']}", $GLOBALS['SETTINGS']['adminUrl']),
      'photo.text' => str_replace("_", " a ", @$_REQUEST['_section'])
    );

    // USER-PHOTO-LIKED
    $emailHeaders = emailTemplate_loadFromDB(array(
      'template_id' => 'USER-FLAGGED-PHOTO',
      'placeholders' => $placeholders,
    ));

    $mailErrors = sendMessage($emailHeaders);
    if ($mailErrors) {
      $errorsAndAlerts .= "Mail Error: $mailErrors";
    }
  }

  //Abhishek flag review
  if (isset($_REQUEST['create']) && @$_REQUEST['_section'] == 'flagged_reviews') {

    $review = mysql_get('reviews', $data['recordNum'], null, "`tip_content`");

    mysql_update('flagged_reviews', $data['num'], null, array('tip' => $review['tip_content']));

    $placeholders = array(
      'review.num' => $data['recordNum'],
      'member.name' => $user['facebook_first_name'] . " " . $user['facebook_last_name'],
      'member.num' => $user['num'],
      'pageUrl' => realUrl("?menu=flagged_reviews&action=edit&num={$data['num']}", $GLOBALS['SETTINGS']['adminUrl']),
    );

    // USER-PHOTO-LIKED
    $emailHeaders = emailTemplate_loadFromDB(array(
      'template_id' => 'USER-FLAGGED-REVIEW',
      'placeholders' => $placeholders,
    ));
    $mailErrors = sendMessage($emailHeaders);
    if ($mailErrors) {
      $errorsAndAlerts .= "Mail Error: $mailErrors";
    }
  }

  //Abhishek flag review
  if (isset($_REQUEST['create']) && @$_REQUEST['_section'] == 'flagged_users') {

    $member = mysql_get("members", $data['recordNum'], null, "`num`, `facebook_first_name`, `facebook_last_name`");

    $placeholders = array(
      'flagged.num' => @$member['num'],
      'flagged.name' => @$member['facebook_first_name'] . " " . @$member['facebook_last_name'],
      'member.name' => $user['facebook_first_name'] . " " . $user['facebook_last_name'],
      'member.num' => $user['num'],
      'pageUrl' => realUrl("?menu=flagged_users&action=edit&num={$data['num']}", $GLOBALS['SETTINGS']['adminUrl']),
    );

    // USER-PHOTO-LIKED
    $emailHeaders = emailTemplate_loadFromDB(array(
      'template_id' => 'USER-FLAGGED-USER',
      'placeholders' => $placeholders,
    ));

    $mailErrors = sendMessage($emailHeaders);
    if ($mailErrors) {
      $errorsAndAlerts .= "Mail Error: $mailErrors";
    }
  }
  //Abhishek flag tag
  if (isset($_REQUEST['reportTag']) && @$_REQUEST['_section'] == 'flagged_tags') {
    if ($data['tagIds']) {
      $placeholders = array(
        'tags.num' => $data['tagIds'],
        'member.name' => $user['facebook_first_name'] . " " . $user['facebook_last_name'],
        'member.num' => $user['num'],
        'pageUrl' => realUrl("?menu=flagged_tags", $GLOBALS['SETTINGS']['adminUrl']),
      );

      // USER-PHOTO-LIKED
      $emailHeaders = emailTemplate_loadFromDB(array(
        'template_id' => 'USER-FLAGGED-TAGS',
        'placeholders' => $placeholders,
      ));
      $mailErrors = sendMessage($emailHeaders);
      if ($mailErrors) {
        $errorsAndAlerts .= "Mail Error: $mailErrors";
      }
    }
  }

  // videos_list api Abhishek  Video like
  if (isset($_REQUEST['read']) && @$_REQUEST['_section'] == 'videos') {

    $member = mysql_get('members', 40, null, "`facebook_picture`, `username`, `num`");

    foreach ($data as $key => $video) {

      $data[$key]['is_liked'] = "0";
      $data[$key]['like_type'] = "";

      if (isUserLoggedIN($user)) {
        $videoLiked = mysql_get('video_likes', null, "`membersNum` = {$user['num']} AND videosNum = {$video['num']}", "`like_type`");
        if ($videoLiked) {
          $data[$key]['is_liked'] = "1";
          $data[$key]['like_type'] = $videoLiked['like_type'];
        }
      }

      $data[$key]['members_likes_count'] = strval(mysql_count('video_likes', "`videosNum` = " . intval($data[$key]['num'])));

      $data[$key]['members_likes_photo'] = mysql_select_join('video_likes', 'members', "`videosNum` = " . intval($data[$key]['num']), "membersNum", array('facebook_picture', 'facebook_gender'), 3);

      $data[$key]['views'] = $data[$key]['views'] ? $data[$key]['views'] : "0";

      $data[$key]['username'] = @$member['username'];
      $data[$key]['facebook_picture'] = @$member['facebook_picture'];
      $data[$key]['membersNum'] = @$member['num'];
      $data[$key]['short_url'] = $GLOBALS['SETTINGS']['shortUrl'] . $video['permalink'];
      $data[$key]['share_text'] = $shareTexts['story_text'];
    }
  }

  if (isset($_REQUEST['create']) && @$_REQUEST['_section'] == 'video_likes') {
    mysql_update('video_likes', $data['num'], null, array('points' => $pointSettings['loves_a_story']));
    $user['points'] = strval(intval($user['points']) + 1);
    urbcan_updateMember($user, $user['rank'], false);
    $successMessage = str_replace("<pointvalue>", intval($pointSettings['loves_a_story']), $pointSettings['story_love_alert']);
    $success .= $successMessage . "\r\n";
  }

  if (isset($_REQUEST['update']) && @$_REQUEST['_section'] == 'photo_likes') {

    $photoLikeFields = ['createdDate', 'num', 'flagged', 'like_type', 'membersNum', 'photo_uploadsNum', 'points'];

    $data = array_filter_key($data, $photoLikeFields);

    $data['photo_uploads.photos'] = getUploadRecords('photo_uploads', 'photos', $data['photo_uploadsNum']);

    mysql_update('feed', null, "section = 'photo_likes' AND `recordNum` = " . $data['num'], array('json' => json_encode($data)));
  }

  // if (isset($_REQUEST['signup'])) {

  //   $cleanPermalink = _permalink_generate_formatInputText($user['username']);

  //   $errorsAndAlerts .= permalink_add("p/".$cleanPermalink, 'members', $user['num'], true);

  // }

  // Abhishek :- update current location of user
  if (isset($_REQUEST['create']) && $_REQUEST['_section'] == 'user_routes') {
    mysql_update("members", $data['membersNum'], null, array('latitude' => $data['latitude'], 'longitude' => $data['longitude'], 'lastLoginDate' => date("Y-m-d H:i:s")));
  }

  if (isset($_REQUEST['create']) && @$_REQUEST['_section'] == 'cert_photo_likes') {
    mysql_update('cert_photo_likes', $data['num'], null, array('points' => $pointSettings['like_a_photo']));
    api_updateUsersPoints($user);
    $user = mysql_get('members', $user['num']);
    urbcan_updateMember($user, $user['rank'], false);
    $successMessage = str_replace("<pointvalue>", intval($pointSettings['like_a_photo']), $pointSettings['photo_like_alert']);
    $success .= $successMessage . "\r\n";

    // Updating photo likes
    $likeCount = mysql_count('cert_photo_likes', "`photo_uploadsNum` = '{$data['photo_uploadsNum']}'");
    mysql_update('certs_uploads', $data['photo_uploadsNum'], null, array('likes' => $likeCount));
  }

  if ((@$_REQUEST['_section'] == 'certs_uploads' && isset($_REQUEST['read']))) {
    $data = addMemberPhotoLikesToPhotoUp($data, 'cert_photo_likes');
    foreach ($data as $key => $upload) {
      // add if logged in user liked photo
      $data[$key]['is_liked'] = "0";
      $data[$key]['like_type'] = "";

      if (isUserLoggedIN($user)) {
        $photoLiked = mysql_get('cert_photo_likes', null, "`membersNum` = '" . intval($user['num']) . "' AND `photo_uploadsNum` = " . intval($data[$key]['photos'][0]['recordNum']), "`like_type`");
        if ($photoLiked) {
          $data[$key]['is_liked'] = "1";
          //$data[$key]['like_type'] = $photoLiked['like_type'];
        }
      }

      $data[$key]['short_url'] = $GLOBALS['SETTINGS']['shortUrl'] . $data[$key]['permalink'];
      $data[$key]['share_text'] = $shareTexts['cert_text'];

      $data[$key]['tags'] = "";//addPhotoTags($data, $key);

      $data[$key]['views'] = $data[$key]['views'] ? $data[$key]['views'] : "0";

      // add listings recent photos
      $listing_recent_photos = mysql_select('photo_uploads', "`listingsNum` = " . intval($data[$key]['listings.num']) . " AND `for_photo` = 'photo' AND `flagged` = 0 ORDER BY `createdDate` DESC LIMIT 0,1");
      $listing_photos = [];
      foreach ($listing_recent_photos as $photoKey => $photo) {
        $listing_photos = getUploadRecords('photo_uploads', 'photos', $photo['num']);
      }

      $uploadUser = mysql_get('members', $data[$key]['membersNum'], null, "`isAdmin`");
      $data[$key]['members.isAdmin'] = $uploadUser['isAdmin'];
      if ($uploadUser['isAdmin']) {
        $data[$key]['members.facebook_first_name'] = $data[$key]['listings.name'];
        $data[$key]['members.facebook_last_name'] = '';
        $data[$key]['members.facebook_picture'] = count($listing_photos) ? @$listing_photos[0]['thumbUrlPath3'] : "";
        $data[$key]['members.username'] = $data[$key]['listings.name'];
        $data[$key]['members.num'] = $data[$key]['listings.num'];
      }
    }
  }

  if (isset($_REQUEST['read']) && $_REQUEST['_section'] == "menu") {

    $data = processProductData($data);

  }

  //Abhishek faces_list api
  if (isset($_REQUEST['read']) && @$_REQUEST['_section'] == 'faces') {

    $member = mysql_get('members', 40, null, "`facebook_picture`, `username`, `num`");

    foreach ($data as $key => $face) {

      $data[$key]['is_liked'] = "0";
      $data[$key]['like_type'] = "";

      if (isUserLoggedIN($user)) {
        $faceLiked = mysql_get('faces_likes', null, "`membersNum` = {$user['num']} AND facesNum = {$face['num']}", "`like_type`");
        if ($faceLiked) {
          $data[$key]['is_liked'] = "1";
          $data[$key]['like_type'] = $faceLiked['like_type'];
        }
      }

      $data[$key]['members_likes_count'] = strval(mysql_count('faces_likes', "`facesNum` = " . intval($data[$key]['num'])));

      $data[$key]['members_likes_photo'] = mysql_select_join('faces_likes', 'members', "`facesNum` = " . intval($data[$key]['num']), "membersNum", array('facebook_picture', 'facebook_gender'), 3);

      $data[$key]['views'] = $data[$key]['views'] ? $data[$key]['views'] : "0";

      $data[$key]['username'] = @$member['username'];
      $data[$key]['facebook_picture'] = @$member['facebook_picture'];
      $data[$key]['membersNum'] = @$member['num'];
      $data[$key]['short_url'] = $GLOBALS['SETTINGS']['shortUrl'] . $face['permalink'];
      $data[$key]['share_text'] = $shareTexts['face_text'];
    }
  }

  //Abhishek faces likes
  if (isset($_REQUEST['create']) && @$_REQUEST['_section'] == 'faces_likes') {
    mysql_update('faces_likes', $data['num'], null, array('points' => $pointSettings['loves_a_face']));
    $user['points'] = strval(intval($user['points']) + 1);
    urbcan_updateMember($user, $user['rank'], false);
    $successMessage = str_replace("<pointvalue>", intval($pointSettings['loves_a_face']), $pointSettings['face_love_alert']);
    $success .= $successMessage . "\r\n";
  }

  //Abhishek counter views for face
  if (isset($_REQUEST['create']) && @$_REQUEST['_section'] == 'faces_views') {
    $views = mysql_count('faces_views', "`facesNum` = " . intval($data['facesNum']));
    mysql_update('faces', intval($data['facesNum']), null, array('views' => $views));
  }

  if (isset($_REQUEST['create']) && @$_REQUEST['_section'] == 'listing_votes') {
    $values = $_REQUEST['insertData'];
    if (isset($values['listingsNum'])) {
      list($latestVotesMembersText, $latestVotesMembersImage, $latestVoteCountText) = getListinglatestVotesCountAndText($values['listingsNum'], $values['locationsNum']);
      $data["latest_votes_members"] = $latestVotesMembersText;
      $data['latest_votes_members_image'] = $latestVotesMembersImage;
      $data['latest_votes_count_text'] = $latestVoteCountText;
    }
  }

  //update listing rating.
  if (isset($_REQUEST['update']) && @$_REQUEST['_section'] == 'ratings') {

    $avgRating = updateListingAvgRating($data['listingsNum']);

    $data['average_rating'] = strval($avgRating);

    $data = [$data];

  }

  if (isset($_REQUEST['read']) && @$_REQUEST['_section'] == 'subscriptions') {

    foreach ($data as $key => $subscription) {
      $imageUrl = "";
      foreach ($subscription['imageUrl'] as $imageData) {

        $imageUrl = $imageData['urlPath'];
      }

      $data[$key]['imageUrl'] = $imageUrl;
      $data[$key]['subscription_price'] = "$" . $subscription['subscription_price'];
    }

  }

  if (isset($_REQUEST['read']) && @$_REQUEST['_section'] == 'orders') {
    foreach ($data as $oKey => $order) {
      $orderItems = mysql_select("order_items", "`ordersNum` = {$order['num']}");
      $tableName = getTableName('order_detail');
      $section = $tableName;
      $orderDetail = mysql_get_query("SELECT '$tableName'.delivery_verification_image_url,'$tableName'.postmates_tracking_url FROM '$tableName' INNER JOIN '$tableName' ON '$tableName'.ordersNum = '$tableName'.num WHERE '$tableName'.num = {$order['num']}");
      $orderItemCount = 0;
      foreach ($orderItems as $itemKey => $orderItem) {
        $menuImage = mysql_get("uploads", null, "`tableName` = 'menu' AND `fieldName` = 'photo' AND `recordNum` = {$orderItem['productsNum']}", "`thumbUrlPath`");
        $orderItems[$itemKey]['image_url'] = $menuImage ? $menuImage['thumbUrlPath'] : $GLOBALS['SETTINGS']['s3AssetsLink'] . "default-menu.png";
        $orderItemCount += (int) $orderItem['quantity'];
        $orderItems[$itemKey]['menu_options'] = $orderItem['menu_options'] ? json_decode($orderItem['menu_options'], true) : [];
        $orderItems[$itemKey]['item_price'] = $orderItem['item_price'] > 0 ? $orderItem['item_price'] : "";
      }
      $data[$oKey]['order_items'] = $orderItems;
      $data[$oKey]['total_items'] = $orderItemCount;
      $orderSetting = mysql_get("order_settings", 1, null, "`cancel_order_time`");
      $data[$oKey]['cancel_time'] = date("Y-m-d H:i:s", strtotime($order['createdDate']) + $orderSetting['cancel_order_time']);

      $data[$oKey] = array_merge($data[$oKey], getOrderDetail($order['num']));

      $order['createdDate'] = getOrderStatusTime($order);

      $localTime = utcTimeToLocalTime($order['createdDate'], $order['listings.timezone'], true, 'Y-m-d H:i:s', 'm/d/y @ h:i A');

      if (!empty($order['locationsNum']) && $order['drivethru_order'] && $order['order_status'] == 'otw' && !$orderDetail['postmates_tracking_url']) {
        $d = mysql_get("members", $order['driver'], null, "`username`,`phone_number`,`facebook_picture`");

        $data[$oKey]['postmates_tracking_url'] = $GLOBALS['SETTINGS']['websiteUrl'] . '/map-new.php?driver_id=' . $order['driver'] . '&drivethru_id=' . $order['locationsNum'];
        $data[$oKey]['driver_name'] = $d['username'];
        $data[$oKey]['driver_phone_number'] = $d['phone_number'];
        $data[$oKey]['driver_image_href'] = $d['facebook_picture'];
      }

      $userSubscription = mysql_get("user_subscription", $order['user_subscription_num'], null, "`total_credits`, `assign_credits`, `subscription_type`");

      $data[$oKey]['assign_credits'] = $userSubscription['assign_credits'] ? $userSubscription['assign_credits'] : "0.00";

      $data[$oKey]['total_credits'] = $userSubscription['total_credits'] ? $userSubscription['total_credits'] : "0.00";

      $data[$oKey]['subscription_type'] = $userSubscription['subscription_type'] ? $userSubscription['subscription_type'] : "";

      $data[$oKey]['shipping_partner'] = $GLOBALS['SETTINGS']['shipping_partner']['fedex'] ? $GLOBALS['SETTINGS']['shipping_partner']['fedex'] : "";

      $data[$oKey]['createdDate'] = $localTime;

      $data[$oKey]['order_help_url'] = $GLOBALS['SETTINGS']['websiteUrl'] . "/order-help.php";

      $data[$oKey]['service_tip'] = coalesce($order['service_tip'], "0.00");

      $data[$oKey]['no_of_people'] = coalesce($order['no_of_people'], "0");

      $data[$oKey]['order_type_text'] = getOrderTypeText($order);

      $data[$oKey]['delivery_verification_image'] = (is_null($orderDetail['delivery_verification_image_url']) || empty($orderDetail['delivery_verification_image_url'])) ? '' : $orderDetail['delivery_verification_image_url'];

      $lastOrder = [];
      if ($order['order_status'] == "delivered") {

        $signPhoto = mysql_get_query("SELECT IFNULL(`uploads`.urlPath, '') as urlPath FROM `cmsb_uploads` AS `uploads` WHERE `uploads`.tableName = 'orders' AND `uploads`.fieldName = 'sign_photo' AND `uploads`.recordNum = {$order['num']} LIMIT 1");
        if (!$signPhoto) {
          $lastOrder[0]['urlPath'] = "";
        }
      }

      $data[$oKey]['last_order'] = $lastOrder;

      $data[$oKey]['booking_datetime'] = "";
      if ($order['booking_datetime'] != "0000-00-00 00:00:00") {
        // add 1 and an half hour to booking_datetime because at the time of saving order
        // we are subtracting 1 hour from the first window of selected schedule datetime of user
        // So, if selected schedule datetime is 2020-10-01 09:00 AM - 09:30 AM, then we are saving 2020-10-01 09:00:00 at the time of saving order. But we are to return 10/01 09:30 AM to user
        if ($order['drivethru_order']) {

          $scheduleDatetime = date("m/d h:i A", strtotime($order['drivethru_order_date']));
          //$scheduleDatetime = utcTimeToLocalTime($order['drivethru_order_date'], $order['listings.timezone'], true, 'Y-m-d H:i:s', 'm/d h:i A');

        } else {

          $order['booking_datetime'] = date("Y-m-d H:i:s", strtotime($order['booking_datetime']) + 5400);
          $scheduleDatetime = utcTimeToLocalTime($order['booking_datetime'], $order['listings.timezone'], true, 'Y-m-d H:i:s', 'm/d h:i A');
        }

        $data[$oKey]['booking_datetime'] = $scheduleDatetime;
      }

      $data[$oKey]['listings.average_rating'] = "5";

      // $data[$oKey]["card"] = mysql_select("member_cards", "`num` = {$order['cardsNum']}", "`num`,`card_number`,`card_type`");

      $imageRecords = mysql_select('photo_uploads', "`listingsNum` = {$order['listingsNum']} AND `for_photo` = 'photo' AND `flagged` = 0 ORDER BY `createdDate` DESC LIMIT 0,1", "`num`");
      $data[$oKey]['listings.latest_photos'] = [];
      foreach ($imageRecords as $imgKey => $imageRecord) {
        $imageFiles = getUploadRecords('photo_uploads', 'photos', $imageRecord['num']);
        foreach ($imageFiles as $file) {
          $data[$oKey]['listings.latest_photos'][] = $file;
        }
      }

    }

  }

  return array($user, $data, $meta, $errorsAndAlerts, $success);

}


function getOrderTypeText($order)
{

  if ($order['order_delivery_type'] == "pickup") {
    $orderTypeText = "PICKUP";
    if ($order['drivethru_order']) {
      $orderTypeText = "DRIVETHRU";
    } elseif ($order['dine_in'] && $order['booking_datetime'] != "0000-00-00 00:00:00") {
      $orderTypeText = "SCHEDULED DINE-IN ({$order['no_of_people']})";
    } elseif ($order['dine_in']) {
      $orderTypeText = "DINE-IN ({$order['no_of_people']})";
    } elseif ($order['booking_datetime'] != "0000-00-00 00:00:00") {
      $orderTypeText = "SCHEDULED";
    }
  } else {
    $orderTypeText = "DELIVERY";
    if ($order['booking_datetime'] != "0000-00-00 00:00:00") {
      $orderTypeText = "SCHEDULED";
    } elseif ($order['no_contact_delivery']) {
      $orderTypeText = "NO-CONTACT DELIVERY";
    }
  }
  return $orderTypeText;
}

function getOrderStatusTime($order)
{

  $status = $order['order_status'];
  $orderDetail = mysql_get("order_detail", null, "`ordersNum` = {$order['num']}", "`received_time`, `preparing_time`, `ready_time`, `otw_time`, `delivered_time`, `cancelled_time`");

  if ($orderDetail[$status . '_time']) {
    $order['createdDate'] = $orderDetail[$status . '_time'];
  }

  return $order['createdDate'];

}

function getListinglatestOrdersCountAndText($listingsNum)
{
  $latestOrdersMembers = mysql_select_query("SELECT UPPER(cmsb_members.facebook_first_name) as facebook_first_name FROM cmsb_orders INNER JOIN cmsb_members ON cmsb_orders.membersNum = cmsb_members.num WHERE listingsNum = $listingsNum GROUP BY cmsb_orders.membersNum ORDER BY cmsb_orders.num DESC LIMIT 3");
  $ordersCount = mysql_count("orders", "`listingsNum` = $listingsNum");

  $latestOrdersMembersText = "";
  if (count($latestOrdersMembers) > 0) {

    $latestOrdersMembersText = implode(", ", array_column($latestOrdersMembers, "facebook_first_name"));

    if ($ordersCount > 3) {
      $latestOrdersMembersText .= " + OTHERS ORDERED";
    } else {
      $latestOrdersMembersText .= " ORDERED";
    }
  }

  $ordersCount = strval($ordersCount);

  return [$latestOrdersMembersText, $ordersCount];
}

function getOrderDetail($ordersNum)
{
  $orderDetail = mysql_get("order_detail", null, "`ordersNum` = $ordersNum", "`received_time`, `preparing_time`, `ready_time`, `otw_time`, `delivered_time`, `postmates_tracking_url`, `driver_name`, `driver_phone_number`, `driver_vehicle_type`, `driver_image_href`");
  unset($orderDetail['_tableName']);

  $orderDetail['received_time'] = "";//$orderDetail['received_time'] ? $orderDetail['received_time'] . "M" : "";
  $orderDetail['preparing_time'] = "";//$orderDetail['preparing_time'] ? $orderDetail['preparing_time'] . "M" : "";
  $orderDetail['ready_time'] = "";//$orderDetail['ready_time'] ? $orderDetail['ready_time'] . "M" : "";
  $orderDetail['otw_time'] = "";//$orderDetail['otw_time'] ? $orderDetail['otw_time'] . "M" : "";
  $orderDetail['delivered_time'] = "";//$orderDetail['delivered_time'] ? $orderDetail['delivered_time'] . "M" : "";
  $orderDetail["driver_name"] = coalesce($orderDetail['driver_name'], "");
  $orderDetail["driver_phone_number"] = coalesce($orderDetail['driver_phone_number'], "");
  $orderDetail["driver_vehicle_type"] = coalesce($orderDetail['driver_vehicle_type'], "");
  $orderDetail["driver_image_href"] = coalesce($orderDetail['driver_image_href'], "");
  $orderDetail["postmates_tracking_url"] = coalesce($orderDetail['postmates_tracking_url'], "");
  return $orderDetail;
}

function addMemberPhotoLikesToPhotoUp($records, $tableName)
{
  foreach ($records as $key => $upload) {
    if ($upload['num']) {

      $records[$key]['members_likes_count'] = strval(mysql_count($tableName, " `photo_uploadsNum` =" . intval($upload['num'])));

      $records[$key]['members_likes_photo'] = mysql_select_join($tableName, 'members', "`photo_uploadsNum` = " . intval($upload['num']), "membersNum", array('facebook_picture', 'facebook_gender'), 3);
    }
  }
  return $records;
}

//Abhishek: This function is used to set logged in member data at first index in Leaderboard api
function filterMemberData($data, $user)
{


  foreach ($data as $key => $member) {
    if (intval($member['num']) == intval($_REQUEST['_membersNum'])) {
      $temp = $data[$key];
      unset($data[$key]);
      array_unshift($data, $temp);
    }
  }

  return $data = array_values($data);
}

//Abhishek : get tags for photos by using tag_ids
function addPhotoTags($photos, $photoKey = null)
{
  if (is_null($photoKey))
    $tagIds = @$photos['tag_ids'];
  else
    $tagIds = @$photos[$photoKey]['tag_ids'];

  if ($tagIds) {
    $tags = mysql_select_query("SELECT `name` FROM cmsb_tags WHERE `flagged` = 0 AND num IN ($tagIds) ORDER BY FIND_IN_SET(num, '" . $tagIds . "')", true);

    if ($tags) {
      $tags = array_map(function ($value) {
        return strtoupper($value[0]);
      }, $tags);

      return implode(",", $tags);
    }
  }
  return "";
}

function setUploadedByListing($member, $photos, $key)
{
  $data = array();
  $data['facebook_first_name'] = $photos[$key]['listings']['name'];
  $data['facebook_last_name'] = '';
  $data['facebook_picture'] = $photos[$key]['photos'][0]['thumbUrlPath3'] ? $photos[$key]['photos'][0]['thumbUrlPath3'] : $photos[$key]['photos'][0]['thumbUrlPath'];
  $data['username'] = $photos[$key]['listings']['name'];
  $data['num'] = $photos[$key]['listings']['num'];
  $data['isAdmin'] = $member['isAdmin'];
  return $data;
}

//This function is used to add custom error checking.
function customErrorChecking($user, $schema)
{
  $errorsAndAlerts = "";

  //Check if the user is already following a listing before creation.
  if (isset($_REQUEST['create']) && @$_REQUEST['_section'] == 'listings_follows') {
    $values = $_REQUEST['insertData'];
    if (isset($values['listingsNum']) && mysql_count('listings_follows', "`membersNum` = '" . intval($user['num']) . "' AND `listingsNum` = " . $values['listingsNum'])) {
      $errorsAndAlerts .= "You're already following this listing.\r\n";
    }
  }
  //Check if the user is alredy following a member before creation.
  if (isset($_REQUEST['create']) && @$_REQUEST['_section'] == 'user_follows') {
    $values = $_REQUEST['insertData'];
    if (!@$values['followingNum']) {
      $errorsAndAlerts .= "You must send a value for followingNum";
    } elseif (mysql_count('user_follows', "`membersNum` = '" . intval($user['num']) . "' AND `followingNum` = " . $values['followingNum'])) {
      $errorsAndAlerts .= "You're already following this member.\r\n";
    }
  }
  //Check if the user is alredy following left a rating for this listing.
  if (isset($_REQUEST['create']) && @$_REQUEST['_section'] == 'ratings') {
    $values = $_REQUEST['insertData'];
    if (isset($values['listingsNum']) && mysql_count('ratings', "`membersNum` = '" . intval($user['num']) . "' AND `listingsNum` = " . $values['listingsNum'])) {
      mysql_update('ratings', null, "`membersNum` = '" . intval($user['num']) . "' AND `listingsNum` = " . $values['listingsNum'], array('rating' => $values['rating']));
    }
  }
  //Check if the user is alredy liked this photo.
  if (isset($_REQUEST['create']) && @$_REQUEST['_section'] == 'photo_likes') {
    $values = $_REQUEST['insertData'];
    if (isset($values['photo_uploadsNum']) && mysql_count('photo_likes', "`membersNum` = '" . intval($user['num']) . "' AND `photo_uploadsNum` = " . $values['photo_uploadsNum'])) {
      $errorsAndAlerts .= "You have already liked this photo.\r\n";
    }
  }
  //Check if the user is alredy liked this cert.
  if (isset($_REQUEST['create']) && @$_REQUEST['_section'] == 'cert_photo_likes') {
    $values = $_REQUEST['insertData'];
    if (isset($values['photo_uploadsNum']) && mysql_count('cert_photo_likes', "`membersNum` = '" . intval($user['num']) . "' AND `photo_uploadsNum` = " . $values['photo_uploadsNum'])) {
      $errorsAndAlerts .= "You have already liked this cert.\r\n";
    }
  }
  //Check if the user is alredy following left a rating for this listing.
  if (isset($_REQUEST['create']) && @$_REQUEST['_section'] == 'check_ins') {
    $values = $_REQUEST['insertData'];
    if (isset($values['listingsNum']) && $values['listingsNum']) {
      $lastCheckIn = mysql_get('check_ins', null, mysql_escapef("`membersNum` = ? AND `listingsNum` = ? ORDER BY `createdDate` DESC ", $user['num'], $values['listingsNum']), "`createdDate`");
      if ($lastCheckIn) {
        $currentTime = time();
        if (($currentTime - strtotime($lastCheckIn['createdDate'])) < 60 * 60) {
          $howLongAgo = nicetime($lastCheckIn['createdDate']);
          $errorsAndAlerts .= "Your last check-in was $howLongAgo. You can only check-in every hour.\r\n";
        }
      }
    }
  }

  //Check if the user is alredy following left a rating for this listing.
  if (isset($_REQUEST['update']) && @$_REQUEST['_section'] == 'members' && $user['num'] == $_REQUEST['num']) {
    $values = $_REQUEST['insertData'];

    if (isset($values['facebook_email']) && empty($values['facebook_email'])) {
      $errorsAndAlerts .= "You cannot leave the username field empty.";
    }
    if (isset($values['username']) && empty($values['username'])) {
      $errorsAndAlerts .= "You cannot leave the email field empty.";
    }

    if (@$values['email']) {
      $emailAlreadyInUse = mysql_count(accountsTable(), mysql_escapef("`num` != ?  AND ? IN (`username`, `facebook_email`)", $user['num'], @$values['email']));
      if ($emailAlreadyInUse) {
        $errorsAndAlerts .= "That email address is already in use by another acount!\r\n";
      }
    }
    if (@$values['username']) {
      $usernameAlreadyInUse = mysql_count(accountsTable(), mysql_escapef("`num` != ?  AND ? IN (`username`, `facebook_email`)", $user['num'], @$values['username']));
      if ($emailAlreadyInUse) {
        $errorsAndAlerts .= "That username is already in use on another account!\r\n";
      }
    }
  }

  //Abhishek : Check if the user is alredy viewed this photo.
  // if(isset($_REQUEST['create']) && @$_REQUEST['_section'] == 'photo_views' ){
  //   $values = $_REQUEST['insertData'];
  //   if(isset($values['photo_uploadsNum']) && mysql_count('photo_views', "`membersNum` = '".intval($user['num'])."' AND `photo_uploadsNum` = ".$values['photo_uploadsNum'])){
  //     $errorsAndAlerts .= "You have already viewed this photo.\r\n";
  //   }
  // }

  //Abhishek : Check if the user is alredy viewed this profile.
  // if(isset($_REQUEST['create']) && @$_REQUEST['_section'] == 'profile_views' ){
  //   $values = $_REQUEST['insertData'];
  //   if(isset($values['viewerNum']) && mysql_count('profile_views', "`membersNum` = '".intval($user['num'])."' AND `viewerNum` = ".$values['viewerNum'])){
  //     $errorsAndAlerts .= "You have already viewed this profile.\r\n";
  //   }
  // }

  //Abhishek : Check if the user is alredy viewed this listing.
  // if(isset($_REQUEST['create']) && @$_REQUEST['_section'] == 'listing_views' ){
  //   $values = $_REQUEST['insertData'];
  //   if(isset($values['listingsNum']) && mysql_count('listing_views', "`membersNum` = '".intval($user['num'])."' AND `listingsNum` = ".$values['listingsNum'])){
  //     $errorsAndAlerts .= "You have already viewed this listing.\r\n";
  //   }
  // }

  //Abhishek : Check if the user is alredy viewed this video.
  // if(isset($_REQUEST['create']) && @$_REQUEST['_section'] == 'stories_views' ){
  //   $values = $_REQUEST['insertData'];
  //   if(isset($values['videosNum']) && mysql_count('stories_views', "`membersNum` = '".intval($user['num'])."' AND `videosNum` = ".$values['videosNum'])){
  //     $errorsAndAlerts .= "You have already viewed this video.\r\n";
  //   }
  // }

  //Abhishek : Check if the photo is already flagged.
  if (isset($_REQUEST['create']) && in_array(@$_REQUEST['_section'], ['flagged_photos', 'flagged_certificates'])) {
    $values = $_REQUEST['insertData'];
    if (isset($values['recordNum']) && mysql_count(@$_REQUEST['_section'], "`content_blocked` = 0 AND `recordNum` = " . intval($values['recordNum']))) {
      $errorsAndAlerts .= "This record is already flagged.\r\n";
    }
  }

  //Abhishek : Check if the review is already flagged.
  if (isset($_REQUEST['create']) && @$_REQUEST['_section'] == 'flagged_reviews') {
    $values = $_REQUEST['insertData'];
    if (isset($values['recordNum']) && mysql_count('flagged_reviews', "`content_blocked` = 0 AND `recordNum` = " . intval($values['recordNum']))) {
      $errorsAndAlerts .= "This review has already flagged.\r\n";
    }
  }

  //Abhishek : Check if the user is already flagged.
  if (isset($_REQUEST['create']) && @$_REQUEST['_section'] == 'flagged_users') {
    $values = $_REQUEST['insertData'];
    if (isset($values['recordNum']) && mysql_count('flagged_users', "`content_blocked` = 0 AND `recordNum` = " . intval($values['recordNum']))) {
      $errorsAndAlerts .= "This user has already flagged.\r\n";
    }
  }

  //Check if the user has alredy liked the video.
  if (isset($_REQUEST['create']) && @$_REQUEST['_section'] == 'video_likes') {
    $values = $_REQUEST['insertData'];
    if (isset($values['videosNum']) && mysql_count('video_likes', "`membersNum` = '" . intval($user['num']) . "' AND `videosNum` = " . $values['videosNum'])) {
      $errorsAndAlerts .= "You have already liked this video.\r\n";
    }
  }

  //Return all Errors
  return $errorsAndAlerts;

}

function api_updateUsersPoints($user)
{
  $totalPoints = 0;
  $checkIns = mysql_select('check_ins', "`membersNum` = '" . $user['num'] . "'", "`points`");
  foreach ($checkIns as $checkIn) {
    $totalPoints += intval($checkIn['points']);
  }

  $reviews = mysql_select('reviews', "`flagged` = 0 AND `membersNum` = '" . $user['num'] . "'", "`points`");
  foreach ($reviews as $review) {
    $totalPoints += intval($review['points']);
  }

  $photoUploads = mysql_select('photo_uploads', "`flagged` = 0 AND `membersNum` = '" . $user['num'] . "'", "`points`");
  foreach ($photoUploads as $photoUpload) {
    $totalPoints += intval($photoUpload['points']);
  }

  $photoLikes = mysql_select('photo_likes', "`flagged` = 0 AND `membersNum` = '" . $user['num'] . "'", "`points`");
  foreach ($photoLikes as $photoLike) {
    $totalPoints += intval($photoLike['points']);
  }

  $ratings = mysql_select('ratings', "`membersNum` = '" . $user['num'] . "'", "`points`");
  foreach ($ratings as $rating) {
    $totalPoints += intval($rating['points']);
  }

  $userBadges = mysql_select('user_badges', "`membersNum` = '" . $user['num'] . "'", "`points`");
  foreach ($userBadges as $userBadge) {
    $totalPoints += intval($userBadge['points']);
  }

  $foodie_experiences = mysql_select('foodie_experience', "`membersNum` = '" . $user['num'] . "'", "`points`");
  foreach ($foodie_experiences as $foodie_experience) {
    $totalPoints += intval($foodie_experience['points']);
  }

  $videoLikes = mysql_select('video_likes', "`membersNum` = '" . $user['num'] . "'", "`points`");
  foreach ($videoLikes as $videoLike) {
    $totalPoints += intval($videoLike['points']);
  }

  $photoLikes = mysql_select('cert_photo_likes', "`flagged` = 0 AND `membersNum` = '" . $user['num'] . "'", "`points`");
  foreach ($photoLikes as $photoLike) {
    $totalPoints += intval($photoLike['points']);
  }

  $surveys = mysql_select('order_survey', "`membersNum` = '" . $user['num'] . "'", "`points`");
  foreach ($surveys as $survey) {
    $totalPoints += intval($survey['points']);
  }

  $pointSettings = mysql_get('points_system', '1');
  $phonePoints = mysql_count('pending_invite_messages', "`createdByUserNum` = '" . $user['num'] . "'");
  $totalPoints += $phonePoints * intval($pointSettings['invite_a_friend']);
  $totalPoints += intval($user['tags']) * intval($pointSettings['tags']);
  mysql_update('members', $user['num'], null, array('points' => $totalPoints));

}

function getAmenities($amIds)
{
  $items = ltrim(rtrim(str_replace("\t", ",", $amIds), ','), ',');
  $result = [];
  $query = "SELECT ua.num,ua.name,uu.thumbUrlPath,uu.urlPath FROM cmsb_amenities ua INNER JOIN cmsb_uploads uu ON uu.recordNum = ua.num AND uu.fieldName = 'image' AND uu.tableName = 'amenities' WHERE ua.num IN ('" . $items . "')";
  $data = mysql_select_query($query);

  if (count($data) > 0) {
    $result = $data;
  }
  return $result;
}

function getMenuItemsData($listingsNum, $searchText)
{
  $query = "SELECT GROUP_CONCAT(name)  as menu_items,COUNT(num)  as menu_items_count FROM `cmsb_menu` WHERE name like '" . $searchText . "%' AND listingsNum = " . $listingsNum;
  $data = mysql_select_query($query);

  if ($data[0]['menu_items_count'] == 0) {
    $query = "SELECT GROUP_CONCAT(name) as menu_items,COUNT(num) as menu_items_count FROM `cmsb_menu` WHERE listingsNum = " . $listingsNum;
    $data = mysql_select_query($query);

  }

  $itemsArray = explode(',', $data[0]['menu_items']);
  $limitMenuItems = array_slice($itemsArray, 0, 3);
  $menuItemString = implode(', ', $limitMenuItems);
  $menuItemString = rtrim($menuItemString, ',');
  if ($data[0]['menu_items_count'] != 0) {
    $menuItemString .= " ...";
  }
  return [$menuItemString, $data[0]['menu_items_count']];
}

function changeListingType($enable_order, $type)
{
  if ($enable_order === 1 || $enable_order === '1') {
    $typeArray = [
      'places' => 'Food',
      'market' => 'Meats',
      'brand' => 'Produce',
      'chef' => 'Kitchen',
    ];

    if (array_key_exists(strtolower($type), $typeArray)) {
      $type = $typeArray[strtolower($type)];
    }
  }
  return $type;
}

function api_addOpenCloseDetailsToListing($listing)
{
  $status = "";
  $timeZone = $listing['timezone'];
  date_default_timezone_set($listing['timezone']);
  $currentTime = time();
  $dayOfTheWeek = strtolower(date('l'));
  $listing['listing_day'] = $dayOfTheWeek;

  if ($listing[$dayOfTheWeek . "_open"] == '24hours') {
    $listing['restaurant_status'] = "open";
    $listing['restaurant_closes_in'] = 1040;

    date_default_timezone_set('UTC');
    return $listing;
  }

  $lastDayOfTheWeek = strtolower(date('l', strtotime("-1 day")));

  if (floatval($listing[$lastDayOfTheWeek . "_open"]) > floatval($listing[$lastDayOfTheWeek . "_close"])) {
    $unixOpenTime = api_getEventDate($listing[$lastDayOfTheWeek . "_open"], date("Y-m-d", strtotime("-1 day")));
    $closeTime = $listing[$lastDayOfTheWeek . "_close"];
    $unixCloseTime = api_getEventDate($closeTime, date("Y-m-d"));

    if ($currentTime > $unixCloseTime) {
      $unixOpenTime = api_getEventDate($listing[$dayOfTheWeek . "_open"], date("Y-m-d"));
      $unixCloseTime = api_getEventDate($listing[$dayOfTheWeek . "_close"], date("Y-m-d"));
    }
  } else {
    $unixOpenTime = api_getEventDate($listing[$dayOfTheWeek . "_open"], date("Y-m-d"));
    $unixCloseTime = api_getEventDate($listing[$dayOfTheWeek . "_close"], date("Y-m-d"));
  }

  if (!$unixOpenTime && !$unixCloseTime) {
    $listing['restaurant_status'] = 'closed';
  } elseif (!$unixOpenTime && $unixCloseTime) {
    $listing['restaurant_status'] = ($currentTime < $unixCloseTime) ? 'open' : 'closed';
  } elseif ($unixOpenTime && !$unixCloseTime) {
    $listing['restaurant_status'] = ($currentTime > $unixOpenTime) ? 'open' : 'closed';
  } elseif ($currentTime < $unixOpenTime) {
    $listing['restaurant_status'] = 'open_soon';
  } elseif ($currentTime > $unixCloseTime) {
    $listing['restaurant_status'] = 'closed';
  } else {
    $listing['restaurant_status'] = ($currentTime > $unixOpenTime && $currentTime < $unixCloseTime) ? 'open' : 'closed';
  }

  $listing['restaurant_status'] = ($listing['restaurant_status'] == 'open' && $unixCloseTime - $currentTime < 3600) ? "closing_soon" : $listing['restaurant_status'];
  if ($unixCloseTime && $unixCloseTime > $currentTime) {
    $listing['restaurant_closes_in'] = ceil(($unixCloseTime - $currentTime) / 60);
  }

  date_default_timezone_set('UTC');
  return $listing;

}

function api_getEventDate($opensOrCloses, $date)
{
  // $date     = date('Y-m-d');
  $fullDate = strtotime($date . " " . api_floatToTime($opensOrCloses) . ":00");
  return $fullDate;

}

function api_floatToTime($time)
{
  if (!$time) {
    return "";
  }
  if (endsWith(".5", $time)) {
    $time = str_pad($time, 4, "0", STR_PAD_LEFT);
    $time = str_replace(".5", ":30", $time);
  } elseif (endsWith(".25", $time)) {
    $time = str_pad($time, 5, "0", STR_PAD_LEFT);
    $time = str_replace(".25", ":15", $time);
  } elseif (endsWith(".75", $time)) {
    $time = str_pad($time, 5, "0", STR_PAD_LEFT);
    $time = str_replace(".75", ":45", $time);
  } else {
    $time = str_pad($time, 2, "0", STR_PAD_LEFT);
    $time = $time . ":00";
  }
  return $time;

}

function getPermalink($photoNum, $tableName)
{

  $permalink = mysql_get('_permalinks', null, "tableName = '$tableName' AND recordNum = $photoNum");
  if (count($permalink)) {
    return $GLOBALS['SETTINGS']['shortUrl'] . $permalink['permalink'];
  }
  return "";
}

function formatFeed($jsonData, $user)
{
  $shareTexts = mysql_get('share_texts', '1');
  foreach ($jsonData['urban_data'] as $key => $value) {

    if (isset($jsonData['urban_data'][$key]['listingsNum'])) {

      $jsonData['urban_data'][$key]['listings'] = mysql_get('listings', $jsonData['urban_data'][$key]['listingsNum'], null, "`timezone`,`monday_open`,`monday_close`,`tuesday_open`,`tuesday_close`,`wednesday_open`,`wednesday_close`,`thursday_open`,`thursday_close`,`friday_open`,`friday_close`,`saturday_open`,`saturday_close`,`sunday_open`,`sunday_close`, `latitude`, `longitude`, `address_1`, `name`, `city`,`state`,`zip`, `average_rating`, `checkins`, `cuisine`, `coupons`, `reviews`, `followers`, `num`");
      // add listings recent photos
      $jsonData['urban_data'][$key]['listings']['recent_photos'] = mysql_select('photo_uploads', "`listingsNum` = " . intval($jsonData['urban_data'][$key]['listingsNum']) . " AND `for_photo` = 'photo' AND `flagged` = 0 ORDER BY `createdDate` DESC LIMIT 0,1");
      foreach ($jsonData['urban_data'][$key]['listings']['recent_photos'] as $photoKey => $photo) {
        $jsonData['urban_data'][$key]['listings']['recent_photos'][$photoKey]['photos'] = getUploadRecords('photo_uploads', 'photos', $photo['num']);
      }
      // add listing close time
      $jsonData['urban_data'][$key]['listings'] = api_addOpenCloseDetailsToListing($jsonData['urban_data'][$key]['listings']);
    }

    if (isset($jsonData['urban_data'][$key]['membersNum']) && $jsonData['urban_data'][$key]['membersNum'] == '0') {
      $jsonData['urban_data'][$key]['points'] = '0';
      $jsonData['urban_data'][$key]['members'] = [
        "facebook_picture" => "",
        "facebook_first_name" => "",
        "facebook_last_name" => "",
        "username" => "",
        "num" => "",
        "isAdmin" => "",
        "points" => "0",
        "check_ins" => "",
        "following" => "",
        "followers" => "0",
        "reviews" => "0",
        "_tableName" => "members"
      ];
    } else if (isset($jsonData['urban_data'][$key]['membersNum'])) {
      $jsonData['urban_data'][$key]['members'] = mysql_get('members', $jsonData['urban_data'][$key]['membersNum'], null, "`facebook_picture`, `facebook_first_name`, `facebook_last_name`, `username`, `num`, `isAdmin`, `points`, `check_ins`, `following`, `followers`, `reviews`");
    }


    // change key from following key to user_following
    if ($jsonData['urban_data'][$key]['_section'] == 'user_follows') {
      $jsonData['urban_data'][$key]['is_following'] = "0";
      if (isUserLoggedIN($user) && mysql_count('user_follows', "`membersNum` = " . intval($jsonData['user']['num']) . " AND `followingNum` = " . intval($jsonData['urban_data'][$key]['followingNum']))) {
        $jsonData['urban_data'][$key]['is_following'] = "1";
      }
      $userFollowing = mysql_get("members", $jsonData['urban_data'][$key]['followingNum'], null, "`facebook_picture`");
      if ($userFollowing) {
        $jsonData['urban_data'][$key]['user_following']['facebook_picture'] = $userFollowing['facebook_picture'];
      }
    }

    if ($jsonData['urban_data'][$key]['_section'] == 'listings_follows') {

      // check if logged in user follow listings
      $jsonData['urban_data'][$key]['is_following'] = "0";
      if (isUserLoggedIN($user) && mysql_count('listings_follows', "`membersNum` = '" . intval($jsonData['user']['num']) . "' AND `listingsNum` = " . $jsonData['urban_data'][$key]['listingsNum'])) {
        $jsonData['urban_data'][$key]['is_following'] = "1";
      }
    }

    if ($jsonData['urban_data'][$key]['_section'] == 'photo_likes') {
      // change key from photo_uploads to photos
      $jsonData['urban_data'][$key]['photos'] = $jsonData['urban_data'][$key]['photo_uploads']['photos'];
      unset($jsonData['urban_data'][$key]['photo_uploads']);

      $jsonData['urban_data'][$key]['other_user_like_type'] = $jsonData['urban_data'][$key]['like_type'];
      // add if logged in user liked photo
      $jsonData['urban_data'][$key]['is_liked'] = "0";
      $jsonData['urban_data'][$key]['like_type'] = "";

      if (isUserLoggedIN($user)) {
        $photoLiked = mysql_get('photo_likes', null, "`membersNum` = '" . intval($jsonData['user']['num']) . "' AND `photo_uploadsNum` = " . intval($jsonData['urban_data'][$key]['photo_uploadsNum']), "`like_type`");
        if ($photoLiked) {
          $jsonData['urban_data'][$key]['is_liked'] = "1";
          $jsonData['urban_data'][$key]['like_type'] = $photoLiked['like_type'];
        }
      }

      $jsonData['urban_data'][$key]['members_likes_count'] = strval(mysql_count('photo_likes', "`photo_uploadsNum` = " . intval($jsonData['urban_data'][$key]['photo_uploadsNum'])));

      // add members pics who liked photo
      $jsonData['urban_data'][$key]['members_likes_photo'] = mysql_select_join('photo_likes', 'members', "`photo_uploadsNum` = " . intval($jsonData['urban_data'][$key]['photo_uploadsNum']), "membersNum", array('facebook_picture', 'facebook_gender'), 3);

      $jsonData['urban_data'][$key]['uploaded_by'] = mysql_select_join('photo_uploads', 'members', "cmsb_photo_uploads.`num` = " . intval($jsonData['urban_data'][$key]['photo_uploadsNum']), "membersNum", array('facebook_picture', 'facebook_first_name', 'facebook_last_name', 'num', 'username', 'isAdmin'), 1);

      $photoData = mysql_get('photo_uploads', null, "`num` = " . intval($jsonData['urban_data'][$key]['photo_uploadsNum']));

      $jsonData['urban_data'][$key]['views'] = $photoData['views'] ? $photoData['views'] : "0";

      $jsonData['urban_data'][$key]['tags'] = addPhotoTags($photoData);

      if ($photoData) {
        $listing = mysql_get('listings', $photoData['listingsNum']);
        $jsonData['urban_data'][$key]['listings']['name'] = $listing['name'];
        $jsonData['urban_data'][$key]['listings']['num'] = $listing['num'];

        // add listings recent photos
        $jsonData['urban_data'][$key]['listings']['recent_photos'] = mysql_select('photo_uploads', "`listingsNum` = " . intval($listing['num']) . " AND `for_photo` = 'photo' AND `flagged` = 0 ORDER BY `createdDate` DESC LIMIT 0,1");
        foreach ($jsonData['urban_data'][$key]['listings']['recent_photos'] as $photoKey => $photo) {
          $jsonData['urban_data'][$key]['listings']['recent_photos'][$photoKey]['photos'] = getUploadRecords('photo_uploads', 'photos', $photo['num']);
        }
      }

      $jsonData['urban_data'][$key]['share_text'] = $shareTexts['moment_text'];
      // add listing name to uploaded by if photo uploaded by admin
      if ($jsonData['urban_data'][$key]['uploaded_by'][0]['isAdmin']) {
        $jsonData['urban_data'][$key]['uploaded_by'][0]['facebook_first_name'] = $jsonData['urban_data'][$key]['listings']['name'];
        $jsonData['urban_data'][$key]['uploaded_by'][0]['facebook_last_name'] = '';
        $jsonData['urban_data'][$key]['uploaded_by'][0]['username'] = $jsonData['urban_data'][$key]['listings']['name'];
        $jsonData['urban_data'][$key]['uploaded_by'][0]['num'] = $jsonData['urban_data'][$key]['listings']['num'];
        $jsonData['urban_data'][$key]['uploaded_by'][0]['facebook_picture'] = @$jsonData['urban_data'][$key]['listings']['recent_photos'][0]['photos'][0]['thumbUrlPath3'];
        $jsonData['urban_data'][$key]['share_text'] = $shareTexts['admin_moment_text'];
      }

      // add photo short url
      $jsonData['urban_data'][$key]['short_url'] = @$photoData['permalink'] ? $GLOBALS['SETTINGS']['shortUrl'] . @$photoData['permalink'] : getPermalink($jsonData['urban_data'][$key]['photo_uploadsNum'], 'photo_uploads');

    }

    if ($jsonData['urban_data'][$key]['_section'] == 'photo_uploads') {

      // add if logged in user liked photo
      $jsonData['urban_data'][$key]['is_liked'] = "0";
      $jsonData['urban_data'][$key]['like_type'] = "";

      if (isUserLoggedIN($user)) {
        $photoLiked = mysql_get('photo_likes', null, "`membersNum` = '" . intval($jsonData['user']['num']) . "' AND `photo_uploadsNum` = " . intval($jsonData['urban_data'][$key]['photos'][0]['recordNum']), "`like_type`");
        if ($photoLiked) {
          $jsonData['urban_data'][$key]['is_liked'] = "1";
          $jsonData['urban_data'][$key]['like_type'] = $photoLiked['like_type'];
        }
      }

      // add photo_count of upload_photos by user
      $jsonData['urban_data'][$key]['photo_count'] = strval(mysql_count('photo_uploads', "`flagged` = 0 AND `membersNum` = '" . intval($jsonData['urban_data'][$key]['membersNum']) . "'"));

      $jsonData['urban_data'][$key]['members_likes_count'] = strval(mysql_count('photo_likes', "`photo_uploadsNum` = " . intval($jsonData['urban_data'][$key]['photos'][0]['recordNum'])));

      // add members pics who liked photo
      $jsonData['urban_data'][$key]['members_likes_photo'] = mysql_select_join('photo_likes', 'members', "`photo_uploadsNum` = " . intval($jsonData['urban_data'][$key]['photos'][0]['recordNum']), "membersNum", array('facebook_picture', 'facebook_gender'), 3);

      $jsonData['urban_data'][$key]['tags'] = addPhotoTags($jsonData['urban_data'], $key);

      $photoData = mysql_get('photo_uploads', null, "`num` = " . intval($jsonData['urban_data'][$key]['num']), "`views`");

      $jsonData['urban_data'][$key]['views'] = $photoData['views'] ? $photoData['views'] : "0";

      // add listing name to uploaded by if photo uploaded by admin
      $jsonData['urban_data'][$key]['share_text'] = $shareTexts['moment_text'];
      if ($jsonData['urban_data'][$key]['members']['isAdmin']) {
        $jsonData['urban_data'][$key]['members'] = setUploadedByListing($jsonData['urban_data'][$key]['members'], $jsonData['urban_data'], $key);
        $jsonData['urban_data'][$key]['share_text'] = $shareTexts['admin_moment_text'];
      }

      // add photo short url
      $jsonData['urban_data'][$key]['short_url'] = @$jsonData['urban_data'][$key]['permalink'] ? $GLOBALS['SETTINGS']['shortUrl'] . @$jsonData['urban_data'][$key]['permalink'] : getPermalink($jsonData['urban_data'][$key]['num'], 'photo_uploads');


    }

    // add is_earned badge for logged in user
    if ($jsonData['urban_data'][$key]['_section'] == 'user_badges') {
      $jsonData['urban_data'][$key]['badges'] = mysql_get('badges', $jsonData['urban_data'][$key]['badgesNum'], null, "`badge_name`, `badge_description`, `points`, `badge_type`");

      $jsonData['urban_data'][$key]['is_earned'] = (isUserLoggedIN($user) && mysql_count('user_badges', "`membersNum` = {$jsonData['user']['num']} AND `badgesNum` = {$jsonData['urban_data'][$key]['badgesNum']}")) ? "1" : "0";

      $jsonData['urban_data'][$key]['badges']['completed_image'] = getUploadRecords('badges', 'completed_image', $jsonData['urban_data'][$key]['badgesNum']);
      $jsonData['urban_data'][$key]['badges']['gif_badge'] = getUploadRecords('badges', 'gif_badge', $jsonData['urban_data'][$key]['badgesNum']);

      // if($jsonData['urban_data'][$key]['badges']['badge_type'] == "CONNOISSUER"){          
      //   $jsonData['urban_data'][$key]['badges']['completed_image'] = count($jsonData['urban_data'][$key]['badges']['completed_image']) > 1 ? array_slice($jsonData['urban_data'][$key]['badges']['completed_image'],1) : $jsonData['urban_data'][$key]['badges']['completed_image'];
      // } 
    }

    if ($jsonData['urban_data'][$key]['_section'] == 'cert_photo_likes') {
      // change key from photo_uploads to photos
      $jsonData['urban_data'][$key]['photos'] = $jsonData['urban_data'][$key]['photo_uploads']['photos'];
      unset($jsonData['urban_data'][$key]['photo_uploads']);

      // add if logged in user liked photo
      $jsonData['urban_data'][$key]['other_user_like_type'] = '';//$jsonData['urban_data'][$key]['like_type'];  
      $jsonData['urban_data'][$key]['is_liked'] = "0";
      $jsonData['urban_data'][$key]['like_type'] = "";

      if (isUserLoggedIN($user)) {
        $photoLiked = mysql_get('cert_photo_likes', null, "`membersNum` = '" . intval($jsonData['user']['num']) . "' AND `photo_uploadsNum` = " . intval($jsonData['urban_data'][$key]['photo_uploadsNum']), "`like_type`");
        if ($photoLiked) {
          $jsonData['urban_data'][$key]['is_liked'] = "1";
          //$jsonData['urban_data'][$key]['like_type'] = $photoLiked['like_type'];
        }
      }

      $jsonData['urban_data'][$key]['members_likes_count'] = strval(mysql_count('cert_photo_likes', "`photo_uploadsNum` = " . intval($jsonData['urban_data'][$key]['photo_uploadsNum'])));

      // add members pics who liked photo
      $jsonData['urban_data'][$key]['members_likes_photo'] = mysql_select_join('cert_photo_likes', 'members', "`photo_uploadsNum` = " . intval($jsonData['urban_data'][$key]['photo_uploadsNum']), "membersNum", array('facebook_picture', 'facebook_gender'), 3);

      $jsonData['urban_data'][$key]['uploaded_by'] = mysql_select_join('certs_uploads', 'members', "cmsb_certs_uploads.`num` = " . intval($jsonData['urban_data'][$key]['photo_uploadsNum']), "membersNum", array('facebook_picture', 'facebook_first_name', 'facebook_last_name', 'num', 'username', 'isAdmin'), 1);

      $photoData = mysql_get('certs_uploads', null, "`num` = " . intval($jsonData['urban_data'][$key]['photo_uploadsNum']));

      $jsonData['urban_data'][$key]['views'] = $photoData['views'] ? $photoData['views'] : "0";

      $jsonData['urban_data'][$key]['tags'] = "";//addPhotoTags($photoData);

      if ($photoData) {
        $listing = mysql_get('listings', $photoData['listingsNum']);
        $jsonData['urban_data'][$key]['listings']['name'] = $listing['name'];
        $jsonData['urban_data'][$key]['listings']['num'] = $listing['num'];

        // add listings recent photos
        $jsonData['urban_data'][$key]['listings']['recent_photos'] = mysql_select('photo_uploads', "`listingsNum` = " . intval($listing['num']) . " AND `for_photo` = 'photo' AND `flagged` = 0 ORDER BY `createdDate` DESC LIMIT 0,1");
        foreach ($jsonData['urban_data'][$key]['listings']['recent_photos'] as $photoKey => $photo) {
          $jsonData['urban_data'][$key]['listings']['recent_photos'][$photoKey]['photos'] = getUploadRecords('photo_uploads', 'photos', $photo['num']);
        }
      }
      $jsonData['urban_data'][$key]['share_text'] = $shareTexts['cert_text'];
      // add listing name to uploaded by if photo uploaded by admin
      if ($jsonData['urban_data'][$key]['uploaded_by'][0]['isAdmin']) {
        $jsonData['urban_data'][$key]['uploaded_by'][0]['facebook_first_name'] = $jsonData['urban_data'][$key]['listings']['name'];
        $jsonData['urban_data'][$key]['uploaded_by'][0]['facebook_last_name'] = '';
        $jsonData['urban_data'][$key]['uploaded_by'][0]['username'] = $jsonData['urban_data'][$key]['listings']['name'];
        $jsonData['urban_data'][$key]['uploaded_by'][0]['num'] = $jsonData['urban_data'][$key]['listings']['num'];
        $jsonData['urban_data'][$key]['uploaded_by'][0]['facebook_picture'] = count(@$jsonData['urban_data'][$key]['listings']['recent_photos']) ? @$jsonData['urban_data'][$key]['listings']['recent_photos'][0]['photos'][0]['thumbUrlPath3'] : "";
        $jsonData['urban_data'][$key]['share_text'] = $shareTexts['admin_cert_text'];
      }

      // add photo short url
      $jsonData['urban_data'][$key]['short_url'] = @$photoData['permalink'] ? $GLOBALS['SETTINGS']['shortUrl'] . @$photoData['permalink'] : getPermalink($jsonData['urban_data'][$key]['photo_uploadsNum'], 'certs_uploads');

    }

    //Abhishek: set restaurant status
    if ($jsonData['urban_data'][$key]['_section'] == 'reviews') {
      if (!$jsonData['urban_data'][$key]['permalink']) {
        $review = mysql_get('reviews', $jsonData['urban_data'][$key]['num'], null, "`permalink`");
        $jsonData['urban_data'][$key]['short_url'] = $GLOBALS['SETTINGS']['shortUrl'] . $review['permalink'];
        $jsonData['urban_data'][$key]['share_text'] = $shareTexts['tip_text'];
      }
    }

  }
  return $jsonData['urban_data'];
}

function formatCertFeed($jsonData, $user)
{

  $shareTexts = mysql_get('share_texts', '1');

  foreach ($jsonData['urban_data'] as $key => $value) {

    if (isset($jsonData['urban_data'][$key]['listingsNum'])) {

      $jsonData['urban_data'][$key]['listings'] = mysql_get('listings', $jsonData['urban_data'][$key]['listingsNum'], null, "`latitude`, `longitude`, `address_1`, `name`, `city`, `average_rating`, `checkins`, `cuisine`, `coupons`, `reviews`, `followers`, `num`");
      // add listings recent photos
      $jsonData['urban_data'][$key]['listings']['recent_photos'] = mysql_select('photo_uploads', "`listingsNum` = " . intval($jsonData['urban_data'][$key]['listingsNum']) . " AND `for_photo` = 'photo' AND `flagged` = 0 ORDER BY `createdDate` DESC LIMIT 0,1");
      foreach ($jsonData['urban_data'][$key]['listings']['recent_photos'] as $photoKey => $photo) {
        $jsonData['urban_data'][$key]['listings']['recent_photos'][$photoKey]['photos'] = getUploadRecords('photo_uploads', 'photos', $photo['num']);
      }

    }

    if (isset($jsonData['urban_data'][$key]['membersNum'])) {
      $jsonData['urban_data'][$key]['members'] = mysql_get('members', $jsonData['urban_data'][$key]['membersNum'], null, "`facebook_picture`, `facebook_first_name`, `facebook_last_name`, `username`, `num`, `isAdmin`, `points`, `check_ins`, `following`, `followers`, `reviews`");
    }

    if ($jsonData['urban_data'][$key]['_section'] == 'cert_photo_likes') {
      // change key from photo_uploads to photos
      $jsonData['urban_data'][$key]['photos'] = $jsonData['urban_data'][$key]['photo_uploads']['photos'];
      unset($jsonData['urban_data'][$key]['photo_uploads']);

      // add if logged in user liked photo
      $jsonData['urban_data'][$key]['other_user_like_type'] = '';//$jsonData['urban_data'][$key]['like_type'];  
      $jsonData['urban_data'][$key]['is_liked'] = "0";
      $jsonData['urban_data'][$key]['like_type'] = "";
      if (isUserLoggedIN($user)) {
        $photoLiked = mysql_get('cert_photo_likes', null, "`membersNum` = '" . intval($jsonData['user']['num']) . "' AND `photo_uploadsNum` = " . intval($jsonData['urban_data'][$key]['photo_uploadsNum']), "`like_type`");
        if ($photoLiked) {
          $jsonData['urban_data'][$key]['is_liked'] = "1";
          //$jsonData['urban_data'][$key]['like_type'] = $photoLiked['like_type'];
        }
      }

      $jsonData['urban_data'][$key]['members_likes_count'] = strval(mysql_count('cert_photo_likes', "`photo_uploadsNum` = " . intval($jsonData['urban_data'][$key]['photo_uploadsNum'])));

      // add members pics who liked photo
      $jsonData['urban_data'][$key]['members_likes_photo'] = mysql_select_join('cert_photo_likes', 'members', "`photo_uploadsNum` = " . intval($jsonData['urban_data'][$key]['photo_uploadsNum']), "membersNum", array('facebook_picture', 'facebook_gender'), 3);

      $jsonData['urban_data'][$key]['uploaded_by'] = mysql_select_join('certs_uploads', 'members', "cmsb_certs_uploads.`num` = " . intval($jsonData['urban_data'][$key]['photo_uploadsNum']), "membersNum", array('facebook_picture', 'facebook_first_name', 'facebook_last_name', 'num', 'username', 'isAdmin'), 1);

      $photoData = mysql_get('certs_uploads', null, "`num` = " . intval($jsonData['urban_data'][$key]['photo_uploadsNum']));

      $jsonData['urban_data'][$key]['views'] = $photoData['views'] ? $photoData['views'] : "0";

      $jsonData['urban_data'][$key]['tags'] = "";//addPhotoTags($photoData);

      if ($photoData) {
        $listing = mysql_get('listings', $photoData['listingsNum'], null, "`num`, `name`");
        $jsonData['urban_data'][$key]['listings']['name'] = $listing['name'];
        $jsonData['urban_data'][$key]['listings']['num'] = $listing['num'];

        // add listings recent photos
        $jsonData['urban_data'][$key]['listings']['recent_photos'] = mysql_select('photo_uploads', "`listingsNum` = " . intval($listing['num']) . " AND `for_photo` = 'photo' AND `flagged` = 0 ORDER BY `createdDate` DESC LIMIT 0,1");
        foreach ($jsonData['urban_data'][$key]['listings']['recent_photos'] as $photoKey => $photo) {
          $jsonData['urban_data'][$key]['listings']['recent_photos'][$photoKey]['photos'] = getUploadRecords('photo_uploads', 'photos', $photo['num']);
        }
      }
      $jsonData['urban_data'][$key]['share_text'] = $shareTexts['cert_text'];
      // add listing name to uploaded by if photo uploaded by admin
      if ($jsonData['urban_data'][$key]['uploaded_by'][0]['isAdmin']) {
        $jsonData['urban_data'][$key]['uploaded_by'][0]['facebook_first_name'] = $jsonData['urban_data'][$key]['listings']['name'];
        $jsonData['urban_data'][$key]['uploaded_by'][0]['facebook_last_name'] = '';
        $jsonData['urban_data'][$key]['uploaded_by'][0]['username'] = $jsonData['urban_data'][$key]['listings']['name'];
        $jsonData['urban_data'][$key]['uploaded_by'][0]['num'] = $jsonData['urban_data'][$key]['listings']['num'];
        $jsonData['urban_data'][$key]['uploaded_by'][0]['facebook_picture'] = count(@$jsonData['urban_data'][$key]['listings']['recent_photos']) ? @$jsonData['urban_data'][$key]['listings']['recent_photos'][0]['photos'][0]['thumbUrlPath3'] : "";
        $jsonData['urban_data'][$key]['share_text'] = $shareTexts['admin_cert_text'];
      }

      // add photo short url
      $jsonData['urban_data'][$key]['short_url'] = @$photoData['permalink'] ? $GLOBALS['SETTINGS']['websiteUrl'] . "/" . @$photoData['permalink'] : getPermalink($jsonData['urban_data'][$key]['photo_uploadsNum'], 'certs_uploads');

    }

    if ($jsonData['urban_data'][$key]['_section'] == 'certs_uploads') {

      // add if logged in user liked photo
      $jsonData['urban_data'][$key]['is_liked'] = "0";
      $jsonData['urban_data'][$key]['like_type'] = "";
      if (isUserLoggedIN($user)) {
        $photoLiked = mysql_get('cert_photo_likes', null, "`membersNum` = '" . intval($jsonData['user']['num']) . "' AND `photo_uploadsNum` = " . intval($jsonData['urban_data'][$key]['photos'][0]['recordNum']), "`like_type`");
        if ($photoLiked) {
          $jsonData['urban_data'][$key]['is_liked'] = "1";
          //$jsonData['urban_data'][$key]['like_type'] = $photoLiked['like_type'];
        }
      }

      // add photo_count of upload_photos by user
      $jsonData['urban_data'][$key]['photo_count'] = strval(mysql_count('certs_uploads', "`flagged` = 0 AND `membersNum` = '" . intval($jsonData['urban_data'][$key]['membersNum']) . "'"));

      $jsonData['urban_data'][$key]['members_likes_count'] = strval(mysql_count('cert_photo_likes', "`photo_uploadsNum` = " . intval($jsonData['urban_data'][$key]['photos'][0]['recordNum'])));

      // add members pics who liked photo
      $jsonData['urban_data'][$key]['members_likes_photo'] = mysql_select_join('cert_photo_likes', 'members', "`photo_uploadsNum` = " . intval($jsonData['urban_data'][$key]['photos'][0]['recordNum']), "membersNum", array('facebook_picture', 'facebook_gender'), 3);

      $jsonData['urban_data'][$key]['tags'] = "";//addPhotoTags($jsonData['urban_data'], $key);

      $photoData = mysql_get('certs_uploads', null, "`num` = " . intval($jsonData['urban_data'][$key]['num']), "`views`");

      $jsonData['urban_data'][$key]['views'] = $photoData['views'] ? $photoData['views'] : "0";
      $jsonData['urban_data'][$key]['share_text'] = $shareTexts['cert_text'];
      // add listing name to uploaded by if photo uploaded by admin
      if ($jsonData['urban_data'][$key]['members']['isAdmin']) {
        $jsonData['urban_data'][$key]['members'] = setUploadedByListing($jsonData['urban_data'][$key]['members'], $jsonData['urban_data'], $key);
        $jsonData['urban_data'][$key]['members']['facebook_picture'] = count(@$jsonData['urban_data'][$key]['listings']['recent_photos']) ? @$jsonData['urban_data'][$key]['listings']['recent_photos'][0]['photos'][0]['thumbUrlPath3'] : "";
        $jsonData['urban_data'][$key]['share_text'] = $shareTexts['admin_cert_text'];
      }

      // add photo short url
      $jsonData['urban_data'][$key]['short_url'] = @$jsonData['urban_data'][$key]['permalink'] ? $GLOBALS['SETTINGS']['shortUrl'] . @$jsonData['urban_data'][$key]['permalink'] : getPermalink($jsonData['urban_data'][$key]['num'], 'certs_uploads');

    }
  }
  return $jsonData['urban_data'];
}

function sendFirstRatingReviewEmail($data, $user)
{

  $listing_image = $GLOBALS['listing_img'];

  if (@$data['listingsNum'] && $user['facebook_email']) {

    $listing = mysql_get('listings', @$data['listingsNum'], null, "`average_rating`, `name`");

    $imageRecords = mysql_select('photo_uploads', "`listingsNum` = {$data['listingsNum']} AND `for_photo` = 'photo' AND `flagged` = 0 ORDER BY `createdDate` DESC LIMIT 0,1", "`num`");
    foreach ($imageRecords as $key => $imageRecord) {
      $imageFiles = getUploadRecords('photo_uploads', 'photos', $imageRecord['num']);
      foreach ($imageFiles as $file) {
        $listing_image = $file['thumbUrlPath3'];
      }
    }

    if ($data['_tableName'] === 'ratings') {
      $rating = intval($data['rating']);
      $template_id = 'FIRST-RATING-EMAIL';
      $emailAction = 'ratings,';
    } else {
      $rating = intval($listing['average_rating']);
      $template_id = 'FIRST-TIP-EMAIL';
      $emailAction = 'reviews,';
    }

    $x = 1;
    $html = '';

    for ($x = 1; $x <= $rating; $x++) {
      $html .= '<img style="margin-right: 2px;" src="https://s3-us-west-1.amazonaws.com/urban-halal/email-newsletter/images/rating-small-yellow.png"/>';
    }
    while ($x <= 5) {
      $html .= '<img style="margin-right: 2px;" src="https://s3-us-west-1.amazonaws.com/urban-halal/email-newsletter/images/rating-small-grey.png"/>';
      $x++;
    }

    $fbName = $user['facebook_first_name'];

    if ($user['username'] && ($user['facebook_first_name'] == '' || $user['facebook_first_name'] === NULL)) {

      $fbName = $user['username'];

    } elseif (($user['username'] == '' || $user['username'] === NULL) && ($user['facebook_first_name'] == '' || $user['facebook_first_name'] === NULL)) {

      $fbName = $user['facebook_email'];

    }

    $unsubUrl = $GLOBALS['SETTINGS']['websiteUrl'] . '/unsubscribe.php?e=' . $user['facebook_email'];

    if ($data['_tableName'] == 'ratings') {
      $placeholders = array('facebook_email' => $user['facebook_email'], 'facebook_first_name' => $fbName, 'facebook_picture' => $user['facebook_picture'], 'listing_image' => $listing_image, 'listing_name' => $listing['name'], 'listing_rating' => $html, 'unsubscribe_url' => $unsubUrl);
    } else {
      $placeholders = array('facebook_email' => $user['facebook_email'], 'facebook_first_name' => $fbName, 'facebook_picture' => $user['facebook_picture'], 'listing_image' => $listing_image, 'listing_name' => $listing['name'], 'listing_rating' => $html, 'tip' => $data['tip_content'], 'unsubscribe_url' => $unsubUrl);
    }

    $emailHeaders = emailTemplate_loadFromDB(array(
      'template_id' => $template_id,
      'placeholders' => $placeholders,
    ));

    $mailErrors = sendMessage($emailHeaders);
    if ($mailErrors) {
      $errorsAndAlerts .= "Mail Error: $mailErrors";
    } else {
      mysql_update("members", $user['num'], null, array('email_actions' => $user['email_actions'] . $emailAction));
    }

  }


}

function getBookingSlots(&$listing)
{
  $listingTime = utcTimeToLocalTime(time(), $listing['timezone']);
  $startDateStr = date("Y-m-d", strtotime("+1 day", strtotime($listingTime)));
  $endDateStr = date("Y-m-d", strtotime("+7 days", strtotime($listingTime)));

  while (strtotime($startDateStr) <= strtotime($endDateStr)) {
    $weekDay = strtolower(date("l", strtotime($startDateStr)));

    $listing[$weekDay] = "true";
    if ($listing[$weekDay . "_open"] == "closed") { // if true skip calculating slots for current day in loop
      $listing[$weekDay] = "false";
      $startDateStr = date("Y-m-d", strtotime("+1 day", strtotime($startDateStr)));
      continue;
    }

    $duration = (int) $listing['booking_slot_value'] * 60 * 60;

    $timeSlots = [];
    if (strpos($listing['booking'], "full") !== false) {
      $timeSlots[] = "Full Day";
    }
    if (strpos($listing['booking'], "slots") !== false) {

      if ($listing[$weekDay . "_open"] == "24hours") {
        $startTime = $startDateStr . " " . "00:00:00";
        $endTime = $startDateStr . " " . "23:45:00";
      } else {

        $lastDay = strtolower(date("l", strtotime("-1 day", strtotime($startDateStr))));
        // if last day close time is after midnight then add that slots to current day
        if (floatval($listing[$lastDay . "_open"]) > floatval($listing[$lastDay . "_close"])) {
          $lastDayOpenTime = $startDateStr . " " . "00:00:00";
          $lastDayCloseTime = $startDateStr . " " . api_floatToTime($listing[$lastDay . "_close"]) . ":00";
          $timeSlots = array_merge($timeSlots, makeTimeSlots($lastDayOpenTime, $lastDayCloseTime, $duration, true));
        }

        $startTime = $startDateStr . " " . api_floatToTime($listing[$weekDay . "_open"]) . ":00"; // 2020-01-24 09:00
        $endTime = $startDateStr . " " . api_floatToTime($listing[$weekDay . "_close"]) . ":00";
        // check if close time is on next day make slots upto 11:45 PM
        if ((float) $listing[$weekDay . "_close"] < (float) $listing[$weekDay . "_open"]) {
          $endTime = $startDateStr . " " . "23:45:00";
        }

      }
      $timeSlots = array_merge($timeSlots, makeTimeSlots($startTime, $endTime, $duration, true));
    }

    $timeSlots = removeBookedSlots($startDateStr, $listing['num'], $timeSlots);

    $listing['booking_time_slots'][] = [
      'date' => $startDateStr,
      'slots' => $timeSlots
    ];

    $startDateStr = date("Y-m-d", strtotime("+1 day", strtotime($startDateStr))); // update $startDateStr by adding 1 day

  }

}

function sendFirstCheckInEmail($listing, $user)
{

  $listing_image = $GLOBALS['listing_img'];

  $dotImage = 'orange';
  if ($listing['restaurant_status'] == 'closed' || $listing['restaurant_status'] == 'open_soon') {
    $dotImage = 'red';
  } elseif ($listing['restaurant_status'] == 'open') {
    $dotImage = 'green';
  }

  $address = "";
  if (!empty($listing['address_1']))
    $address = $listing['address_1'];
  if (!empty($listing['address_2']))
    $address .= ", " . $listing['address_2'];
  if (!empty($listing['city']))
    $address .= ", " . $listing['city'];

  $address = trim($address, ", ");

  $imageRecords = mysql_select('photo_uploads', "`listingsNum` = {$listing['num']} AND `for_photo` = 'photo' AND `flagged` = 0 ORDER BY `createdDate` DESC LIMIT 0,1", "`num`");
  foreach ($imageRecords as $key => $imageRecord) {
    $imageFiles = getUploadRecords('photo_uploads', 'photos', $imageRecord['num']);
    foreach ($imageFiles as $file) {
      $listing_image = $file['thumbUrlPath3'];
    }
  }

  $x = 1;
  $html = '';

  for ($x = 1; $x <= $listing['average_rating']; $x++) {
    $html .= '<img style="margin-right: 2px;" src="https://s3-us-west-1.amazonaws.com/urban-halal/email-newsletter/images/rating-small-yellow.png"/>';
  }
  while ($x <= 5) {
    $html .= '<img style="margin-right: 2px;" src="https://s3-us-west-1.amazonaws.com/urban-halal/email-newsletter/images/rating-small-grey.png"/>';
    $x++;
  }

  $fbName = $user['facebook_first_name'];

  if ($user['username'] && ($user['facebook_first_name'] == '' || $user['facebook_first_name'] === NULL)) {

    $fbName = $user['username'];

  } elseif (($user['username'] == '' || $user['username'] === NULL) && ($user['facebook_first_name'] == '' || $user['facebook_first_name'] === NULL)) {

    $fbName = $user['facebook_email'];

  }

  $mapImage = "https://maps.google.com/maps/api/staticmap?center=" . $listing['latitude'] . "," . $listing['longitude'] . "&zoom=16&size=280x80&scale=1&markers=icon:" . $GLOBALS['SETTINGS']['s3AssetsLink'] . "mapmarker-31x37.png" . "|" . $listing['latitude'] . "," . $listing['longitude'] . "&key=" . $GLOBALS['SETTINGS']['googleApiKey'];

  $unsubUrl = $GLOBALS['SETTINGS']['websiteUrl'] . '/unsubscribe.php?e=' . $user['facebook_email'];

  $placeholders = array('facebook_email' => $user['facebook_email'], 'facebook_first_name' => $fbName, 'facebook_picture' => $user['facebook_picture'], 'listing_image' => $listing_image, 'listing_name' => $listing['name'], 'listing_address' => $address, 'map_image' => $mapImage, 'listing_rating' => $html, 'listing_status' => $dotImage, 'unsubscribe_url' => $unsubUrl);

  $emailHeaders = emailTemplate_loadFromDB(array(
    'template_id' => 'FIRST-CHECKIN-EMAIL',
    'placeholders' => $placeholders,
  ));

  $mailErrors = sendMessage($emailHeaders);
  if ($mailErrors) {
    $errorsAndAlerts .= "Mail Error: $mailErrors";
  } else {
    mysql_update("members", $user['num'], null, array('email_actions' => $user['email_actions'] . "checkins,"));
  }

}

function sendFirstPhotoEmail($data, $user)
{

  $fbName = $user['facebook_first_name'];

  if ($user['username'] && ($user['facebook_first_name'] == '' || $user['facebook_first_name'] === NULL)) {

    $fbName = $user['username'];

  } elseif (($user['username'] == '' || $user['username'] === NULL) && ($user['facebook_first_name'] == '' || $user['facebook_first_name'] === NULL)) {

    $fbName = $user['facebook_email'];

  }

  $unsubUrl = $GLOBALS['SETTINGS']['websiteUrl'] . '/unsubscribe.php?e=' . $user['facebook_email'];

  $placeholders = array('facebook_email' => $user['facebook_email'], 'facebook_first_name' => $fbName, 'facebook_picture' => $user['facebook_picture'], 'image' => $_REQUEST['fileUrl'], 'unsubscribe_url' => $unsubUrl);

  $emailHeaders = emailTemplate_loadFromDB(array(
    'template_id' => 'FIRST-PHOTO-EMAIL',
    'placeholders' => $placeholders,
  ));

  $mailErrors = sendMessage($emailHeaders);
  if ($mailErrors) {
    $errorsAndAlerts .= "Mail Error: $mailErrors";
  } else {
    mysql_update("members", $user['num'], null, array('email_actions' => $user['email_actions'] . "photo,"));
  }
}

// Abhishek
// returns listings certs
function getListingCerts($listingsNum, $userNum, $certShareTexts, $listingName)
{

  $certs = addMemberPhotoLikesToPhotoUp(mysql_select('certs_uploads', "`listingsNum` = " . intval($listingsNum) . " AND `for_photo` = 'certificate' AND `flagged` = 0 ORDER BY `createdDate` DESC LIMIT 0,3"), 'cert_photo_likes');
  foreach ($certs as $certKey => $cert) {
    $certs[$certKey]['photos'] = getUploadRecords('certs_uploads', 'photos', $cert['num']);

    $certs[$certKey]['is_liked'] = "0";
    $certs[$certKey]['like_type'] = "";

    if (isUserLoggedIN($user) && mysql_get('cert_photo_likes', null, "`flagged` = 0 AND `membersNum` = " . intval($userNum) . " AND `photo_uploadsNum` = " . intval($cert['num']), "`like_type`")) {
      $certs[$certKey]['is_liked'] = "1";
      // $latest_photos[$photoKey]['like_type'] = $photoLiked['like_type'];
    }

    $certs[$certKey]['short_url'] = $GLOBALS['SETTINGS']['shortUrl'] . $cert['permalink'];
    $certs[$certKey]['share_text'] = $certShareTexts;
    // $certs[$certKey]['share_text'] = $certShareTexts;
  }
  return $certs;
}

function processProductData($products, $listingClosed = false, $batchScreen = false)
{

  $productAttrFields = ["price", "small", "medium", "large", "extra_large", "lbs1", "lbs2", "lbs3", "lbs4", "lbs5", "lbs6", "lbs7", "lbs8", "lbs_12_14", "lbs_14_16"];

  foreach ($products as $prodKey => $product) {

    $productAttrs = [];
    $priceSetup = getPriceSetup($product['listingsNum']);
    //Abhishek make price varinnt data data for each product 
    foreach ($productAttrFields as $prodAttrValue) {

      if (!is_null($product[$prodAttrValue]) && $product[$prodAttrValue] != '' && floatval($product[$prodAttrValue]) > 0) {

        if ($priceSetup) {
          $price = addCompetitivePrice($priceSetup, $product[$prodAttrValue]);
        } else {
          $price = number_format((float) $product[$prodAttrValue], 2, '.', ''); // format price value
        }

        $price = startsWith("$", $price) ? $price : "$" . $price; // add currency to price
        if ($prodAttrValue === 'price') { // if price attribute/variant is price then chaange it to regular
          array_push($productAttrs, ["regular" => $price]);
        } else {
          array_push($productAttrs, [$prodAttrValue => $price]);
        }
      }
      unset($products[$prodKey][$prodAttrValue]); // unset variant from product data because we are adding these to attribute param

      if (!$products[$prodKey]['price']) {
        $prodAttrValue = $prodAttrValue == "price" ? "regular" : $prodAttrValue;
        $products[$prodKey]['price'] = $productAttrs[0][$prodAttrValue];
      }
    }

    // Abhishek add options

    $reqMenuOptions = [];
    $optMenuOptions = [];
    $menuOptionsAttrs = mysql_select("menu_options", "`menu_id` = '" . $product['num'] . "'", "`name`,`price`,`is_required`");
    foreach ($menuOptionsAttrs as $menuOptionsAttr) {

      if ($priceSetup) {
        $menuOptionsAttr['price'] = addCompetitivePrice($priceSetup, $menuOptionsAttr['price']);
      } else {
        $menuOptionsAttr['price'] = number_format((float) $menuOptionsAttr['price'], 2, '.', ''); // format price value
      }

      if ($menuOptionsAttr['is_required'] == 1) {

        array_push($reqMenuOptions, ['name' => $menuOptionsAttr['name'], 'price' => "$" . formatPrice($menuOptionsAttr['price']), 'is_required' => $menuOptionsAttr['is_required']]);

      } else {

        array_push($optMenuOptions, ['name' => $menuOptionsAttr['name'], 'price' => "$" . formatPrice($menuOptionsAttr['price']), 'is_required' => $menuOptionsAttr['is_required']]);
      }

    }
    $products[$prodKey]['required_menu_options'] = $reqMenuOptions;

    $products[$prodKey]['optional_menu_options'] = $optMenuOptions;

    $listing = mysql_get("listings", $product['listingsNum'], null, "`name`, `type`, `city`, `is_online`, `timezone`,`monday_open`,`monday_close`,`tuesday_open`,`tuesday_close`,`wednesday_open`,`wednesday_close`,`thursday_open`,`thursday_close`,`friday_open`,`friday_close`,`saturday_open`,`saturday_close`,`sunday_open`,`sunday_close`");

    $listing = api_addOpenCloseDetailsToListing($listing);

    if (!$listing['is_online'] || $listing['restaurant_status'] === "closing_soon") {
      $listing['restaurant_status'] = 'closed';
    }

    if ($batchScreen) {
      $listing['restaurant_status'] = $listingClosed ? 'closed' : 'open';
    }

    // set time fields for listing
    getListingReadableTime($listing);

    unsetListingTimeFields($listing);

    $products[$prodKey] = array_merge($products[$prodKey], $listing);
    $products[$prodKey]['type'] = @$listing['type'] ? $listing['type'] : "";
    $products[$prodKey]['listing_name'] = $listing['name'];
    $products[$prodKey]['listing_city'] = $listing['city'];
    $products[$prodKey]['restaurant_status'] = $listing['restaurant_status'];

    $deliveryType = explode("\t", trim($product['delivery_type'], "\t"));
    sort($deliveryType);

    $products[$prodKey]['attributes'] = $productAttrs;
    // if prices for all the attributes are 0, empty or null then set price value to 0.00
    if (count($productAttrs) < 1) {
      $products[$prodKey]['price'] = "$0.00";
    }

    $products[$prodKey]['rating'] = "3.5";
    $products[$prodKey]['delivery_type'] = $deliveryType;
    $menuImage = mysql_get("uploads", null, "`tableName` = 'menu' AND `fieldName` = 'photo' AND `recordNum` = {$product['num']}", "`urlPath`");

    $products[$prodKey]['menu_image'] = $menuImage ? $menuImage['urlPath'] : $GLOBALS['SETTINGS']['s3AssetsLink'] . "default-menu.png";
    $products[$prodKey]['name'] = trim(ucwords(strtolower($product['name'])));

  }

  return $products;
}

function addListingData(&$listings, $key)
{

  $listings[$key]['mapKey'] = $GLOBALS['SETTINGS']['googleApiKey'];
  $listings[$key]['assetsLink'] = $GLOBALS['SETTINGS']['s3AssetsLink'];
  $listings[$key]['listingPhoto'] = $GLOBALS['SETTINGS']['s3AssetsLink'] . "uh-default-new.png";
  if (count($listings[$key]['urban_data_photo']) > 0) {
    foreach ($listings[$key]['urban_data_photo'] as $recentPhoto) {
      $listings[$key]['listingPhoto'] = $recentPhoto['photos'][0]['thumbUrlPath'];
      break;
    }
  }

  $listings[$key]['statusImage'] = 'orange';
  if ($listings[$key]['restaurant_status'] == 'closed' || $listings[$key]['restaurant_status'] == 'open_soon') {
    $listings[$key]['statusImage'] = 'red';
  } elseif ($listings[$key]['restaurant_status'] == 'open' || $listings[$key]['restaurant_status'] == "closing_soon") {
    $listings[$key]['statusImage'] = 'green';
  }

  $listings[$key]['listingStatusText'] = "Open 24 hours";
  $dayOfWeek = strtolower(date("l"));
  $nextDayOfWeek = strtolower(date("l", strtotime("+1 day")));
  if ($listings[$key]['restaurant_status'] == 'closing_soon') {
    if (intVal($listings[$key]['restaurant_closes_in']) > 60) {
      $listings[$key]['listingStatusText'] = "Open until " . $listings[$key][$dayOfWeek . "_close:label"];
    } else {
      $listings[$key]['listingStatusText'] = "Closing in " . $listings[$key]['restaurant_closes_in'] . " minutes";
    }
  } elseif ($listings[$key]['restaurant_status'] == 'open_soon') {
    $listings[$key]['listingStatusText'] = "Opens at " . $listings[$key][$dayOfWeek . "_open:label"];
  } elseif ($listings[$key]['restaurant_status'] == 'closed') {
    $nextDayStatus = $listings[$key][$nextDayOfWeek . "_open:label"];
    if ($nextDayStatus == 'closed')
      $listings[$key]['listingStatusText'] = "Closed";
    elseif ($nextDayStatus == '24hours')
      $listings[$key]['listingStatusText'] = "Opens tomorrow for 24 hours";
    else
      $listings[$key]['listingStatusText'] = "Opens tomorrow at " . $nextDayStatus;
  } else {
    if ($listings[$key][$dayOfWeek . "_close:label"] == '24hours') {
      $listings[$key]['listingStatusText'] = "Open 24 hours";
    } else {
      $listings[$key]['listingStatusText'] = "Open until " . $listings[$key][$dayOfWeek . "_close:label"];
    }
  }

  $address1 = "";
  $address2 = "";
  if (!empty($listings[$key]['address_1']))
    $address1 = $listings[$key]['address_1'];
  if (!empty($listings[$key]['address_2']))
    $address1 .= ", " . $listings[$key]['address_2'];
  if (!empty($listings[$key]['city']))
    $address2 .= ", " . $listings[$key]['city'];
  if (!empty($listings[$key]['state']))
    $address2 .= ", " . $listings[$key]['state'];
  if (!empty($listings[$key]['zip']))
    $address2 .= ", " . $listings[$key]['zip'];

  $listings[$key]['address_1'] = trim($address1, ", ");
  $listings[$key]['address_2'] = trim($address2, ", ");

  $mapQuery = urlencode($listings[$key]['name']) . "," . urlencode(trim($listings[$key]['address_1'] . $listings[$key]['address_2'], ", "));

  $listings[$key]['mapLink'] = "https://www.google.com/maps/search/?api=1&query=" . trim($mapQuery, ", ");

  $listings[$key]['addListingUrl'] = "name=" . urlencode($listings[$key]['name']) . "&city=" . urlencode($listings[$key]['city']) . "&zip=" . urlencode($listings[$key]['zip']) . "&type=" . urlencode($listings[$key]['type']);

  $platforms = empty($listings[$key]['platforms']) ? [] : array_map(function ($v) {
    return strtolower(str_replace(" ", "", $v)); }, explode("\t", trim($listings[$key]['platforms'], "\t")));
  $listings[$key]['platforms'] = $platforms;

}

function getListingReadableTime(&$listing)
{
  $timeFields = array('monday_open', 'monday_close', 'tuesday_open', 'tuesday_close', 'wednesday_open', 'wednesday_close', 'thursday_open', 'thursday_close', 'friday_open', 'friday_close', 'saturday_open', 'saturday_close', 'sunday_open', 'sunday_close');
  $readableTimes = getListOptions('listings', 'monday_open');

  foreach ($timeFields as $field) {

    $listing[$field . "_label"] = $readableTimes[$listing[$field]];

  }
}

function unsetListingTimeFields(&$listing)
{
  $fields = array('monday_open', 'monday_close', 'tuesday_open', 'tuesday_close', 'wednesday_open', 'wednesday_close', 'thursday_open', 'thursday_close', 'friday_open', 'friday_close', 'saturday_open', 'saturday_close', 'sunday_open', 'sunday_close', 'timezone', '_tableName');

  foreach ($fields as $field) {
    unset($listing[$field]);
  }
}

// Abhishek
// 
// Description  check if user has applied promo in the cart
//
// params $user(object), $subTotal(float), $cartData
//
// return $discount(float)
function checkPromoCode($user, $subTotal, &$cartData)
{
  $discount = 0;
  if (isUserLoggedIN($user)) {
    //$userPromoCode = mysql_get("promo_code_used", null, "`membersNum` = {$user['num']} AND `is_redeemed` = 0");
    $userPromoCode = mysql_get_query("SELECT cmsb_promo_codes.name, promo_type, percentage_discount, price_discount, description, order_price_limit, quantity_per_user FROM `cmsb_promo_code_used` INNER JOIN cmsb_promo_codes ON cmsb_promo_codes.num = cmsb_promo_code_used.promoCodesNum WHERE cmsb_promo_code_used.membersNum = {$user['num']} AND cmsb_promo_code_used.is_redeemed = 0 AND (NOW() < cmsb_promo_codes.expiry_date)");

    if ($userPromoCode) {
      //$promoCode = mysql_get("promo_codes", $userPromoCode['promoCodesNum'], null);
      if ($userPromoCode['percentage_discount']) {
        $discount = ($subTotal * (int) $userPromoCode['percentage_discount']) / 100;
      } else {
        $discount = $userPromoCode['price_discount'];
      }
    }
  }

  // Abhishek add promo code data to first item of cart beacuse of app requirements
  $cartData[0]['promo_name'] = @$userPromoCode ? $userPromoCode['name'] : "";
  $cartData[0]['promo_type'] = @$userPromoCode ? $userPromoCode['promo_type'] : "";
  $cartData[0]['promo_percentage_discount'] = @$userPromoCode ? $userPromoCode['percentage_discount'] : "";
  $cartData[0]['promo_price_discount'] = @$userPromoCode ? $userPromoCode['price_discount'] : "";
  $cartData[0]['promo_description'] = @$userPromoCode ? $userPromoCode['description'] : "";
  $cartData[0]['promo_order_price_limit'] = @$userPromoCode ? $userPromoCode['order_price_limit'] : "";
  $cartData[0]['promo_quantity_per_user'] = @$userPromoCode ? $userPromoCode['quantity_per_user'] : "";

  return round($discount, 2);

}

// Abhishek
// make time slots for next n days
function getTimeSlotsForSchedule($listing)
{
  $listingTime = utcTimeToLocalTime(time(), $listing['timezone']);
  $startDateStr = date("Y-m-d", strtotime($listingTime));

  $dateTimeSlots[] = [
    'dates' => "Now",
    'times' => ["ASAP"]
  ];
  if ($listing['type'] === "Brands") {
    $startDateStr = date("Y-m-d", strtotime("+1 day", strtotime($listingTime)));
    $dateTimeSlots = [];
  }

  // $endDateStr   = date("Y-m-d", strtotime("+6 days", strtotime($listingTime)));
  $count = 1;
  while ($count < 8) {
    $addDeliveryNowOption = true;
    $weekDay = strtolower(date("l", strtotime($startDateStr)));
    // echo $weekDay;

    // if true skip calculating slots for current day in loop
    if ($listing[$weekDay . "_open"] == "closed") {
      $startDateStr = date("Y-m-d", strtotime("+1 day", strtotime($startDateStr)));
      continue;
    }

    //$duration  = (int)$listing['booking_slot_value'] * 60 * 60;
    $duration = 30 * 60;
    $timeSlots = [];
    // if (strpos($listing['booking'], "full") !== false) {
    //   $timeSlots[] = "Full Day";
    // }
    //if (strpos($listing['booking'], "slots") !== false) {
    if ($listing['type'] === "Brands") {
      $startTime = $startDateStr . " " . "08:00:00";
      $endTime = $startDateStr . " " . "20:00:00";
      $duration = 4 * 60 * 60;
    } elseif ($listing[$weekDay . "_open"] == "24hours") {
      $startTime = $startDateStr . " " . "00:00:00";
      $endTime = $startDateStr . " " . "23:59:59";
    } else {

      $lastDay = strtolower(date("l", strtotime("-1 day", strtotime($startDateStr))));
      // if last day close time is after midnight then add that slots to current day
      if (floatval($listing[$lastDay . "_open"]) > floatval($listing[$lastDay . "_close"])) {
        $lastDayOpenTime = $startDateStr . " " . "00:00:00";
        $lastDayCloseTime = $startDateStr . " " . api_floatToTime($listing[$lastDay . "_close"]) . ":00";
        $timeSlots = array_merge($timeSlots, makeTimeSlots($lastDayOpenTime, $lastDayCloseTime, $duration, true));
      }

      $startTime = $startDateStr . " " . api_floatToTime($listing[$weekDay . "_open"]) . ":00"; // 2020-01-24 09:00
      $endTime = $startDateStr . " " . api_floatToTime($listing[$weekDay . "_close"]) . ":00";

      // check if close time is on next day make slots upto 11:45 PM
      // if ((float)$listing[$weekDay."_close"] < (float)$listing[$weekDay."_open"]) {
      //   $endTime = $startDateStr . " " . "23:45:00";
      // }

    }

    if ($listing['type'] !== "Brands") {

      // if current time is before the listing open time then do not add "Deliver Now" option
      if ($count === 1 && strtotime($listingTime) < strtotime($startTime)) {
        array_shift($dateTimeSlots);
        $addDeliveryNowOption = false;
      }

      // add 90 minutes to listing open time so user can't schedule order at exact open time of listing
      // also subtract 1 hour from listing end time so user can't order when there is only 1 hour left for listing closed time
      $startTime = date('Y-m-d H:i:s', strtotime('+90 minutes', strtotime($startTime)));
      $endTime = date('Y-m-d H:i:s', strtotime('-1 hour', strtotime($endTime)));

      // if listing current time is past the listing end time then skip time slots for current day
      if (strtotime($endTime) - strtotime($listingTime) <= 5400) {

        if ($addDeliveryNowOption && strtotime($endTime) - strtotime($listingTime) > 0) {
          goto endofloop;
        }
        $startDateStr = date("Y-m-d", strtotime("+1 day", strtotime($startDateStr)));
        continue;
      }

      if (strpos($listingTime, $startDateStr) !== false) {
        // add 30 minutes to starttime until startTime is atlest 1 hour ahead
        // from listing current time
        while (strtotime($startTime) - strtotime($listingTime) <= 3600) {
          $startTime = date("Y-m-d h:i A", strtotime($startTime) + $duration);
        }
      }

    }

    $timeSlots = array_merge($timeSlots, makeTimeSlots($startTime, $endTime, $duration, true));
    //}

    // timeSlots are empty when listing open and close time diffrence is less than 3 hsours
    if (empty($timeSlots)) {
      $startDateStr = date("Y-m-d", strtotime("+1 day", strtotime($startDateStr)));
      continue;
    }

    //$timeSlots = removeBookedSlots($startDateStr, $listing['num'], $timeSlots);

    $dateTimeSlots[] = [
      'dates' => date("D, M j", strtotime($startDateStr)),
      'times' => $timeSlots
    ];

    endofloop:
    // update $startDateStr by adding 1 day
    $startDateStr = date("Y-m-d", strtotime("+1 day", strtotime($startDateStr)));

    $count++;
  }
  return $dateTimeSlots;
}

// Abhishek
// make time slots of $duration from $startTime and $startTime
// return array of slots like 
// if $bookingSlots == true [09:00 AM - 01:00 PM, 01:00 PM - 05:00 PM]
// else [09:00 AM, 09:15 AM, 10:00 AM]
function makeTimeSlots($startTime, $endTime, $duration, $bookingSlots = false)
{
  $returnArray = array();// Define output
  $startTime = strtotime($startTime); //Get Timestamp
  $endTime = strtotime($endTime); //Get Timestamp

  while ($startTime <= $endTime) //Run loop
  {
    $slot = date("h:i A", $startTime);

    if ($bookingSlots) {
      if ($startTime == $endTime) {
        break;
      }
      // $slot = makeTimeBookingSlotsStr($startTime, $endTime, $duration, $slot);
      $slot .= " - " . date("h:i A", $startTime + $duration);
    }

    $returnArray[] = $slot;
    $startTime += $duration; //Endtime check
  }
  return $returnArray;
}

// Abhishek
// make booking time slots of $duration from $startTime and $endTime
// return slots like 09:00 AM - 01:00 PM if $duration is 4hrs i .e 4 * 60 * 60
function makeTimeBookingSlotsStr($startTime, $endTime, $duration, $slot)
{
  if (($startTime + $duration) > $endTime) {
    $slot .= " - " . date("h:i A", $endTime);
  } else {
    $slot .= " - " . date("h:i A", $startTime + $duration);
  }
  return $slot;
}

// Abhishek
// Check if there is already a booking for $startDateStr date and filter the slots
function removeBookedSlots($startDateStr, $listingsNum, $bookingTimeSlots)
{
  $newBookingSlots = [];
  foreach ($bookingTimeSlots as $slotKey => $bookingTimeSlot) {
    $where = "`listingsNum` = $listingsNum AND booking_datetime = '" . $startDateStr . " " . $bookingTimeSlot . "'";
    $bookings = mysql_count("orders", "$where");
    if ($bookings) {

      if ($bookingTimeSlot === "Full Day") {
        $newBookingSlots = [];
        break;
      } else {
        // if any of the slot is book for day then remove full day booking option also if any
        if (($arrayKey = array_search("Full Day", $newBookingSlots)) !== false) {
          unset($newBookingSlots[$arrayKey]);
        }
      }

    } else {
      array_push($newBookingSlots, $bookingTimeSlot);
    }
  }
  return array_values($newBookingSlots);
}

// Abhishek
// return lisitng address string like Street Address, City, State Zip
// e.g M. Younis Building 5708 Schaefer Rd, Dearborn, MI 48126
function getListingAddressStr($listingsNum)
{
  $listing = mysql_get("listings", $listingsNum, null, "`name`, `address_1`, `city`, `state`, `zip`,`phone`");
  if ($listing) {
    return trim($listing['address_1'] . ", " . $listing['city'] . ", " . $listing['state'] . " " . $listing['zip'], ", ");
  }

  return "";
}


function getCartData($section)
{
  global $user;
  error_log('getCartData: called with $section = ' . $section . ', $user = ' . print_r($user, true));

  // Get cart items based on user
  list($where, $tempMemberNum) = updateCartMember($user);
  error_log('getCartData: $where = ' . $where);

  $cartItems = mysql_select($section, $where);
  error_log('getCartData: $cartItems = ' . print_r($cartItems, true));

  $cartData = array();
  $cartData['urban_data'] = array();
  $cartData['meta'] = array();
  $cartData['item_text'] = '';
  $cartData['item_data'] = array();

  if ($cartItems) {
    $subTotal = 0;
    $deliveryFee = 0;
    $platformFee = 0;
    $smallOrderFee = 0;
    $discount = 0;
    $total = 0;

    foreach ($cartItems as $key => $cartItem) {
      // Validate each item
      if (validateItem($cartItem)) {
        $cartData['urban_data'][] = $cartItem;
        
        // Check if this is a party order
        $menuOptions = json_decode($cartItem['menu_options'], true) ?: [];
        if (isset($menuOptions['_party_metadata']) && $menuOptions['_party_metadata']['is_party_order']) {
          // For party orders, price is already multiplied by people count
          $subTotal += $cartItem['item_price'] * 1;
        } else {
          // For individual orders, use normal quantity calculation
        $subTotal += $cartItem['item_price'] * $cartItem['quantity'];
        }
      }
    }

    // Calculate totals and fees
    if (!empty($cartData['urban_data'])) {
      $firstItem = reset($cartData['urban_data']);
      $listingsNum = $firstItem['listingsNum'];

      // Get listing details
      $listing = mysql_get('urbanhal_listings', $listingsNum);

      if ($listing) {
        // Get delivery fee setup
        $deliveryFeeSetup = getListingDeliveryFeeSetup($listingsNum);

        // Calculate delivery fee
        $deliveryFee = $deliveryFeeSetup['delivery_fee'] ?? 0;

        // Calculate platform and small order fees
        list($platformFee, $smallOrderFee) = getPlatformAndSmallOrderFee(
          $listing['type'],
          $firstItem['item_delivery_type'],
          $subTotal,
          $deliveryFeeSetup
        );

        // Calculate total
        $total = $subTotal + $deliveryFee + $platformFee + $smallOrderFee - $discount;

        // Add meta information
        $cartData['meta'] = array(
          'subtotal' => number_format($subTotal, 2),
          'delivery_fee' => number_format($deliveryFee, 2),
          'platform_fee' => number_format($platformFee, 2),
          'small_order_fee' => number_format($smallOrderFee, 2),
          'discount' => number_format($discount, 2),
          'total' => number_format($total, 2),
          'currency' => 'USD',
          'items_count' => count($cartData['urban_data'])
        );
      }
    }
  }

  error_log('getCartData: Final $cartData = ' . print_r($cartData, true));
  return $cartData;
}

function validateItem(&$cartItem)
{
  $menuItem = mysql_get("menu", $cartItem['productsNum'], null);
  if (!$menuItem) {
    $cartItem['error'] = "Item not found in menu";
    return false;
  }

  $size = ($cartItem['size'] == "regular") ? "price" : $cartItem['size'];
  if ($size === "extra large") {
    $size = "extra_large";
  }
  $size = getItemSize($size);

  $priceSetup = getPriceSetup($cartItem['listingsNum']);
  if ($priceSetup) {
    $cartItem['item_price'] = $originalPrice = addCompetitivePrice($priceSetup, $menuItem[$size]);
  } else {
    $cartItem['item_price'] = $originalPrice = (float) $menuItem[$size];
  }

  // Initialize people count for party orders (category = 'party')
  $peopleCount = 1;
  
  // Get category name to check if it's a party order
  $categoryName = '';
  if ($menuItem && $menuItem['category']) {
    $categoryRow = mysql_get("menu_categories", $menuItem['category'], null);
    if ($categoryRow) {
      $categoryName = strtolower($categoryRow['category_name']);
    }
  }
  $isPartyOrder = ($categoryName === 'party');
  
  // Calculate options price and find people count for party orders
  $optionsPrice = 0;
  foreach ($cartItem['menu_options'] as $menuOption) {
    $menuOptionName = $menuOption['name'];
    
    // Get option by matching option_name field (not 'name')
    $optionRow = mysql_get("menu_options", null, "`menu_id` = {$cartItem['productsNum']} AND `option_name` = '" . mysqli_real_escape_string(mysqli(), $menuOptionName) . "'");

    if ($optionRow) {
      // Check if this is a people_count option for party orders
      if ($isPartyOrder && $optionRow['option_type'] == 'people_count') {
        // Get the selected choice to determine people count
        if (isset($menuOption['choice_id'])) {
          $choiceRow = mysql_get("menu_option_choices", $menuOption['choice_id'], null);
          if ($choiceRow && isset($choiceRow['choice_name'])) {
            // Extract number from choice name (e.g., "2 People" -> 2)
            preg_match('/(\d+)/', $choiceRow['choice_name'], $matches);
            if (!empty($matches[1])) {
              $peopleCount = (int) $matches[1];
            }
          }
        }
      }
      
      // Add option base price (from menu_options.price)
      if ($priceSetup) {
        $optionsPrice += addCompetitivePrice($priceSetup, $optionRow['price']);
      } else {
        $optionsPrice += (float) $optionRow['price'];
      }
      
      // Add choice price if selected (from menu_option_choices.price)
      if (isset($menuOption['choice_id'])) {
        $choiceRow = mysql_get("menu_option_choices", $menuOption['choice_id'], null);
        if ($choiceRow) {
          if ($priceSetup) {
            $optionsPrice += addCompetitivePrice($priceSetup, $choiceRow['price']);
          } else {
            $optionsPrice += (float) $choiceRow['price'];
          }
        }
      }
    }
  }

  // For party orders, multiply by people count
  if ($isPartyOrder) {
    $totalPrice = ($originalPrice + $optionsPrice) * $peopleCount;
    
    // Store party info in menu_options JSON (no database change needed)
    if (!isset($cartItem['menu_options'])) {
      $cartItem['menu_options'] = [];
    }
    
    // Add party metadata to options
    $cartItem['menu_options']['_party_metadata'] = [
      'is_party_order' => true,
      'people_count' => $peopleCount,
      'base_price_per_person' => ($originalPrice + $optionsPrice),
      'total_calculated' => $totalPrice
    ];
  } else {
    $totalPrice = $originalPrice + $optionsPrice;
  }

  if (isset($menuItem['discount']) && $menuItem['discount_expire_date'] > date('Y-m-d H:i:s')) {
    $totalPrice = $totalPrice - ($menuItem['discount'] * ($isPartyOrder ? $peopleCount : 1));
  }

  $cartItem['item_price'] = formatPrice($totalPrice);
  $cartItem['old_price'] = "";
  $cartItem['error'] = "";
  return true;
}


function getItemSize($size)
{

  switch ($size) {

    case '1lbs':
      $size = "lbs1";
      break;

    case '2lbs':
      $size = "lbs2";
      break;

    case '3lbs':
      $size = "lbs3";
      break;

    case '4lbs':
      $size = "lbs4";
      break;

    case '5lbs':
      $size = "lbs5";
      break;

    case '6lbs':
      $size = "lbs6";
      break;

    case '7lbs':
      $size = "lbs7";
      break;

    case '8lbs':
      $size = "lbs8";
      break;

    case '12-14lbs':
      $size = "lbs_12_14";
      break;

    case '14-16lbs':
      $size = "lbs_14_16";
      break;

    default:
      $size;
  }

  return $size;
}

function addCompetitivePrice($priceSetup, $price)
{
  $price = str_replace("$", "", trim($price));
  $competitivePrice = ($price * $priceSetup['competitive_price']) / 100;

  $price = round($price + $competitivePrice, 2);

  return number_format($price, 2, '.', '');
}

function getCompetitivePrice($priceSetup, $productPrice, $productQty)
{
  // $productSize = ($productSize == "regular") ? "price" : $productSize;
  // $menuItem = mysql_get("menu", $productsNum, null, "$productSize");
  $orgPrice = ($productPrice * 100) / (100 + $priceSetup['competitive_price']);
  $competitivePrice = round(($orgPrice * $priceSetup['competitive_price']) / 100, 2);

  return array($competitivePrice * $productQty);

}

function getPriceSetup($listingsNum)
{
  $priceSetup = mysql_get("stripe_accounts", null, "`listingsNum` = $listingsNum", "`competitive_price`");
  if (intval(@$priceSetup['competitive_price'])) {
    return $priceSetup;
  }
  return false;
}

function getListingStatus($listingsNum, $listing = null, $returnString = true)
{

  if (!$listing) {
    $listing = mysql_get('listings', $listingsNum, null, "`timezone`,`monday_open`,`monday_close`,`tuesday_open`,`tuesday_close`,`wednesday_open`,`wednesday_close`,`thursday_open`,`thursday_close`,`friday_open`,`friday_close`,`saturday_open`,`saturday_close`,`sunday_open`,`sunday_close`");
  }
  $listing = api_addOpenCloseDetailsToListing($listing);

  return $listing['restaurant_status'];
}

function getDeliveryDiscountValues($listingsNum, $orderSettings, $listingType)
{

  $listingFeeSetup = getListingDeliveryFeeSetup($listingsNum);

  if (
    strtotime($listingFeeSetup['free_delivery_expiry_date']) >= time() ||
    in_array($listingType, ['Produce', 'Brands'])
  ) {
    if (!empty($listingFeeSetup['flat_delivery_fee'])) {
      $orderSettings['delivery_fee_discount'] = $orderSettings['adjust_platform_fee'] = "0";
    } else {
      $orderSettings['delivery_fee_discount'] = $listingFeeSetup['delivery_fee_discount'];
      $orderSettings['adjust_platform_fee'] = $listingFeeSetup['adjust_platform_fee'];
    }

  } elseif (strtotime($orderSettings['free_delivery_expiry_date']) < time()) {
    $orderSettings['delivery_fee_discount'] = $orderSettings['adjust_platform_fee'] = "0";
  }

  return $orderSettings;
}

function getPlatformAndSmallOrderFee($listingType, $deliveryType, $subTotalAfterDiscount, $orderSettings)
{
  $platformFee = $smallOrderFee = "0.00";

  if ($deliveryType === 'delivery' && in_array(ucfirst($listingType), ['Places', 'Markets', 'Brands', 'Produce'])) {
    $platformFee = $subTotalAfterDiscount >= (float) $orderSettings['platform_fee_subtotal'] ? $orderSettings['max_delivery_platform_fee'] : $orderSettings['min_delivery_platform_fee'];
  }

  // if($deliveryType === 'ship' && $listingType === 'Brands') {
  //   $platformFee = $subTotalAfterDiscount >= (float)$orderSettings['platform_fee_subtotal'] ? $orderSettings['max_delivery_platform_fee'] : $orderSettings['min_delivery_platform_fee'];
  // }

  // if($deliveryType === 'ship' && $listingType === 'Markets') {
  //   $platformFee = $subTotalAfterDiscount < (float)$orderSettings['platform_fee_subtotal'] ? $orderSettings['meat_ship_platform_fee'] : "0.00";
  // }

  if ($deliveryType === 'pickup') {
    if ($listingType === 'Places') {
      $platformFee = $subTotalAfterDiscount < (float) $orderSettings['platform_fee_subtotal'] ? $orderSettings['food_pickup_platform_fee'] : "0.00";
    } elseif ($listingType === 'Festival') {
      $platformFee = $subTotalAfterDiscount < (float) $orderSettings['platform_fee_subtotal'] ? $orderSettings['events_pickup_platform_fee'] : "0.00";
    } elseif ($listingType === 'Markets') {
      $platformFee = $subTotalAfterDiscount < (float) $orderSettings['platform_fee_subtotal'] ? $orderSettings['meat_pickup_platform_fee'] : "0.00";
    }
  }

  // if($deliveryType === 'schedule') {
  //   if($subTotalAfterDiscount >= (float)$orderSettings['order_subtotal_max']) {
  //     $platformFee = $orderSettings['max_schedule_platform_fee'];
  //   }
  //   elseif($subTotalAfterDiscount >= (float)$orderSettings['order_subtotal_min'] && $subTotalAfterDiscount < (float)$orderSettings['order_subtotal_max']) {
  //     $platformFee = $orderSettings['avg_schedule_platform_fee'];
  //   }
  //   else{
  //     $platformFee = $orderSettings['min_schedule_platform_fee'];
  //   }
  // }

  // add small delivery fee only for food and meat
  if (in_array($listingType, ['Places', 'Markets', 'Brands', 'Produce']) && $deliveryType === 'delivery') {
    $smallOrderFee = $subTotalAfterDiscount < (float) $orderSettings['small_order_subtotal'] ? $orderSettings['small_order_fee'] : "0.00";
  }

  return [$platformFee, $smallOrderFee];
}

// Abhishek subtract platform fee from delivery fee
function discountDeliveryFee($deliveryFee, $listing, $orderSettings)
{
  // Initialize default values
  $deliveryFeeDiscount = 0;
  $adjustPlatformFee = false;

  // Check if listing array exists and has required keys
  if (
    is_array($listing) && isset($listing['free_delivery_expiry_date']) &&
    strtotime($listing['free_delivery_expiry_date']) >= time()
  ) {
    $deliveryFeeDiscount = isset($listing['delivery_fee_discount']) ? $listing['delivery_fee_discount'] : 0;
    $adjustPlatformFee = isset($listing['adjust_platform_fee']) ? $listing['adjust_platform_fee'] : false;
  }
  // Check if orderSettings array exists and has required keys
  elseif (
    is_array($orderSettings) && isset($orderSettings['free_delivery_expiry_date']) &&
    strtotime($orderSettings['free_delivery_expiry_date']) >= time()
  ) {
    $deliveryFeeDiscount = isset($orderSettings['delivery_fee_discount']) ? $orderSettings['delivery_fee_discount'] : 0;
    $adjustPlatformFee = isset($orderSettings['adjust_platform_fee']) ? $orderSettings['adjust_platform_fee'] : false;
  }

  // Apply delivery fee discount if available
  if ($deliveryFeeDiscount > 0) {
    $deliveryFee = $deliveryFee - ($deliveryFee * $deliveryFeeDiscount) / 100;
  }
  // Apply platform fee adjustment if available
  elseif ($adjustPlatformFee && isset($orderSettings['min_delivery_platform_fee'])) {
    $deliveryFee = $deliveryFee - $orderSettings['min_delivery_platform_fee'];
  }

  // Ensure delivery fee is not negative
  $deliveryFee = max(0, $deliveryFee);

  // Format the delivery fee
  $deliveryFee = number_format($deliveryFee, 2, '.', '');

  return $deliveryFee;
}

function getListingDeliveryFeeSetup($listingsNum)
{
  $listing = mysql_get("stripe_accounts", null, "`listingsNum` = '" . $listingsNum . "'", "`adjust_platform_fee`, `delivery_fee_discount`,`free_delivery_expiry_date`,`flat_delivery_fee`,`offer_text`");
  if (!empty($listing)) {
    $listing['delivery_fee_discount'] = (int) $listing['delivery_fee_discount'] ? $listing['delivery_fee_discount'] : "0";
  } else {
    $listing['free_delivery_expiry_date'] = "0000-00-00 00:00:00";
    $listing['flat_delivery_fee'] = "";
    $listing['adjust_platform_fee'] = $listing['delivery_fee_discount'] = "0";
  }
  return $listing;
}

function checkOrderBadge($userNum)
{

  $badge = mysql_get("badges", null, "`badge_type` = 'EATER'", "`num`,`badge_name`,`success_text`,`points`");

  $userBadge = mysql_get("user_badges", null, "`membersNum` = '" . $userNum['num'] . "' AND `badgesNum` = '" . $badge['num'] . "'", "*");

  $badgeImage = mysql_get("uploads", null, "`tableName`= 'badges' AND  `recordNum`= '" . $badge['num'] . "' AND `fieldName`= 'completed_image'", "`urlPath`");

  $badgeGif = mysql_get("uploads", null, "`tableName`= 'badges' AND  `recordNum`= '" . $badge['num'] . "' AND `fieldName`= 'gif_badge'", "`urlPath`");

  if (count($userBadge) > 0) {
    $badgeInfo['first_order'] = "0";

  } else {

    mysql_insert("user_badges", array("membersNum" => $userNum['num'], "createdByUserNum" => $userNum['num'], "updatedByUserNum" => $userNum['num'], "badgesNum" => $badge['num'], "points" => $badge['points'], 'createdDate' => date("Y-m-d H:i:s"), 'updatedDate' => date("Y-m-d H:i:s")), true);

    $updatedPoints = intval($badge['points']) + intval($userNum['points']);

    mysql_update("members", $userNum['num'], null, array('points' => $updatedPoints));

    $badgeInfo['first_order'] = "1";
    $badgeInfo['badge_num'] = $badge['num'];
    $badgeInfo['badge_points'] = $badge['points'];
    $badgeInfo['badge_name'] = $badge['badge_name'];
    $badgeInfo['badge_image'] = $badgeImage['urlPath'];
    $badgeInfo['badge_gif'] = $badgeGif['urlPath'];
    $badgeInfo['success_text'] = $badge['success_text'];
    $badgeInfo['updated_points'] = $updatedPoints;
  }
  return $badgeInfo;
}


function checkOrderScheduleTimeExpired($listing, $scheduleTime, $listingClosed)
{
  $listingTime = utcTimeToLocalTime(time(), $listing['timezone']);
  $scheduledTime = explode(" - ", str_replace("/", " ", $scheduleTime))[0];
  $scheduledTimeInSec = strtotime($scheduledTime) - 3600;

  $expired = false;
  if (strtotime($listingTime) > $scheduledTimeInSec) {
    $expired = true;
  }
  $scheduleDate = date("Y-m-d", $scheduledTimeInSec);
  if (strtotime($listingTime) < $scheduledTimeInSec && strpos($listingTime, $scheduleDate) !== false && $listingClosed) {
    $expired = true;
  }

  return $expired ? "RESCHEDULE ORDER\tYour scheduled time window has expired. Please choose a new time to proceed." : "";
}


function getUserCardData($user)
{

  $lastOrder = $badges = $promo = [];

  $where = "";

  $promoWhere = "`name` = 'HALALFOODNOW'";

  if (isUserLoggedIN($user)) {

    $order = mysql_select_query("SELECT `orders`.total, `orders`.num, `orders`.createdDate, `orders`.order_delivery_type as order_type, `listings`.name as listing_name, `orders`.listingsNum as listing_num, `listings`.timezone, `listings`.average_rating FROM `cmsb_orders` AS `orders` INNER JOIN `cmsb_listings` AS `listings` ON `listings`.num = `orders`.listingsNum WHERE `orders`.membersNum = {$user['num']} ORDER BY `orders`.createdDate DESC LIMIT 1");

    if ($order) {

      $imageRecords = mysql_select('photo_uploads', "`listingsNum` = {$order[0]['listing_num']} AND `for_photo` = 'photo' AND `flagged` = 0 ORDER BY `createdDate` DESC LIMIT 0,1", "`num`");

      foreach ($imageRecords as $imgKey => $imageRecord) {
        $imageFiles = getUploadRecords('photo_uploads', 'photos', $imageRecord['num']);
        foreach ($imageFiles as $file) {
          $order[0]['listing_image'] = $file['thumbUrlPath3'];
        }
      }

      $lastOrder[] = [
        "listing_name" => $order[0]['listing_name'],
        "average_rating" => $order[0]['average_rating'],
        "order_num" => $order[0]['num'],
        "order_total" => "$" . $order[0]['total'],
        "order_date" => utcTimeToLocalTime($order[0]['createdDate'], $order[0]['timezone'], true, 'Y-m-d H:i:s', 'Y-m-d H:i:s'),
        "order_type" => $order[0]['order_type'],
        "listing_image" => isset($order[0]['listing_image']) ? $order[0]['listing_image'] : ""
      ];

      $promoWhere = "num NOT IN (SELECT promoCodesNum FROM cmsb_promo_code_used WHERE membersNum = {$user['num']} AND is_redeemed = 1) AND expiry_date >= NOW() AND name != 'HALALFOODNOW'";

    }

    $where = "WHERE membersNum = {$user['num']}";

  }

  $badgeInfo = mysql_select_query("SELECT `badges`.badge_name, `badges`.num, `badges`.badge_description FROM `cmsb_badges` AS `badges` WHERE num NOT IN ( SELECT badgesNum FROM cmsb_user_badges $where ) ORDER BY RAND() LIMIT 1");

  if ($badgeInfo) {

    $badgeImage = mysql_get("uploads", null, "`tableName`= 'badges' AND  `recordNum`= '" . $badgeInfo[0]['num'] . "' AND `fieldName`= 'completed_image'", "`thumbUrlPath`");

    $badgeGif = mysql_get("uploads", null, "`tableName`= 'badges' AND  `recordNum`= '" . $badgeInfo[0]['num'] . "' AND `fieldName`= 'gif_badge'", "`thumbUrlPath`");

    $badges[] = [

      "badge_name" => $badgeInfo[0]['badge_name'],
      "badge_description" => $badgeInfo[0]['badge_description'],
      "badge_image" => isset($badgeImage['thumbUrlPath']) ? $badgeImage['thumbUrlPath'] : "",
      "badge_gif" => isset($badgeGif['thumbUrlPath']) ? $badgeGif['thumbUrlPath'] : "",
      "badge_num" => $badgeInfo[0]['num']
    ];


  }

  $promoCode = mysql_select_query("SELECT `promo_codes`.num, `promo_codes`.name, `promo_codes`.description FROM `cmsb_promo_codes` AS `promo_codes` WHERE $promoWhere ORDER BY RAND() LIMIT 1");
  if ($promoCode) {

    $promoImage = mysql_get("uploads", null, "`tableName`= 'promo_codes' AND  `recordNum`= '" . $promoCode[0]['num'] . "' AND `fieldName`= 'image'", "`urlPath`");

    $defaultImage = "https://urban-halal.s3-us-west-1.amazonaws.com/static_assets/promo.png";

    $promo[] = [

      "name" => "#" . $promoCode[0]['name'],
      "description" => $promoCode[0]['description'],
      "promo_image" => isset($promoImage['urlPath']) ? $promoImage['urlPath'] : $defaultImage,
    ];
  }

  return [$badges, $lastOrder, $promo];
}



function getListinglatestVotesCountAndText($listingsNum, $locationsNum)
{
  $createdDate = date("Y-m-d", strtotime("last sunday")) . " 00:00:00";

  $latestVotesMembers = mysql_select_query("SELECT UPPER(cmsb_members.facebook_first_name) as facebook_first_name, cmsb_members.facebook_picture as facebook_picture FROM cmsb_listing_votes INNER JOIN cmsb_members ON cmsb_listing_votes.membersNum = cmsb_members.num WHERE cmsb_listing_votes.listingsNum = $listingsNum AND cmsb_listing_votes.locationsNum = $locationsNum AND cmsb_listing_votes.createdDate > '$createdDate' GROUP BY cmsb_listing_votes.membersNum ORDER BY cmsb_listing_votes.num DESC LIMIT 3");
  $votesCount = mysql_count("listing_votes", "`listingsNum` = $listingsNum AND `locationsNum` = $locationsNum AND `createdDate` > '$createdDate'");

  $latestVotesMembersText = "";
  $latestVotesMembersImage = [];
  $latestVoteCountText = "";
  if (count($latestVotesMembers) > 0) {

    $latestVotesMembersText = implode(", ", array_column($latestVotesMembers, "facebook_first_name"));
    foreach ($latestVotesMembers as $latestVotesMember) {

      $latestVotesMembersImage[] = array_slice($latestVotesMember, 1);
    }

    if ($votesCount > 3) {
      $latestVoteCountText .= " + " . ($votesCount - 3) . " VOTED";
    } else {
      $latestVoteCountText .= " VOTED";
    }
  }

  $votesCount = "";

  return [$latestVotesMembersText, $latestVotesMembersImage, $latestVoteCountText];
}

function getaddress($lat, $lng)
{
  $array = [];
  $url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' . trim($lat) . ',' . trim($lng) . '&sensor=false&key=' . $GLOBALS['SETTINGS']['googleApiKey'];
  $json = @file_get_contents($url);
  $data = json_decode($json);
  $status = $data->status;
  if ($status == "OK") {
    $aComponents = $data->results[0]->address_components;

    foreach ($aComponents as $key => $value) {
      if ($value->types[0] == "street_number") {
        $array['street'] = $value->long_name;
      }

      if ($value->types[0] == "postal_code") {
        $array['zip'] = $value->long_name;
      }

      if ($value->types[0] == "route") {
        $array['street'] = $array['street'] . ' ' . $value->long_name;
      }

      if ($value->types[0] == "locality") {
        $array['city'] = $value->long_name;
      }

      if ($value->types[0] == "administrative_area_level_1") {
        $array['state'] = $value->short_name;
      }

    }
    return $array;
  } else {
    return $array;
  }
}