<?php
/*
Plugin Name: Urban Halal / Canvaas Plugin
Description: Contains custom functions for the Urban Halal and Canvaas Plugins
Author: Greg Thomas
Version: 1.0
Required System Plugin: True
*/
$GLOBALS['API_CHECK_INVITE_ALREADY_SENT'] = true;
//require $GLOBALS['SETTINGS']['webRootDir']."/vendor/facebook/graph-sdk/src/Facebook/autoload.php";
//require $GLOBALS['SETTINGS']['webRootDir']."/vendor/abraham/twitteroauth/autoload.php";
// require $GLOBALS['SETTINGS']['webRootDir']."/vendor/dompdf/dompdf/src/Autoloader.php";
use Abraham\TwitterOAuth\TwitterOAuth;

/***** DO NOT EDIT ANYHTING BELOW THIS POINT *****/


//addCronJob('urbcan_updateUserAndListingsMeta', "Update User And Listing Meta Info", '* * * * *');             // Run every hour
// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
pluginAction_addHandlerAndLink(t('Update User And Listing Meta Info'), 'urbcan_updateUserAndListingsMeta', 'admins');


// this function is called by cron, and logged under: Admin > General > Background Tasks
// return()'d content is logged as "Summary" and and print/echo content is logged as "output"
function urbcan_updateUserAndListingsMeta() {
  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive
  
  // $limit = 0;
  // $group = 500;
  // echo "Updating ratings...\r\n";
  // while(true){
  //   echo "\r\nGetting batch $limit, $group\r\n";
  //   $listings = mysql_select('listings', "TRUE LIMIT $limit, $group");
  //   if(!$listings){ echo "No more records found!\n"; break; }
  //   foreach($listings as $listing){
  //     echo "updating rating #{$listing['num']}...\n";
  //     $ratings = mysql_select('ratings', "`listingsNum` = '{$listing['num']}'");
  //     $totalRating = 0;
  //     foreach($ratings as $rating){
  //       $ratingValue = floatval($rating['rating']);
  //       if($ratingValue > 5) { echo "RATING #{$rating['num']} greater than 5!\n"; continue; }
  //       if($ratingValue < 0) { echo "RATING #{$rating['num']} less than 0!\n"; continue; }
  //       $totalRating += $ratingValue;
  //     }
  //     $numberOfRatings = count($ratings);
  //     $averageRating   = ($numberOfRatings)? $totalRating / $numberOfRatings : '0' ;
  //     $averageRating   = ($averageRating)? urbcan_convertFloatToRating($averageRating): '0' ;
  //     echo "Rating updated to '$averageRating'!\n";

  //     //Abhishek : added average_foodie_experince
  //     echo "updating foodie_experience #{$listing['num']}...\n";
  //     $foodieExperiences = mysql_select('foodie_experience', "`listingsNum` = '{$listing['num']}'");
  //     $totalFoodieExperience = 0;
  //     foreach($foodieExperiences as $foodieExperience){
  //       $foodieExperienceValue = floatval($foodieExperience['rating']);
  //       if($foodieExperienceValue > 5) { echo "FoodieExperience #{$foodieExperience['num']} greater than 5!\n"; continue; }
  //       if($foodieExperienceValue < 0) { echo "FoodieExperience #{$foodieExperience['num']} less than 0!\n"; continue; }
  //       $totalFoodieExperience += $foodieExperienceValue;
  //     }
  //     $numberOfFoodies = count($foodieExperiences);
  //     $averageFoodieExperience   = ($numberOfFoodies)? $totalFoodieExperience / $numberOfFoodies : '0' ;
  //     $averageFoodieExperience   = ($averageFoodieExperience)? urbcan_convertFloatToRating($averageFoodieExperience): '0' ;
  //     echo "FoodieExperience updated to '$averageFoodieExperience'!\n";
  //     //
  //     mysql_update('listings',$listing['num'], null, array('average_rating' => $averageRating, 'average_foodie_experience' => round($averageFoodieExperience) ) );
  //   }
  //   $limit += $group;
  // }


  echo "\nUpdating listings stats...\n";
  $limit       = 0;
  $group       = 500;
  $rank        = 0;
  $currentRank = 1;
  $lastPoints  = -4;
  while(true){
    echo "\r\nGetting batch $limit, $group\n";
    $listings = mysql_select('listings', "TRUE ORDER BY `points` * 1 DESC, `createdDate` DESC LIMIT $limit, $group");
    if(!$listings){ echo "No more records found!\n"; break; }
    foreach($listings as $listing){

      // $rank++;
      // if($listing['points'] != $lastPoints){
      //   $currentRank = $rank;
      // }
      // $lastPoints = $listing['points'];

      // $photoQuantity                = 0;
      $updateArray                  = array();
      // $updateArray['rank']          = $currentRank; 
      //$updateArray['total_ratings'] = mysql_count('ratings', "`listingsNum` = ".intval($listing['num']));
      // $updateArray['points']        = intval($listing['points']);
      //$updateArray['checkins']      = mysql_count('check_ins', "`listingsNum` = ".intval($listing['num']));
      // $updateArray['reviews']       = mysql_count('reviews', "`flagged` = 0 AND `listingsNum` = ".intval($listing['num']));
      //$updateArray['badge_count']   = mysql_count('user_badges', "`listingsNum` = ".intval($listing['num']));
      // $updateArray['photo_count']   = mysql_count('photo_uploads', "`flagged` = 0 AND `listingsNum` = '".intval($listing['num'])."'");
      //$updateArray['coupons']       = mysql_count('coupons_used', "`listingsNum` = ".intval($listing['num']));
      // $updateArray['followers']     = mysql_count('listings_follows', "`listingsNum` = ".intval($listing['num']));
      // $updateArray['following']     = mysql_count('listings_follows', "`membersNum` = ".intval($listing['membersNum']));
      // $updateArray['total_foodie_experience'] = mysql_count('foodie_experience', "`listingsNum` = ".intval($listing['num']));
      if(empty($listing['timezone'])){
        $updateArray['timezone']      = urbcan_getTimezone($listing['latitude'], $listing['longitude']);
      }

      if(count($updateArray)){
        mysql_update('listings',$listing['num'], null, $updateArray);
        echo "Updated stats for listing #{$listing['num']}\n";
      }

    }
    $limit += $group;
  }

  echo "\nUpdating Members stats...\n";
  $limit       = 0;
  $group       = 500;
  $rank        = 0;
  $currentRank = 1;
  $lastPoints  = -4;
  while(true){
    echo "\r\nGetting batch $limit, $group\n";
    $members = mysql_select('members', "TRUE AND isAdmin = 0 ORDER BY `points` * 1 DESC, `createdDate` DESC LIMIT $limit, $group");
    if(!$members){ echo "No more records found!\n"; break; }
    foreach($members as $member){
      $rank++;
      if($member['points'] != $lastPoints){
        $currentRank = $rank;
      }
      $lastPoints = $member['points'];      
      urbcan_updateMember($member, $currentRank);
    }
    $limit += $group;
  }

  // $sections = array('listings', 'members');
  // echo "\nUpdating Shares stats...\n";
  // foreach($sections as $section){
  //   $limit = 0;
  //   $group = 500;
  //   echo "Looping through records for $section section.\n";
  //   while(true){
  //     echo "\r\nGetting batch $limit, $group\n";
  //     $records = mysql_select($section, "TRUE ORDER BY `points` * 1 DESC, `createdDate` DESC LIMIT $limit, $group");
  //     if(!$records){ echo "No more records found!\n"; break; }
  //     foreach($records as $record){
  //       $updateArray = array('total_shares' => mysql_count('social_shares', "`section` = '$section' AND `recordNum` = '{$record['num']}'") );
  //       mysql_update($section, $record['num'], null, $updateArray);
  //       echo "Updated shares for record #{$record['num']}\n";
  //     }
  //     $limit += $group;
  //   }
  // }


  // echo "\nUpdating Photo stats...\n";
  // $limit       = 0;
  // $group       = 500;
  // while(true){
  //   echo "\r\nGetting batch $limit, $group\n";
  //   $photoUploads = mysql_select('photo_uploads', "TRUE ORDER BY `createdDate` DESC LIMIT $limit, $group");
  //   if(!$photoUploads){ echo "No more records found!\n"; break; }
  //   foreach($photoUploads as $photoUpload){
  //     echo "Updating photo #{$photoUpload['num']}\r\n";
  //     $likeCount = mysql_count('photo_likes', "`photo_uploadsNum` = '{$photoUpload['num']}'");
  //     mysql_update('photo_uploads', $photoUpload['num'], null, array('likes' => $likeCount));

  //   }
  //   $limit += $group;
  // }

  echo "SCRIPT COMPLETE!";

  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron
}


function updateListingAvgRating($listingsNum){
  // echo "updating rating #{$listing['num']}...\n";
  $ratings = mysql_select('ratings', "`listingsNum` = '$listingsNum'");
  $totalRating = 0;
  $totalRating = array_reduce($ratings, function($carry, $rating) {
    $carry += floatval($rating['rating']);
    return $carry;
  });
  $numberOfRatings = count($ratings);
  $averageRating   = ($numberOfRatings)? $totalRating / $numberOfRatings : '0' ;
  $averageRating   = ($averageRating)? urbcan_convertFloatToRating($averageRating): '0' ;
  // echo "Rating updated to '$averageRating'!\n";

  mysql_update('listings',$listingsNum, null, array('average_rating' => $averageRating) );

  return $averageRating;
}

//Abhishek : added average_foodie_experince
function updateListingAvgFoodieExperirence($listingsNum){
  // echo "updating foodie_experience #{$listing['num']}...\n";
  $foodieExperiences = mysql_select('foodie_experience', "`listingsNum` = '$listingsNum'");
  $totalFoodieExperience = 0;
  $totalFoodieExperience = array_reduce($foodieExperiences, function($carry, $rating) {
    $carry += floatval($rating['rating']);
    return $carry;
  });
  $numberOfFoodies = count($foodieExperiences);
  $averageFoodieExperience   = ($numberOfFoodies)? $totalFoodieExperience / $numberOfFoodies : '0' ;
  $averageFoodieExperience   = ($averageFoodieExperience)? urbcan_convertFloatToRating($averageFoodieExperience): '0' ;
  // echo "FoodieExperience updated to '$averageFoodieExperience'!\n";

  mysql_update('listings',$listingsNum, null, array('average_foodie_experience' => round($averageFoodieExperience)) );
}

addCronJob('urbcan_updateSiteMetaStats', "Update sites meta stats", '0 * * * *');             // Run every hour
// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
pluginAction_addHandlerAndLink(t('Update Sites meta stats'), 'urbcan_updateSiteMetaStats', 'admins');
function urbcan_updateSiteMetaStats($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive


  $updateArray              = [
    'updatedDate'            => date('Y-m-d H:i:s'),
    'ios_users'              => mysql_count('man_mobile_devices', "`platform` = 'iOS'"),
    'android_users'          => mysql_count('man_mobile_devices', "`platform` = 'Android'"),
    'sms_invites'            => mysql_count('pending_invite_messages', "`sent` = '1'"),
    'newsletter_subscribers' => mysql_count('_nlb_subscribers', "`confirmed` = '1'"),
    'shared_content'         => mysql_count('social_shares'),
    'check_ins'              => mysql_count('check_ins'),
    'tips'                   => mysql_count('reviews'),
    'rated'                  => mysql_count('ratings'),
    'photo_uploads'          => mysql_count('photo_uploads', "`for_photo` = 'photo'"),
    'certificate_uploads'    => mysql_count('photo_uploads', "`for_photo` = 'certificate' "),
    'photo_likes'            => mysql_count('photo_likes'),
    'badges_earned'          => mysql_count('user_badges'),
    'coupons_redeemed'       => mysql_count('coupons_used'),
    'menu_items'             => mysql_count('menu'),
    'all_users'              => mysql_count('members')
  ];

  mysql_update('dashboard_stats','1', null, $updateArray);
  if($includeComments){ echo "Updated site wide meta stats\r\n"; }

  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron

}

function urbcan_convertFloatToRating($float){
  $float  = floatval($float);
  $number = $float / 0.5;
  $number = round($number);
  $number = $number * 0.5;
  return $number;

}

//get timezone from latitude and longitude
//Function from this post: http://stackoverflow.com/questions/3126878/get-php-timezone-name-from-latitude-and-longitude
function urbcan_getTimezone($latitude, $longitude, $country_code = '') {
  $timezone_ids = ($country_code) ? DateTimeZone::listIdentifiers(DateTimeZone::PER_COUNTRY, $country_code) : DateTimeZone::listIdentifiers();
  if(!$latitude)  { return 'America/Los_Angeles'; }
  if(!$longitude) { return 'America/Los_Angeles'; }

  if($timezone_ids && is_array($timezone_ids) && isset($timezone_ids[0])) {
    $time_zone = '';
    $tz_distance = 0;
    //only one identifier?
    if (count($timezone_ids) == 1) {
      $time_zone = $timezone_ids[0];
    }else{
      foreach($timezone_ids as $timezone_id) {
        $timezone = new DateTimeZone($timezone_id);
        $location = $timezone->getLocation();
        $tz_lat   = $location['latitude'];
        $tz_long  = $location['longitude'];

        $theta    = $longitude - $tz_long;
        $distance = (sin(deg2rad($latitude)) * sin(deg2rad($tz_lat))) 
        + (cos(deg2rad($latitude)) * cos(deg2rad($tz_lat)) * cos(deg2rad($theta)));
        $distance = acos($distance);
        $distance = abs(rad2deg($distance));
        if (!$time_zone || $tz_distance > $distance) {
          $time_zone   = $timezone_id;
          $tz_distance = $distance;
        } 
      }
    }
    return  $time_zone;
  }
  return 'America/Los_Angeles';

}

addCronJob('sendPendingInvites', "Send Pending Invites", '* * * * *');             // Run every hour

// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
pluginAction_addHandlerAndLink(t('Send Pending Invites'), 'sendPendingInvites', 'admins');

function sendPendingInvites(){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive
  
  $generalSettings = mysql_get('general_settings', '1');
  $limit           = 500;
  $batch           = 0;
  $smsContent      = $generalSettings['join_sms_content'];
  $date            = date('Y-m-d H:i:s');

  echo "Collecting pending invites...\n";

  while(true){

    echo "Getting batch $batch, $limit...\n";
    $pendingInvites = mysql_select('pending_invite_messages', "`sent` = 0 LIMIT $batch, $limit");
    if(!$pendingInvites){ echo "No more pending invites found!\n"; break; }
    else{ echo "Batch found, looping through results...\n"; }

    foreach($pendingInvites as $invite){

      $user = mysql_get('members', $invite['membersNum']);

      echo "Sending invite #{$invite['num']}\n";
      
      if($invite['cell']){  
        // $number = formatCellNumber($invite['cell']);
        $number = $invite['cell'];
        if($number && $GLOBALS['API_CHECK_INVITE_ALREADY_SENT'] && !mysql_count('pending_invite_messages', "`sent` = '1' AND `cell` = '".mysqli_real_escape_string(mysqli(), $number)."'") ){
          echo "Sending invite via SMS to {$invite['cell']}\n";
          
          $message = str_replace("#name#", $invite['name'], $smsContent);
          $message = str_replace("#sender_name#", @$user['facebook_first_name']." ".@$user['facebook_last_name'], $message);
          // twilio_sendSMS($number, $message, array());
          sendSMS($number, $message);
          $insertData                       = array();
          $insertData['createdDate']        = $date;
          $insertData['createdByUserNum']   = $invite['membersNum'];
          $insertData['updatedDate']        = $date;
          $insertData['updatedByUserNum']   = $invite['membersNum'];
          $insertData['membersNum']         = $invite['membersNum'];
          $insertData['phone_number']       = $number;
          $insertData['message']            = $smsContent;
          $insertData['ip_address_of_user'] = $invite['ip_address_of_user'];
          mysql_insert('promotion_sms_log', $insertData);
          echo "Successfully sent SMS message to $number\n";
        }
      }

      // INVITE-USER
      if($invite['email']) {
        echo "Sending invite via email\n";

        list($productOne, $productTwo, $productThree, $productFour) = getCardHtml();

        $feedData = mysql_select('feed', "`section` = 'orders' ORDER BY `action_date` DESC LIMIT 3");

        $feedHtml = getRecentOrderFeed($feedData);

        // $feeds = mysql_select('feed', "`section` = 'photo_uploads' ORDER BY `action_date` DESC LIMIT 0,9");
        // $foodie_moments = '';
        // foreach ($feeds as $feed) {
        //   $record = json_decode($feed['json'], true);
        //   $foodie_moments .='<img  src="'.$record['photos'][0]['thumbUrlPath'].'" alt="" width="100" height="100" />';
        // }

        // $query = 'SELECT REPLACE(LOWER(cuisine)," ","-") as cuisine,count(num) as cuisine_count FROm urbanhal_listings WHERE cuisine != "" GROUP BY cuisine';
        //   $cuisines = mysql_select_query($query);
        //   // echo"<pre>";print_r($cuisines);echo"</pre>";
        // $listingsCuisineCount = [];
        // foreach ($cuisines as $cuisine) {
        //   $listingsCuisineCount[$cuisine['cuisine']] = $cuisine['cuisine_count'];
        // }

        $senderName = @$user['facebook_first_name']." ".@$user['facebook_last_name'][0];

        // $placeholders = array_merge(["foodie_moments" => $foodie_moments], $listingsCuisineCount, ['email' => $invite['email'], "name" => $invite['name'], "sender_name" => $senderName]);

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

        $placeholders = array_merge(['email' => $invite['email'], "name" => $invite['name'], "sender_name" => $senderName], ['productOne' => $productOne, 'productTwo' => $productTwo, 'productThree' => $productThree, 'productFour' => $productFour, 'feedHtml' => $feedHtml, 'unsubscribe_url' => $unsubUrl]);
        
        $emailHeaders = emailTemplate_loadFromDB(array(
          'template_id'  => 'INVITE-USER',
          'placeholders' => $placeholders,
        ));
        $mailErrors = sendMessage($emailHeaders);
        if ($mailErrors) { echo "Mail Error: $mailErrors.\n"; }
        else             { echo "Email successfully sent to {$invite['email']}.\n"; }
      }
      mysql_update('pending_invite_messages', $invite['num'], null, array('sent' => '1', 'cell' => $number));
    }

    $batch += $limit;
  }
  echo "SCRIPT COMPLETE!";
  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron
}



// Note: This function is EXPERIMENTAL and may change in future
function api_searchMultipleTables($searchTables, $searchOptions) {
  global $VIEWER_NAME, $TABLE_PREFIX;
  $VIEWER_NAME = "Search Multiple Tables";

  # error checking
  if (!@$searchOptions['perPage'])  { die("$VIEWER_NAME : No perPage option specified!\n"); }

  ### create subqueries
  $subqueries = array();
  foreach ($searchTables as $tablename => $tableOptions) {
    foreach (array('viewerUrl', 'searchFields', 'titleField') as $optionName) {
      if (!@$tableOptions[$optionName]) { die("$VIEWER_NAME : No '$optionName' option specified for searchTable '" .htmlencode($tablename). "'!\n"); }
    }

    // get search fields
    $searchFieldsCSV   = '';
    foreach ($tableOptions['searchFields'] as $fieldname) {
      if ($searchFieldsCSV) { $searchFieldsCSV .= ", "; }
      $searchFieldsCSV .= "`" . mysql_escape($fieldname) . "`";
    }

    // create query
    $fullEscapedTable = mysql_escape($TABLE_PREFIX . $tablename);
    $schema           = loadSchema($tablename);
    $where            = _addWhereConditionsForSpecialFields($schema, '', $searchOptions);
    $subquery         = "SELECT '$tablename' as `tablename`, num, `{$tableOptions['titleField']}` as `_title`, ";
    if (@$tableOptions['summaryField']) { $subquery .= "`{$tableOptions['summaryField']}` as `_summary`, "; }
    else                                { $subquery .= "'' as `_summary`, "; }
    foreach (range(1,10) as $num) {
      $fieldname = "field$num";
      if (@$tableOptions["field$num"]) { $subquery .= "`{$tableOptions[$fieldname]}` as `$fieldname`, "; }
      else                             { $subquery .= "'' as `$fieldname`, "; }
    }
    $subquery        .= "CONCAT_WS('\\t', $searchFieldsCSV) as _content FROM `$fullEscapedTable` $where\n";

    $subqueries[] = $subquery;
  }

  # create query
  $schema = array('_content' => array()); // allow this field to be searched in _getWhereForSearchQuery
  $where  = _getWhereForSearchQuery($searchOptions['keywords'], array('_content'), $schema);
  $query       = "SELECT SQL_CALC_FOUND_ROWS * FROM (\n  " .implode('  UNION ', $subqueries). ") as combinedTable\n";
  if ($where) { $query .= "WHERE $where"; }
  if (@$searchOptions['orderBy']) { $query .= " ORDER BY ".$searchOptions['orderBy'] ." "; }
  $query      .= mysql_limit($searchOptions['perPage'], @$_REQUEST['page']);

  #

  ## execute query
  $rows = array();
  if ($searchOptions['keywords'] && $where) {
    if (@$searchOptions['debugSql']) { print "<xmp>$query</xmp>"; }
    $result     = mysql_query($query) or die("$VIEWER_NAME: MySQL Error: ". htmlencode(mysql_error()) . "\n");

    while ($record = mysql_fetch_assoc($result)) {
      $detailUrl       = $searchTables[$record['tablename']]['viewerUrl'];
      $filenameValue   = ''; // not working yet... getFilenameFieldValue($record, $searchTables[$record['tablename']]['filenameFields']);
      $useSeoUrls      = false;
      $link            = _getLink($detailUrl, $filenameValue, $record['num'], $useSeoUrls);

      $record['_title']   = $record['_title'];
      $record['_summary'] = strip_tags($record['_summary']);
      $record['_link']    = $link;

      array_push($rows, $record);
    }


  }

  $searchOptions['pageNum'] = @$_REQUEST['page'];
  $listDetails = _getListDetails($searchOptions, count($rows));

  //
  return array($rows, $listDetails);
}


// addCronJob('updateFeed', "Update the User Feed", '* * * * *');             // Run every hour

// // Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
// pluginAction_addHandlerAndLink(t('Update the User Feed'), 'updateFeed', 'admins');

// function updateFeed(){

//   include 'lib/viewer_functions.php';

//   if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
//     if (!headers_sent()) { 
//       header("Content-type: text/plain");
//       header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
//       ob_disable();              // Turn off browser buffering
//     }
//     // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
//     // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
//     // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
//     ignore_user_abort( false ); // continue running even if user clicks stop on their browser
//     session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
//   }
//   set_time_limit(0);  // ignore PHP's max_execution_time directive


//   echo "UPDATING MASTER FEED\r\n";


//   $sections = ['coupons_used' ,'user_follows', 'photo_uploads', 'photo_likes', 'user_badges', 'reviews', 'check_ins', 'ratings', 'listings_follows', 'foodie_experience'];

//   foreach($sections as $section){
//     echo "\r\nGetting $section and adding to feed...\r\n";

//     $sectionRules  = api_getSectionRules($section);
//     $schemaFields  = getSchemaFields($section);
//     $displayFields = array();
//     if($sectionRules['display_fields']){
//       $displayFields = explode(",", $sectionRules['display_fields']);
//       foreach ($displayFields as $key => $field) { $displayFields[$key] = trim($field); }
//     }

//     $pageNum = 1;
//     $lastNum = 0;

//     $leftJoin = [];
//     if(@$schemaFields['membersNum']){
//       $leftJoin['members'] = 'membersNum';
//     }
//     if(@$schemaFields['listingsNum']){
//       $leftJoin['listings'] = 'listingsNum';
//     }

//     if(@$schemaFields['badgesNum']){
//       $leftJoin['badges'] = 'badgesNum';
//     }

//     while(true){
//       $date = date('Y-m-d H:i:s');

//       $recordOptions = array(
//         'tableName'     => $section,
//         'perPage'       => '150',
//         'loadUploads'   => true,
//         'allowSearch'   => false,
//         'pageNum'       => $pageNum,
//         'leftJoin'      => $leftJoin,
//         'loadCreatedBy' => false,
//       );

//       //Abhishek :- add where condition to filter out flagged records
//       if(in_array($section, array("photo_uploads","photo_likes","reviews"))){
//         $recordOptions['where'] = "$section.`flagged` = 0";
//       }

//       list($records, $reviewsMeta) = getRecords($recordOptions);

//       if(!$records){ echo "No more records found for $section!\n"; break; }
//       foreach($records as $key => $record){

//         if($section != 'ratings' && mysql_count('feed', "`section` = '$section' AND `recordNum` = '".mysqli_real_escape_string(mysqli(), $record['num'])."'")){

//           echo "$section {$record['num']} exists \n";

//           continue;
//         }

//         if($key == 0){
//           if($lastNum == $record['num']){ break 2; }
//           $lastNum = $record['num'];
//         }

//         // Filter the data if display fields have been set
//         if($displayFields){
//           $data = array();
//           foreach($displayFields as $field){
//             $data[$field] = @$record[$field];
//           }
//         // Otherwise return all data
//         }else{
//           $data = $record;
//         }


//         //If we're dealing with earn a badge, add the badge image. 
//         if($section == 'user_badges' && $record['badgesNum']){
//           $data['badges.completed_image'] = getUploadRecords('badges', 'completed_image', $record['badgesNum']);
//           $data['badges.gif_badge']       = getUploadRecords('badges', 'gif_badge', $record['badgesNum']);  
//         }

//         if($section == 'listings_follows' && $record['listingsNum']){
//           $data['listings.logo']         = getUploadRecords('listings', 'logo', $record['listingsNum']); 
//           $data['listings.header_image'] = getUploadRecords('listings', 'header_image', $record['listingsNum']); 
//         }

//         if($section == 'photo_likes' && @$record['photo_uploadsNum']){
//           $data['photo_uploads.photos'] = getUploadRecords('photo_uploads', 'photos', $record['photo_uploadsNum']); 
//         }

//         if($section == 'user_follows' && $record['membersNum']){
//           $data['members.photos'] = getUploadRecords('members', 'photo', $record['membersNum']); 
//           $followingMember        = mysql_get('members',$record['followingNum']);
//           $require_fields = ["facebook_first_name", "facebook_last_name", "facebook_picture", "reviews", "followers", "check_ins","facebook_gender",'username'];
//           if($followingMember){
//             foreach($followingMember as $field => $value){
//               if(in_array($field, $require_fields))
//                   $data['user_following.'.$field] = $value;
//             }
//           }
//         }

//         if($section == 'photo_uploads' && count($data['photos']) <=0 ) {
//           continue;
//         }

//         $recordData = [
//           'updatedDate'      => $date,
//           'updatedByUserNum' => '0',
//           'section'          => $section,
//           'membersNum'       => $record['membersNum'],
//           'json'             => json_encode($data),
//         ];

//         if(mysql_count('feed', "`section` = '$section' AND `recordNum` = '".mysqli_real_escape_string(mysqli(), $record['num'])."'")){
//           echo "Updating $section #{$record['num']} to feed\r\n";
//           mysql_update('feed', null, "`section` = '$section' AND `recordNum` = '".mysqli_real_escape_string(mysqli(), $record['num'])."'", $recordData);
//         }else{
//           $recordData['createdDate']      = $date;
//           $recordData['createdByUserNum'] = '0';
//           $recordData['recordNum']        = $record['num'];
//           $recordData['action_date']      = $record['createdDate'];
//           echo "Adding $section #{$record['num']} to feed\r\n";
//           mysql_insert('feed', $recordData);
//         }
//       }
//       if(count($records) < 150 ){ echo "No more records found for $section!\n"; break; }
//       $pageNum++;
//     }
//   }

//   // return summary message
//   echo "\r\n\r\nSCRIPT COMPLETED SUCCESSFULLY!\r\n";
//   $summary = "Successful";
//   if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
//   return $summary;  // otherwise, return summary if being run by cron
// }




//addCronJob('urbcan_whatsNewEmail', "Send 2 week warning emails.", '30 6 * * 4');             // Run every hour
// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
pluginAction_addHandlerAndLink(t('Send 2 week warning emails.'), 'urbcan_whatsNewEmail', 'admins');
function urbcan_whatsNewEmail(){


  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( false ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive
  

  echo "Sending 2 week drip marketing emails.\r\n";
  $endDate   = date('Y-m-d 00:00:00', strtotime("-2 weeks"));
  $startDate = date('Y-m-d 23:59:59', strtotime("-3 weeks"));
  $members   = mysql_select('members', "`lastLoginDate` >= '$startDate' AND `lastLoginDate` <= '$endDate'");

  list($productOne, $productTwo, $productThree, $productFour) = getCardHtml();

  $feedData = mysql_select('feed', "`section` = 'orders' ORDER BY `action_date` DESC LIMIT 3");

  $feedHtml = getRecentOrderFeed($feedData);

  foreach ($members as $key => $member) {

    if($member['facebook_email']){
      echo "Sending weekly reminder to member #{$member['num']}...\r\n";

      $fbName = $member['facebook_first_name'];

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

        $fbName = $member['username'];

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

        $fbName = $member['facebook_email'];

      }

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

      $placeholders = array('productOne' => $productOne, 'productTwo' => $productTwo, 'productThree' => $productThree, 'productFour' => $productFour, 'feedHtml' => $feedHtml, 'facebook_picture' => $member['facebook_picture'], 'username' => $member['username'], 'facebook_email' => $member['facebook_email'], 'facebook_first_name' => $fbName, 'facebook_last_name' => $member['facebook_last_name'], 'unsubscribe_url' => $unsubUrl); 

      // 2-WEEK-REMINDER
      $emailHeaders = emailTemplate_loadFromDB(array(
        'template_id'  => '2-WEEK-REMINDER',
        'placeholders' => $placeholders,
      ));
      //print_r($emailHeaders);exit();
      $mailErrors = sendMessage($emailHeaders);
      if ($mailErrors) { echo("Mail Errors: $mailErrors\r\n"); }
      else{ echo "Message Sent\r\n"; }
    }else{
      echo "Member #{$member['num']} does not have email...\r\n";
    }
  }

  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron

}


addCronJob('urbcan_whatsNewEmailMonth', "Send 1 month warning emails.", '30 6 * * 4');             // Run every thursday at 6:30 AM
// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
pluginAction_addHandlerAndLink(t('Send 1 month warning emails.'), 'urbcan_whatsNewEmailMonth', 'admins');
function urbcan_whatsNewEmailMonth(){


  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( false ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive
  

  echo "Sending 1 month drip marketing emails.\r\n";
  $endDate   = date('Y-m-d 00:00:00', strtotime("-1 month"));
  $startDate = date('Y-m-d 23:59:59', strtotime("-35 days"));
  $members   = mysql_select('members', "`lastLoginDate` >= '$startDate' AND `lastLoginDate` <= '$endDate' AND isAdmin = 0", "`facebook_picture`, `facebook_first_name`, `facebook_last_name`, `username`, `num`, `isAdmin`, `facebook_email`");

  list($productOne, $productTwo, $productThree, $productFour) = getCardHtml();

  $feedData = mysql_select('feed', "`section` = 'photo_uploads' ORDER BY `action_date` DESC LIMIT 3", "`json`");

  $orderFeedData = mysql_select('feed', "`section` = 'orders' ORDER BY `action_date` DESC LIMIT 3");

  $orderFeedHtml = getRecentOrderFeed($orderFeedData);
  
  $feedHtml = addPhotoSnapData($feedData);

  foreach ($members as $key => $member) {

    if($member['facebook_email']){
      echo "Sending monthly reminder to member #{$member['num']}...\r\n";

      $fbName = $member['facebook_first_name'];

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

        $fbName = $member['username'];

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

        $fbName = $member['facebook_email'];

      }

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

      $placeholders = array('productOne' => $productOne, 'productTwo' => $productTwo, 'productThree' => $productThree, 'productFour' => $productFour, 'orderFeedHtml' => $orderFeedHtml,'feedHtml' => $feedHtml, 'facebook_picture' => $member['facebook_picture'], 'username' => $member['username'], 'facebook_email' => $member['facebook_email'], 'facebook_first_name' => $fbName, 'facebook_last_name' => $member['facebook_last_name'], 'unsubscribe_url' => $unsubUrl);



      // 1-MONTH-REMINDER
      $emailHeaders = emailTemplate_loadFromDB(array(
        'template_id'  => '1-MONTH-REMINDER',
        'placeholders' => $placeholders,
      ));

      $mailErrors = sendMessage($emailHeaders);
      if ($mailErrors) { echo("Mail Errors: $mailErrors\r\n"); }
      else{ echo "Message Sent\r\n"; }
    }else{
      echo "Member #{$member['num']} does not have email...\r\n";
    }
  }

  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron

}


function addPhotoSnapData($feedData){

  $feedHtml = "";

  foreach($feedData as $key => $feed){

    $feed = json_decode($feed['json'], true);

      // $isLiked = mysql_count('photo_likes', "`membersNum` = '".intval($memberNum)."' AND `photo_uploadsNum` = ".intval($feed['num']) );
      // $isliked = $isLiked ? "1" : "0";

    $member = mysql_get('members', $feed['membersNum'], null, "`facebook_picture`, `facebook_first_name`, `facebook_last_name`, `username`, `num`, `isAdmin`");

    $members_likes_count = strval(mysql_count('photo_likes', "`photo_uploadsNum` = ".intval($feed['num'])));

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

    $feedActionText = "Snaps a moment";

      // add listing name to uploaded by if photo uploaded by admin
    if($member['isAdmin']){
      $listing = mysql_get('listings', $feed['listingsNum'], null, "`name`");
      $member['facebook_first_name'] = $listing['name'];
      $member['facebook_last_name']  = '';
      $member['facebook_picture']    = $feed['photos'][0]['thumbUrlPath3'];
      $member['username']            = $listing['name'];
      $member['num']                 = $feed['listingsNum'];
      $feedActionText = "Shares a moment";
    }


    $feedHtml .= '<tr>
    <td align="center" style="padding: 10px 0 0">
    <table cellspacing="0" cellpadding="0" style="" width="300">
    <tbody>
    <tr>
    <td style="padding: 0 5px 0 0;" width="35">
    <img width="30" height="30" src="'.$member['facebook_picture'].'" style="border-radius: 50%;" /></td>
    <td style="font-size:14px;" width="230">
    <p style="margin:0;line-height: 12px;"><b>'.$member['username'].'</b></p>
    <p style="font-size: 11px;margin:0;">'.$feedActionText.'</p>
    </td>
    <td align="left" style="color: #5bbc2e; font-size: 12px;" width="25">
    <img style="vertical-align: middle;" src="https://s3-us-west-1.amazonaws.com/urban-halal/email-newsletter/images/camera-small.png" />
    </td>
    <td width="10">25</td>
    </tr>
    <tr>
    <td height="20"></td>
    </tr>
    <tr>
    <td colspan="4">
    <img src="'.$feed['photos'][0]['thumbUrlPath'].'" width="300" height="300" style="background-color: #ddd;border-radius: 5px;" />
    </td>
    </tr>
    </tbody>
    </table></td>
    </tr>';
  }

  return $feedHtml;
}


function urbcan_getFriendNumsFriendMeta($member) {
  $returnArray = [];
  
  //Check if the user is following
  $fullTableName   = getTableNameWithPrefix('user_follows');
  $query           = "SELECT `followingNum` FROM `$fullTableName` WHERE `membersNum` = '".$member['num']."' ";
  $records         = mysql_select_query($query);
  foreach($records as $record) {
    if(!in_array($record['followingNum'], $returnArray)){
      $returnArray[] = $record['followingNum'];
    }
  }
  if($member['facebook_user_friends']) {
    $facebookFriends   = json_decode($member['facebook_user_friends'], true);
    $facebookFriendIds = array_keys($facebookFriends);
    $fullTableName     = getTableNameWithPrefix('members');
    $query             = "SELECT `num` FROM `$fullTableName` WHERE `facebook_id` IN(".mysql_escapeCSV($facebookFriendIds).") ";
    $records           = mysql_select_query($query);
    foreach($records as $record) {
      if(!in_array($record['num'], $returnArray)){
        $returnArray[] = $record['num'];
      }
    }
  }
  return $returnArray;
}

//addCronJob('urbcan_updateFacebookFriends', "Update All Users Facebook Friends Meta Data", '45 * * * *'); // Run every hour
// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
//pluginAction_addHandlerAndLink(t('Update all users Facebook Friends Meta Data'), 'urbcan_updateFacebookFriends', 'admins');

// this function is called by cron, and logged under: Admin > General > Background Tasks
// return()'d content is logged as "Summary" and and print/echo content is logged as "output"
function urbcan_updateFacebookFriends() {
  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive

  echo "\nUpdating Members Friends...\n";

  include_once('api-functions.php');
  include_once('api-custom.php');
  $limit       = 0;
  $group       = 500;

  while(true){
    echo "\r\nGetting batch $limit, $group\n";
    $members = mysql_select('members', "TRUE ORDER BY `createdDate` DESC LIMIT $limit, $group");
    if(!$members){ echo "No more records found!\n"; break; }
    foreach($members as $member){

      list($validToken, $error) = api_verifyFacebookToken($member['facebook_access_token'], $member['facebook_id']);
      if($validToken){
        $userFriends = facebookUtil_getFacebookFriends($member['facebook_id'], $member['facebook_access_token']);
        if($userFriends){
          echo "Friends returned for user #{$member['num']}\r\n";
          mysql_update('members', $member['num'], null, array('facebook_user_friends' => json_encode($userFriends)));
        }
      }else{
        echo "Token not valid for user #{$member['num']}: $error\r\n";
      }
    }
    $limit += $group;
  }

  echo "SCRIPT COMPLETE!";

  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron
}

addCronJob('urbcan_assignBadges', "Assign Badges to all users", '0-3 * * * *'); // Run every hour
// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
pluginAction_addHandlerAndLink(t('Assign Badges to all users'), 'urbcan_assignBadges', 'admins');

// this function is called by cron, and logged under: Admin > General > Background Tasks
// return()'d content is logged as "Summary" and and print/echo content is logged as "output"
function urbcan_assignBadges(){
  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive
  include_once("lib/viewer_functions.php");
  include_once('api-custom.php');
  echo "\nAssigning badges to members...\n";  

  $limit = 0;
  $group = 500;
  $testUser = 1;
  while(true){
    echo "\r\nGetting batch $limit, $group\n";
    $members = mysql_select('members', "TRUE AND isAdmin = 0 ORDER BY `points` * 1 ASC, `createdDate` ASC LIMIT $limit, $group");
    if(!$members){ echo "No more records found!\n"; break; }
    foreach($members as $member){
      
      $badge_type = "default";
      echo "Assigning points badges\n";
      switch(true){
        
        case ($member['points'] >= 1000 && $member['points'] < 5000):
        $badge_type = "RISING STAR";
        break;

        case ($member['points'] >= 5000 && $member['points'] < 10000):
        $badge_type = "PROFESSIONAL";
        break;

        case ($member['points'] >= 10000):
        $badge_type = "G.O.A.T";
        break;

      }//switch

      if($badge_type != 'default') {
        insertBadgeData($badge_type, $member);
      }

      echo "Assigning invited 5 user badge\n";
      $badge_type = "CONNOISSUER"; // change in api-custom.php for memebrs api
      $inviteCount = mysql_count("pending_invite_messages", "`membersNum` = ".intval($member['num']));
      
      if($inviteCount >= 5){
        insertBadgeData($badge_type, $member);
      }

      // echo "Assigning beta test user badge\n";
      // $badge_type = "BETA TEST USER";

      // if($testUser <= 25) { // assign badge for 25 test user
      //   insertBadgeData($badge_type, $member);
      //   $testUser++;
      // }

      // echo "Assigning level up badge\n";
      // $badge_type = "All Actions Complete Badge";

      // $likes_count   = mysql_count('photo_likes', "`membersNum` = ".intval($member['num']));
      // $invites_count = mysql_count('pending_invite_messages', "`membersNum` = ".intval($member['num']));
      // $survey_count  = mysql_count('foodie_experience', "`membersNum` = ".intval($member['num']));

      // if($member['ratings'] >=1 && $member['reviews'] >=1 && $member['check_ins'] >= 1 && $member['photo_count'] >=1 && $member['certificate_count'] >=1 && $likes_count >=1 && $invites_count >=1 && $survey_count >= 1 ) {
      
      //   insertBadgeData($badge_type, $member);
      
      // }

      echo "Assigning frequent foodie checkins badge\n";
      $badge_type = "EXPLORER";
      if($member['check_ins'] >= 10) {
        insertBadgeData($badge_type, $member);
      }

      echo "Assigning frequent foodie reviews badge\n";
      $badge_type = "FIRST TIMER";
      if($member['reviews'] >= 10) {
        insertBadgeData($badge_type, $member);
      }

      echo "Assigning frequent foodie uploads badge\n";
      $badge_type = "SHUTTERBUG";
      if($member['photo_count'] >= 10) {
        insertBadgeData($badge_type, $member);
      }

      echo "Assigning Milestone checkins badge\n";
      $badge_type = "TREKKER";
      if($member['check_ins'] >= 50) {
        insertBadgeData($badge_type, $member);
      }

      echo "Assigning FREQUENT FOODIE reviews badge\n";
      $badge_type = "WORDSMITH";
      if($member['reviews'] >= 50) {
        insertBadgeData($badge_type, $member);
      }

      echo "Assigning FREQUENT FOODIE uploads badge\n";
      $badge_type = "VISUAL ARTIST";
      if($member['photo_count'] >= 50) {
        insertBadgeData($badge_type, $member);
      }

      echo "Assigning FREQUENT FOODIE 100 checkins badge\n";
      $badge_type = "ADVENTURER";
      if($member['check_ins'] >= 100) {
        insertBadgeData($badge_type, $member);
      }

      echo "Assigning FREQUENT FOODIE 100 reviews badge\n";
      $badge_type = "INFLUENCER";
      if($member['reviews'] >= 100) {
        insertBadgeData($badge_type, $member);
      }

      echo "Assigning FREQUENT FOODIE 100 uploads badge\n";
      $badge_type = "CINEMATOGRAPHER";
      if($member['photo_count'] >= 100) {
        insertBadgeData($badge_type, $member);
      }

    } // members loop
    $limit += $group;
  } // while loop
  echo "SCRIPT COMPLETE!";

  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron
}

function insertBadgeData($badge_type, $member){
  $continue = false;
  // load record from 'badges'
  list($badgesRecords, $badgesMetaData) = getRecords(array(
    'tableName'   => 'badges',
    'where'       => "`badge_type` = '".$badge_type."'",
    'loadUploads' => true,
    'allowSearch' => false,
    'limit'       => '1',
  ));
  
  $badge = @$badgesRecords[0]; // get first record
  if(!$badge) { echo "Badge not found of type $badge_type\r\n"; return true; }
  
  if(!mysql_count('user_badges', "`membersNum` = ".intval($member['num'])." AND `badgesNum` = ".intval($badge['num'])))
  {
    // $pointSettings = mysql_get('points_system', '1');

    $date = date('Y-m-d H:i:s');
    $insertData                     = array();
    $insertData['createdDate']      = $date;
    $insertData['createdByUserNum'] = $member['num'];
    $insertData['updatedDate']      = $date;
    $insertData['updatedByUserNum'] = $member['num'];
    $insertData['membersNum']       = $member['num'];
    $insertData['badgesNum']        = $badge['num'];
    $insertData['points']           = $badge['points'];
    $badgeNum = mysql_insert('user_badges', $insertData, true);
    
    $total_badges = mysql_count('user_badges', "`membersNum` = ".intval($member['num']));

    mysql_update('members', $member['num'], null, array('points' => intval($badge['points'])+intval($member['points']), 'badge_count' => $total_badges ) );

    echo "Badge $badge_type Assigned to user {$member['num']}\r\n";

    // add push notification data

    $badge_image = $badge['completed_image'][0]['urlPath'];
    if($badge_type == "CONNOISSUER" && count($badge['completed_image']) > 1){
      $badge_image = $badge['completed_image'][1]['urlPath'];
    }
    $badge_gif_image = "";
    if(count($badge['gif_badge'])){
      $badge_gif_image = $badge['gif_badge'][0]['urlPath'];
    }

    $shareTexts   = mysql_get('share_texts', '1');
    $placeholders = array("#userName" => $member['username'], "#badgeName" => $badge['badge_name']);
    $msg          = str_replace(array_keys($placeholders), array_values($placeholders), $shareTexts['badge_notify_text']);
    
    $notifyData = [ 'num' => $badge['num'], 'badge_name' => $badge['badge_name'],'badge_description' => $badge['badge_description'], 'success_text' => $badge['success_text'],'badge_gif_image' => $badge_gif_image,'badge_image' => $badge_image, 'points' => $badge['points'], 'notification_type' => 'badges', 'userName' => $member['username'],'firstName' => $member['facebook_first_name'], 'userId' => $member['num'] ];
    $inserData = ['app_id' => 'urbanhalal.com', 'message' => $msg, 'to' => 'userNum', 'to_userNum' => $member['num'], 'notification_type' => 'badges', 'notify_data' => json_encode($notifyData), 'createdDate' => date("Y-m-d H:i:s")];
    $notifyNum = mysql_insert('man_push_notifications', $inserData, true);
    //
    
    if($member['facebook_email']){

      $fbName = $member['facebook_first_name'];

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

        $fbName = $member['username'];

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

        $fbName = $member['facebook_email'];

      }

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

      $placeholders = [];
      $placeholders['badge_name']          = $badge["badge_name"];
      $placeholders['points']              = $badge["points"];
      $placeholders['badge_image']         = realUrl($badge_image);
      $placeholders['badge_description']   = $badge['badge_description'];
      $placeholders['facebook_email']      = $member['facebook_email'];
      $placeholders['username']            = $member['username'];
      $placeholders['facebook_first_name'] = $fbName;
      $placeholders['unsubscribe_url']     = $unsubUrl;

      $emailHeaders = emailTemplate_loadFromDB(array(
        'template_id'  => 'USER-EARNED-BADGE',
        'placeholders' => $placeholders,
      ));
      $mailErrors = sendMessage($emailHeaders);
      if ($mailErrors) { echo "Mail Error: $mailErrors\r\n"; }
      else{ echo "Mail Sent\r\n"; }
    }
  }
  return $continue;
}

//Abhishek
addCronJob('urbcan_blockedContent', "Update all blocked content.", '* * * * *');             // Run every minute
// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
pluginAction_addHandlerAndLink(t('Update all flagged content.'), 'urbcan_blockedContent', 'admins');
function urbcan_blockedContent(){


  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( false ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive
  

  echo "Update all flagged content.\r\n";
  
  echo "Flagging photos data...\r\n";

  $flaggedPhotos   = mysql_select('flagged_photos', "`blocked` = 1 AND `content_blocked` = 0");
  
  foreach ($flaggedPhotos as $key => $flaggedPhoto) {
    echo "Flagging photo_uploads #{$flaggedPhoto['recordNum']}...\r\n";
    
    $photo = mysql_get('photo_uploads', $flaggedPhoto['recordNum']);  

    mysql_update('photo_uploads', $flaggedPhoto['recordNum'], null, array('flagged'=>1));

    echo "Deleting photo_uploads #{$flaggedPhoto['recordNum']} feed...\r\n";
    mysql_delete("feed", null, mysql_escapef("`section` = ? AND `recordNum` = ? ",'photo_uploads', intval($flaggedPhoto['recordNum'])));

    echo "Flagging photo_likes #{$flaggedPhoto['recordNum']}...\r\n";
    
    $photoLikes = mysql_select("photo_likes", "`photo_uploadsNum` = ".intval($flaggedPhoto['recordNum']));

    foreach($photoLikes as $photoLike){
      mysql_update('photo_likes', $photoLike['num'], null, array('flagged'=>1));

      mysql_delete("feed", null, mysql_escapef("`section` = ? AND `recordNum` = ? ",'photo_likes', intval($photoLike['num'])));
    }

    $photoCount = mysql_count('photo_uploads', "`flagged` = 0 AND `listingsNum` = '".intval($photo['listingsNum'])."'");

    echo "Updating photo count of listing #{$photo['listingsNum']}....\r\n";
    mysql_update('listings', $photo['listingsNum'], null, array('photo_count' => $photoCount));

    $photoCount = mysql_count('photo_uploads', "`flagged` = 0 AND `membersNum` = ".intval($photo['membersNum']));
    
    echo "Updating photos count of member #{$photo['membersNum']}....\r\n";
    mysql_update('members', $photo['membersNum'], null, array('photo_count' => $photoCount));

    mysql_update('flagged_photos', $flaggedPhoto['num'], null, array('content_blocked'=>1));
    
  }

  echo "Flagging reviews data...\r\n";

  $flaggedReviews   = mysql_select('flagged_reviews', "`blocked` = 1 AND `content_blocked` = 0");
  
  foreach ($flaggedReviews as $key => $flaggedReview) {
    echo "Flagging reviews #{$flaggedReview['recordNum']}...\r\n";

    $review = mysql_get('reviews', $flaggedReview['recordNum']);

    mysql_update('reviews', $flaggedReview['recordNum'], null, array('flagged' => 1));

    echo "Deleting reviews #{$flaggedReview['recordNum']} feed...\r\n";
    mysql_delete("feed", null, mysql_escapef("`section` = ? AND `recordNum` = ? ",'reviews', intval($flaggedReview['recordNum'])));

    $reviewCount = mysql_count('reviews', "`flagged` = 0 AND `listingsNum` = ".intval($review['listingsNum']));
    
    echo "Updating reviews count of listing #{$review['listingsNum']}....\r\n";
    mysql_update('listings', $review['listingsNum'], null, array('reviews' => $reviewCount));

    $reviewCount = mysql_count('reviews', "`flagged` = 0 AND `membersNum` = ".intval($review['membersNum']));
    
    echo "Updating reviews count of member #{$review['membersNum']}....\r\n";
    mysql_update('members', $review['membersNum'], null, array('reviews' => $reviewCount));

    mysql_update('flagged_reviews', $flaggedReview['num'], null, array('content_blocked' => 1));
  }

  echo "Flagging member data...\r\n";

  $flaggedUsers   = mysql_select('flagged_users', "`blocked` = 1 AND `content_blocked` = 0");
  
  foreach ($flaggedUsers as $key => $flaggedUser) {
    echo "Flagging user #{$flaggedUser['recordNum']}...\r\n";
    mysql_update('members', $flaggedUser['recordNum'], null, array('flagged'=>1));

    mysql_update('flagged_users', $flaggedUser['num'], null, array('content_blocked'=>1));
  }

  echo "Flagging tags data...\r\n";

  $flaggedTags   = mysql_select('flagged_tags', "`blocked` = 1 AND `content_blocked` = 0");
  
  foreach ($flaggedTags as $key => $flaggedTag) {
    echo "Flagging tags #{$flaggedTag['recordNum']}...\r\n";
    mysql_update('tags', $flaggedTag['recordNum'], null, array('flagged'=>1));

    mysql_update('flagged_tags', $flaggedTag['num'], null, array('content_blocked'=>1));
  }

  echo "Flagging certs data...\r\n";

  $flaggedCerts   = mysql_select('flagged_certificates', "`blocked` = 1 AND `content_blocked` = 0");
  
  foreach ($flaggedCerts as $key => $flaggedCert) {
    echo "Flagging certs_uploads #{$flaggedCert['recordNum']}...\r\n";
    
    $cert = mysql_get('certs_uploads', $flaggedCert['recordNum']);  

    mysql_update('certs_uploads', $flaggedCert['recordNum'], null, array('flagged'=>1));

    echo "Deleting certs_uploads #{$flaggedCert['recordNum']} feed...\r\n";
    mysql_delete("feed", null, mysql_escapef("`section` = ? AND `recordNum` = ? ",'certs_uploads', intval($flaggedCert['recordNum'])));

    echo "Flagging cert_photo_likes #{$flaggedCert['recordNum']}...\r\n";
    
    $certLikes = mysql_select("cert_photo_likes", "`photo_uploadsNum` = ".intval($flaggedCert['recordNum']));

    foreach($certLikes as $certLike){
      mysql_update('cert_photo_likes', $certLike['num'], null, array('flagged'=>1));

      mysql_delete("feed", null, mysql_escapef("`section` = ? AND `recordNum` = ? ",'cert_photo_likes', intval($certLike['num'])));
    }

    $certCount = mysql_count('certs_uploads', "`flagged` = 0 AND `listingsNum` = '".intval($cert['listingsNum'])."'");

    echo "Updating certs count of listing #{$photo['listingsNum']}....\r\n";
    mysql_update('listings', $cert['listingsNum'], null, array('certs_count' => $certCount));

    $photoCount = mysql_count('certs_uploads', "`flagged` = 0 AND `membersNum` = ".intval($cert['membersNum']));
    
    // echo "Updating certs count of member #{$photo['membersNum']}....\r\n";
    // mysql_update('members', $photo['membersNum'], null, array('photo_count' => $photoCount));

    mysql_update('flagged_photos', $flaggedCert['num'], null, array('content_blocked'=>1));
    
  }

  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron

}

//addCronJob('urbcan_autopostData', "Twitter Facebook Autopost Data", '0 * * * *');             // Run every 1 hour

// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
//pluginAction_addHandlerAndLink(t('Autopost Data'), 'urbcan_autopostData', 'admins');
function urbcan_autopostData($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive
  
  //rating autpost feed
  // NOTE :- JAVED uncomment below code to autopost rating
  /*
  $ratings = mysql_select("ratings", "post_to_fb = 0 AND post_to_twitter = 0 AND rating = 5 order by createdDate desc LIMIT 1");

  foreach ($ratings as $key => $rating) {

    $photos    = mysql_select("photo_uploads", "listingsNum={$rating['listingsNum']} order by createdDate desc LIMIT 1");
    
    if(count($photos) > 0){
      foreach ($photos as $key => $photo) {
        list($photoUrl[],$tags) = getPhotoDetail($photo);
      }
    }else{
      $photoUrl[]  = 'https://s3-us-west-1.amazonaws.com/urban-halal/static_assets/landing_page/uh-default.png';
      $tags      = '';
    }

    $member  = mysql_get("members", $rating['membersNum'], null, "`username`");
    $listing = mysql_get("listings", $rating['listingsNum'], null, "`num`,`name`,`city`,`state`,`cuisine`,`address_1`");
    $text    = "{$member['username']} rates {$rating['rating']} stars\r\n#listingname";

    $text = formatPostData($listing, $tags, $text);
    postToFacebook($photoUrl,$text,"ratings", [$rating['num']]);
    postToTwitter($photoUrl, $text,'ratings',[$rating['num']]);

  }
  */
  
  //Photo Uploads
  // $listing = mysql_get("listings", null, "TRUE ORDER BY RAND() ASC", "`num`,`name`,`city`,`state`,`cuisine`, `address_1`,`tw_username`,`fb_username`");
  // $query = "SELECT `urbanhal_listings`.num,name,city,state,cuisine,address_1,fb_username,tw_username FROM urbanhal_listings INNER JOIN urbanhal_photo_uploads ON urbanhal_photo_uploads.listingsNum = urbanhal_listings.num WHERE `post_to_fb` = 0 AND `post_to_twitter` = 0 GROUP BY urbanhal_listings.num ORDER BY RAND() ASC LIMIT 1";
  // $listing = mysql_get_query($query); 
  $photos  = mysql_select("photo_uploads", "post_to_fb = 0 AND (membersNum != 44 OR num IN (SELECT photo_uploadsNum FROM urbanhal_photo_likes WHERE membersNum = 40)) order by createdDate desc LIMIT 1");
  
  if(count($photos) > 0){
    $photoUrl = [];$tags = "";$photoNum = [];$isAdminUpload=false;
    
    $listing = mysql_get("listings", $photos[0]['listingsNum'], null, "`num`,`name`,`city`,`state`,`cuisine`,`address_1`,`fb_username`, `tw_username`");

    foreach ($photos as $key => $photo) {
      
      list($photoUrl[],$tags,$isAdminUpload) = getPhotoDetail($photo);
      
      $autoPostData = replacePostText(true, $isAdminUpload, $listing);
      $text = formatPostData($listing, $tags, $autoPostData, true);
      
      $photoNum[] = $photo['num'];
    }

    postToFacebook($photoUrl, $text, "photo_uploads", $photoNum);
  }

  $photos  = mysql_select("photo_uploads", "post_to_twitter = 0 AND (membersNum != 44 OR num IN (SELECT photo_uploadsNum FROM urbanhal_photo_likes WHERE membersNum = 40)) order by createdDate desc LIMIT 3");
  if(count($photos) > 0){
    
    $listing = mysql_get("listings", $photos[0]['listingsNum'], null, "`num`,`name`,`city`,`state`,`cuisine`,`address_1`,`fb_username`, `tw_username`");

    $photoUrl = [];$tags = "";$photoNum = [];$isAdminUpload=false;
    foreach ($photos as $key => $photo) {
      
      list($photoUrl[],$tags,$isAdminUpload) = getPhotoDetail($photo);

      $photoNum[] = $photo['num'];
    }
    
    $autoPostData = replacePostText(false, $isAdminUpload, $listing);
    $text = formatPostData($listing, $tags, $autoPostData);
    
    postToTwitter($photoUrl, $text, "photo_uploads", $photoNum);
  }

  if($includeComments){ echo "Autopost data\r\n"; }

  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron

}

function replacePostText($isFb, $isAdminUpload, $listing){

  $autoPostData = mysql_get("share_texts", 1, null, "`moment_autopost_text`, `autopost_tags`");
  $autoPostData['moment_autopost_text'] = strip_tags($autoPostData['moment_autopost_text']);
  $autoPostData['autopost_tags']     = strip_tags($autoPostData['autopost_tags']);

  if($isFb && $listing['fb_username']) {
    $autoPostData['moment_autopost_text'] = str_replace("#businessname", "@".$listing['fb_username'], $autoPostData['moment_autopost_text']);
  }
  elseif(!$isFb && $listing['tw_username']) {
    $autoPostData['moment_autopost_text'] = str_replace("#businessname", "@".$listing['tw_username'], $autoPostData['moment_autopost_text']);
  }
  else {
    $autoPostData['moment_autopost_text'] = str_replace("✅ #businessname ", "", $autoPostData['moment_autopost_text']);
  }

  if($isAdminUpload){
    $autoPostData['moment_autopost_text'] = str_replace("#uploadType", "IG", $autoPostData['moment_autopost_text']);
  }else{
    $autoPostData['moment_autopost_text'] = str_replace("#uploadType", "UH", $autoPostData['moment_autopost_text']);
  }

  return $autoPostData;
}

function formatPostData($listing, $tags, $textData, $isFBPost = false, $count = 0, $recursionCount = 0){
  $temp = $textData;
  $customTags = explode(",", $textData['autopost_tags']);

  if($count != 0){
    // shuffle($customTags);
    array_splice($customTags, -$count);
  }  

  $tempTags = implode(" ", $customTags)." ".$tags;

  $address  = trim($listing['address_1'].", ".$listing['city'].', '.$listing['state']," ,");

  $text     = str_replace(["#listingname", "#address"], [strtoupper($listing['name']), $address], $textData['moment_autopost_text']);

  // $text     = $text."\r\n".$address."#tagline\r\n.\r\n.\r\n".trim($tempTags);
  $text .= "\r\n"."💯 ".trim($tempTags);

  if($recursionCount > 4){
    return trim($text);
  }

  if(strlen($text) > 280 && !$isFBPost){
    $diff = (strlen($text) - 280) / 10;
    $text = formatPostData($listing, $tags, $temp, false, ceil($diff), ++$recursionCount);
  } 
  
  return trim($text);
}

function getPhotoDetail($photo){
  $imageFiles = getUploadRecords('photo_uploads', 'photos', $photo['num']);

  $photoUrl = '';
  $tags = '';
  foreach($imageFiles as $file){
   $photoUrl = $file['urlPath'];
 }
 $isAdminUpload = false;
 if($photoUrl){
  
  if($photo['tag_ids']){
    $tags = mysql_select_query("SELECT `name` FROM urbanhal_tags WHERE `flagged` = 0 AND num IN ({$photo['tag_ids']})", true);
    
    if(count($tags)>0){
      $tags = array_map(function($value){ 
        return strtolower(preg_replace("/[\s-]/", "", $value[0]));
      },$tags);
      
      $tags =  implode(" ", $tags);
    }else{
      $tags = '';
    }
  }
}
$member  = mysql_get("members", $photo['membersNum'], null, "`isAdmin`");
if($member && $member['isAdmin']){
      // $tags  .= " #photo [IG]";
  $isAdminUpload = true;
}

return [$photoUrl,trim($tags), $isAdminUpload];
}

function postToFacebook($url,$string,$type,$recordNum){

  $recordNum = $recordNum[0];
  $url       = $url[0];

  $appId     = '1567266503589168';
  $appSecret = '5bc98880e08d3342f4055faceee9c4f3';
  $pageId    = '878347945644047';

  // test
  // $appId     = '252287179037626';
  // $appSecret = 'b4af3786b88bbb01646886babecb02b7';
  // $pageId    = '763298644052669';

  $token = $appId.'|'.$appSecret;
  $fb = new \Facebook\Facebook([
    'app_id' => $appId,
    'app_secret' => $appSecret,
    'default_graph_version' => 'v2.5'
  ]);

  $foreverPageAccessToken = 'EAAWRa6s2ZCTABABqD5v1GiJZACmATSTfvB4iNfoC39tXfpuDUz49FXXJxb4lUk0Vad9ZCjlkM9jw9ZCU6ETC5xr1vudsIlGu6LLX6wjZAJ1ZAkG5qOSyC0NaMOGOqSZB7WddAB91Eh6t1XmBbJ1s41W3PJgaHyfZAEPEKx6hZAOPxm4Uxz8bN8VZC8';
  // test
  // $foreverPageAccessToken = 'EAADldCZBwG7oBAP46x6dkEaoBxDJZCmPKFjRmIdRuxWCJ4sMbdhJQpOKFmvCTRtz0MRtTJ0QgEbY1iwZA07cU4LRAHUHoSh6X6ElmkSZCR4IrucFjXtEPxGgItplgn8Wdghaxvbq5EJGKfbi3SVnwpB4TDtSQgTWQri8dCOnfHfQkqAaaxT6';
  
  $fb->setDefaultAccessToken($foreverPageAccessToken);

  echo "\r\nPosting $type #$recordNum to facebook..\r\n";

  // $string .= "\r\n\r\nURBAN HALAL\r\nFood You Love From Local Favorites\r\nhttps://urbanhal.al/ios";

  // if($type == 'photo_uploads'){
  //   $fbFeedCount = mysql_get("fb_autopost_feed", 1);

  //   if($fbFeedCount['last_feed_count'] > 2){
  //     $foodPhrase = mysql_get("food_phrases", null, "TRUE ORDER BY updatedDate ASC");

  //     $string = $foodPhrase['phrase']."\r\n".$string;

  //     mysql_update("food_phrases", $foodPhrase['num'], null, array('updatedDate' => date("Y-m-d H:i:s", time()), 'is_added' => 1));
  //     mysql_update("fb_autopost_feed", 1, null, array('last_feed_count' => 1));
  //   }else{
  //     $fbFeedCount['last_feed_count'] = $fbFeedCount['last_feed_count'] + 1;
  //     mysql_update("fb_autopost_feed", 1, null, array('last_feed_count' => $fbFeedCount['last_feed_count']));
  //   }
  // }

  //echo $string."\r\n\r\n";

  $fb->sendRequest('POST', "$pageId/photos", [
    'message' => $string,
    'source' => $fb->fileToUpload($url),
  ]);

  if(is_array($recordNum)){
    foreach($recordNum as $num){
      mysql_update($type, $num, null, array('post_to_fb' => 1));
    }
  }else{
    mysql_update($type, $recordNum, null, array('post_to_fb' => 1));
  }
  

}

function postToTwitter($url,$string,$type,$recordNum){

  $consumerKey       = 'T3N74sv9YGtCPztySO3rvKXWv';
  $consumerSecret    = 'TJ9LqjQaegmT8NUODDYDP6EU5srn1CnYKjaHQWBFy0ZdynPRDA';
  $accessToken       = '83309820-2rgLk32P20vEHTW6O0IsoZKX9SCnTb1IAzFqX6rzZ';
  $accessTokenSecret = 'DCkSBO5cocKpczJGWjiHA47y0tDVkWnlBZP6vtGjx8rfE';

  //test
  // $consumerKey = '89thM0h5mCq0xWyHVXn5wE24c';
  // $consumerSecret =  'UXVcInEaqeneAu2ndjhe6TJwwnNqNvOveNTfZrSACpRvsevOF7';
  // $accessToken =  '1105021455757004800-aFgTu84xs6GVeddR2AYls7WulSYdnj';
  // $accessTokenSecret =  'R3vhVYaGB7DE7daF7EM0jVNX9Hpidycva4rcikuwVjXTM';

  $connection = new TwitterOAuth($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret);
  
  echo "\r\nPosting $type #recordNum to twitter..\r\n";

  // $string .= "\r\n\r\nURBAN HALAL\r\nFood You Love From Local Favorites\r\nhttps://urbanhal.al/ios";

  //echo $string."\r\n\r\n";
  
  //Photo Upload
  $mediaIds = [];
  foreach($url as $photoUrl){
    $img = file_get_contents($photoUrl);
    $imgExtension = pathinfo($photoUrl, PATHINFO_EXTENSION);
    $imgName = 'twitterPost.'.$imgExtension;

    file_put_contents($imgName, $img);
    $media1 = $connection->upload('media/upload', ['media' => $imgName]);
    $mediaIds[] = $media1->media_id_string;
    unlink($imgName);
  }
  $parameters = [
    'status' => $string,
    'media_ids' => implode(',', $mediaIds)
  ];


  try{
    $post_tweets = $connection->post("statuses/update", $parameters);
    if(is_array($recordNum)){
      foreach($recordNum as $num){
        mysql_update($type, $num, null, array('post_to_twitter' => 1));
      }
    }else{
      mysql_update($type, $recordNum, null, array('post_to_twitter' => 1));
    }
  }
  catch (TwitterException $e) {
    echo 'Error: ' . $e->getMessage();
  }
}

addCronJob('urbcan_updateListingsHalalItems', "Update Listings Halal Items", '0 1 * * *');             // Run every day at 1AM
// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
pluginAction_addHandlerAndLink(t('Update Listings Halal Items'), 'urbcan_updateListingsHalalItems', 'admins');
function urbcan_updateListingsHalalItems($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive

  echo "\nUpdating listings halal items...\n";
  $limit       = 0;
  $group       = 500;

  while(true){
    echo "\r\nGetting batch $limit, $group\n";
    
    $listings = mysql_select("listings", "TRUE ORDER BY `num` DESC LIMIT $limit, $group", "`num`,`halal_items`");
    
    if(count($listings) < 1){ echo "No more records found!\n"; break; }
    
    foreach($listings as $listing){
      echo "\r\nUpdating halal items for listing #{$listing['num']}...\n";
      $updateArray = array();
      $menuItems = mysql_select("menu", "`listingsNum` = {$listing['num']}", "`name`");

      $halalItems = [];
      foreach ($menuItems as $menuItem) {
        // chicken = chicken, chick
        if(stripos($menuItem['name'], "Chicken") !== false || stripos($menuItem['name'], "chick") !== false){
          $halalItems[] = "Chicken";
        }
        // beef = beef, ribs, sausage, ham, pepperoni, salami
        if(stripos($menuItem['name'], "Beef") !== false || stripos($menuItem['name'], "ribs") !== false || stripos($menuItem['name'], "sausage") !== false || stripos($menuItem['name'], "ham") !== false || stripos($menuItem['name'], "pepperoni") !== false || stripos($menuItem['name'], "salami") !== false){
          $halalItems[] = "Beef";
        }
        // goat = goat
        if(stripos($menuItem['name'], "Goat") !== false){
          $halalItems[] = "Goat";
        }
        // lamb = lamb, mutton
        if(stripos($menuItem['name'], "Lamb") !== false || stripos($menuItem['name'], "mutton") !== false){
          $halalItems[] = "Lamb";
        }
        // fish = fish, seafood, crab, shrimp, scallops, squid, calamari
        if(stripos($menuItem['name'], "Fish") !== false || stripos($menuItem['name'], "seafood") !== false || stripos($menuItem['name'], "crab") !== false || stripos($menuItem['name'], "shrimp") !== false || stripos($menuItem['name'], "scallops") !== false || stripos($menuItem['name'], "squid") !== false || stripos($menuItem['name'], "calamari") !== false){
          $halalItems[] = "Fish";
        }
        if(stripos($menuItem['name'], "Turkey") !== false){
          $halalItems[] = "Turkey";
        }
        // alcohol = wine, beer, alcohol, spirit
        $updateArray['alcohol'] = 0;
        if(stripos($menuItem['name'], "wine") !== false || stripos($menuItem['name'], "beer") !== false || stripos($menuItem['name'], "alcohol") !== false || stripos($menuItem['name'], "spirit") !== false){
          $updateArray['alcohol'] = 1;
        }
        // pig = pork, pig
        if(stripos($menuItem['name'], "pork") !== false || stripos($menuItem['name'], "pig") !== false){
          $updateArray['pork'] = 1;
        } 
      }
      //Chicken. Lamb. Beef. Fish. Turkey. Duck

      if(count($halalItems)){
        $halalItems = sortHalalItems($halalItems);
        $updateArray['halal_items'] = "\t".implode("\t", array_unique($halalItems))."\t";
        mysql_update('listings',$listing['num'], null, $updateArray);
        echo "Updated halal_items for listing #{$listing['num']}...\r\n";
      }else{
        echo "No menus items found for listing #{$listing['num']}...\r\n";
      }
    }
    
    $limit += $group;
  }
  if($includeComments){ echo "Updated listigns halal_items data...\r\n"; }

  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron

}

function sortHalalItems($halalItems){
  $arr = ["Chicken", "Beef", "Lamb", "Fish", "Goat", "Turkey"];
  $newArr = [];
  foreach($arr as $val){

    if(in_array($val, $halalItems)){
      $newArr[] = $val;
    }

  }
  return $newArr;
}

//addCronJob('urbcan_updateFBUserPicToS3', "Update FB Users picture to s3", '0 * * * *');             // Run every hour
// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
//pluginAction_addHandlerAndLink(t('Update FB Users picture to s3'), 'urbcan_updateFBUserPicToS3', 'admins');
function urbcan_updateFBUserPicToS3($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive

  echo "\nUpdating members profile picture...\n";
  $limit       = 0;
  $group       = 500;

  while(true){
    echo "\r\nGetting batch $limit, $group\n";
    
    $members = mysql_select("members", "facebook_picture != '' AND facebook_picture NOT LIKE '%/users/profile_pic/%' ORDER BY `num` DESC LIMIT $limit, $group", "`num`,`facebook_picture`");

    if(count($members) < 1){ echo "No more records found!\n"; break; }
    
    foreach($members as $member){
      if(!empty($member['facebook_picture'])){
        echo "\r\nUpdating profile picture for member #{$member['num']}...\n";
        
        $picUrl = uploadUserPic($member['facebook_picture']);

        mysql_update('members',$member['num'], null, array('facebook_picture' => $picUrl));
        
        echo "Updated profile picture for member #{$member['num']}...\r\n";
      }
    }
    
    $limit += $group;
  }
  if($includeComments){ echo "Updated members profile picture...\r\n"; }

  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron

}

addCronJob('urbcan_movePhotos', "Adding photos from archive to photo_uploads", '0 * * * *');             // Run every hour
// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
pluginAction_addHandlerAndLink(t('Adding photos from archive to photo_uploads'), 'urbcan_movePhotos', 'admins');
function urbcan_movePhotos($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive

  $archieveData = mysql_get('archive_photos', NULL, "TRUE ORDER BY rand()");
  if($archieveData){
    echo "Moving record {$archieveData['num']} \r\n\r\n";
    $archiveNum = $archieveData['num'];
    unset($archieveData['_tableName'], $archieveData['num']);
    $archieveData['createdDate'] = date('Y-m-d H:i:s');
    $archieveData['updatedDate'] = date('Y-m-d H:i:s');
    $archieveData['post_to_fb']      = 0;
    $archieveData['post_to_twitter'] = 0;
    $archieveData['post_to_ig']      = 0;
    // echo "<pre>";
    // print_r($archieveData);
    // exit();
    $newNum = mysql_insert('photo_uploads', $archieveData, true);
    mysql_update('uploads', null, "`tableName` = 'photo_uploads' AND `fieldname` = 'photos' AND `recordNum` = $archiveNum", array("recordNum" => $newNum));
    mysql_delete('archive_photos', $archiveNum);
  }else{
    echo "No more record found\r\n";
  }

  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron

}

addCronJob('urbcan_moveListingRequest', "Move listing requests to listings table", '0 * * * *');             // Run every hour
// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
pluginAction_addHandlerAndLink(t('Move listing requests to listings table'), 'urbcan_moveListingRequest', 'admins');
function urbcan_moveListingRequest($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive

  $requests = mysql_select("listing_requests", "`is_moved` = 1 AND `email_sent` = 0", "`num`, `name`, `listing_type`, `city`, `zip`, `email`, `username`, `mobile`,`merchant_id`,`merchant_type`");
  //$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  //Creating user
  if(count($requests)>0){
    foreach($requests as $request){
      $merchant_type  = (isset($request['merchant_type']) && $request['merchant_type'] != '') ? $request['merchant_type'] : '';
      $merchant_id  = (isset($request['merchant_id']) && $request['merchant_id'] != '') ? $request['merchant_id'] : '';

      $string = 'halalfood123';

      $extListing = mysql_get("listings", null, "`name` = '".$request['name']."' AND `zip` = '".$request['zip']."'","`createdByUserNum`,`num`");

      $createUser = (!isset($extListing['createdByUserNum']) || $extListing['createdByUserNum'] == 0) ? true : false;

      if($createUser){

        echo "\r\nCreating cms user\r\n";

        $listing = $request;

        $name     = mysqli_real_escape_string(mysqli(), $listing['name']."-".$listing['zip']);
        $pwd      = mysqli_real_escape_string(mysqli(), '$sha1$87d956e3d8dedd5c3b4ffa7e9847f271b6cf7508'); 
        $username   = preg_replace('/\s+/', '-', $name);               // replace spaces with dashes
        $username   = preg_replace('/[^a-z0-9\-\.\_]+/i', '', $username);  // remove non-alphanumeric chars
        $username   = preg_replace("/-+/", '-', $username);                // collapse multiple dashes
        $username   = preg_replace("/(^-+|-+$)/", '', $username);          // remove leading and trailing underscores
        $username   = strtolower($username);

        $data = [
          'username' => $username,
          'email'   => mysqli_real_escape_string(mysqli(), $username."@urbanhalal.com"),
          'city'    => mysqli_real_escape_string(mysqli(), $listing['city']),
         // 'state'   => mysqli_real_escape_string(mysqli(), $listing['state']),
          'account_type'    => mysqli_real_escape_string(mysqli(), $listing['listing_type']),
          'first_name' => mysqli_real_escape_string(mysqli(), $listing['name']),
          'last_name'   => mysqli_real_escape_string(mysqli(), $listing['zip']),
          'createdDate' => date('Y-m-d H:i:s', time()),
          'updatedDate' => date('Y-m-d H:i:s', time()),
          'createdByUserNum' => 1,
          'updatedByUserNum' => 1,
          'lastLoginDate' => date('Y-m-d H:i:s', time()),
          'expiresDate' => date('Y-m-d H:i:s', time()),
          'phone'   => mysqli_real_escape_string(mysqli(), $listing['mobile']),
          'password' => $pwd,
          'isAdmin' => 0,
          'neverExpires' => 1,
          'merchant_type'=>$merchant_type,
          'merchant_id'=>$merchant_id
        ];

        $userNum = mysql_insert('accounts', $data, true);
        
        //Giving required access
        $tables = ['see_orders','sales_dashboard','payments_dashboard','connect_stripe_account','menu','square_authorization'];
        foreach($tables as $tableName) {
          mysql_insert("_accesslist", ['userNum' => $userNum, 'tableName' => $tableName, 'accessLevel' => 7, 'randomSaveId' => ''], true);
        }
      }
      // create listings
      
      $mailData = $request;
      $request['phone'] = $request['mobile'];
      $request['type']  = $request['listing_type'];
      unset($request['username'],$request['mobile'],$request['listing_type'], $request['_tableName'],$request['num'],$request['merchant_type'],$request['merchant_id']);
      // $request = api_setUserAsCreator(['num'=>$user_num], $request);
      
      $createListing = !isset($extListing['num']) ? true : false;

      if($createListing){

        echo "\r\nCreating listing....\r\n";

        $request = array_merge($request, ['createdByUserNum'=>$userNum,'updatedByUserNum'=>$userNum,'createdDate'=>date('Y-m-d H:i:s'),'updatedDate'=>date('Y-m-d H:i:s'),'average_rating'=>'0','total_ratings'=>'0','points'=>'0','checkins'=>'0','reviews'=>'0','coupons'=>'0','followers'=>'0','photo_count'=>'0','average_rating'=>'0','average_foodie_experience'=>'0','total_foodie_experience'=>'0','total_shares'=>'0','views'=>'0','hidden' => 1, 'enable_order' => 0, 'is_online' => 0, 'monday_open' =>'9', 'monday_close' =>'17', 'tuesday_open' =>'9', 'tuesday_close' =>'17', 'wednesday_open' =>'9', 'wednesday_close' =>'17', 'thursday_open' =>'9', 'thursday_close' =>'17', 'friday_open' =>'9', 'friday_close' =>'17', 'saturday_open' =>'9', 'saturday_close' =>'17', 'sunday_open' =>'9', 'sunday_close' =>'17']);

        $num = mysql_insert('listings', $request, true);
        createCrmRecord($num,'Prospect','Listing Created');
      }

      if(isset($extListing['num']) && (!isset($extListing['createdByUserNum']) || $extListing['createdByUserNum'] == 0)){
        mysql_update("listings", $extListing['num'], null, ['createdByUserNum' => $userNum]);
      }

      $feedData = mysql_select('feed', "`section` != 'photo_uploads' AND `section` != 'photo_likes' ORDER BY `action_date` DESC LIMIT 3");

      $feeds = mysql_select('feed', "`section` = 'photo_uploads' ORDER BY `action_date` DESC LIMIT 0,9");
      $recent_moments = '';
      foreach ($feeds as $feed) {
        $record = json_decode($feed['json'], true);
        $recent_moments .='<img  style="margin-right:3px;margin-left:2px;" src="'.$record['photos'][0]['thumbUrlPath'].'" alt="" width="100" height="100" />';
      }

      if(isset($merchant_type) && $merchant_type == 'Clover' && $merchant_id){
        $tempData = [
          'merchantID'=>$merchant_id,
          'listingName'=>$request['name'],
          'zipcode'=> $request['zip'],
        ];
        $emailHeaders = emailTemplate_loadFromDB(array(
          'template_id' => 'CLOVER-MERCHANT-APPROVAL',
          'placeholders' => $tempData,
        ));

        $mailErrors = sendMessage($emailHeaders);
      }
      
      $placeholders = array('merchant_type'=>$merchant_type,'merchant_id'=>$merchant_id,'recent_moments' => $recent_moments, 'fullname' => $mailData['username'], 'username' => $username, 'password' => $string,'email' =>$mailData['email'],'loginUrl' => $GLOBALS['SETTINGS']['adminUrl']);

      $emailHeaders = emailTemplate_loadFromDB(array(
        'template_id'  => 'USER-SIGNUP',
        'placeholders' => $placeholders,
      ));
      // print_r($emailHeaders);exit;
      $mailErrors = sendMessage($emailHeaders);

      mysql_update("listing_requests", $mailData['num'], null, ['email_sent' => 1]);
    }
    echo "Done\r\n";
  }else{
    echo "No request found to add listing";
  }

  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron
}

addCronJob('urbcan_sendNewOrderEmail', "Send new order email to listing owner", '* * * * *');             // Run every hour
// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
pluginAction_addHandlerAndLink(t('Send new order email to listing owner'), 'urbcan_sendNewOrderEmail', 'admins');
function urbcan_sendNewOrderEmail($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive

  echo "\nSending new order emails...\n";
  $limit       = 0;
  $group       = 500;

  $orderAcceptTime = mysql_get("order_settings", 1, null, "`accept_order_time`")['accept_order_time'];
  
  while (true) {
    $start = (int)$orderAcceptTime;
    $end = (int)$orderAcceptTime * 3;

    $orders = mysql_select("orders", "`new_order_email_sent` = 0 AND `drivethru_order` = 0 AND `order_status` = 'preparing' AND (((NOW() > DATE_ADD(`createdDate`, INTERVAL $start SECOND)) AND (`booking_datetime` IS NULL OR `booking_datetime` = '0000-00-00 00:00:00')) OR (NOW() > DATE_ADD(`booking_datetime`, INTERVAL $start SECOND)) AND (`booking_datetime` IS NOT NULL OR `booking_datetime` != '0000-00-00 00:00:00')) ORDER BY createdDate DESC LIMIT $limit, $group");

    
    if(!$orders) { echo "No more orders found!...\n"; break; }
    
    foreach($orders as $order) {
      echo "Sending email for #{$order['order_number']}\n";
      $listingData = mysql_get("listings", $order['listingsNum'], null, "`num`, `name`, `address_1`, `city`, `state`, `zip`, `average_rating`, `timezone`, `createdByUserNum`");

      $listingAddress = trim($listingData['address_1'] . ", " . $listingData['city'], ", ");

      $listingRating = '';
      $x = 1;
      for($x = 1; $x <= $listingData['average_rating']; $x++){
        $listingRating .= '<img width="20" style="margin-right: 2px;" src="' . $GLOBALS['SETTINGS']['s3AssetsLink'] . 'rating-medium-yellow.png"/>';
      }
      while($x<=5) {
        $listingRating .= '<img width="20" style="margin-right: 2px;" src="' . $GLOBALS['SETTINGS']['s3AssetsLink'] . 'rating-medium-grey.png"/>';
        $x++; 
      }

      $listingPhoto = $GLOBALS['SETTINGS']['s3AssetsLink']."uh-default-new.png";
      $listingPhotos = mysql_select('photo_uploads', "`listingsNum` = ".intval($listingData['num'])." AND `for_photo` = 'photo' AND `flagged` = 0 ORDER BY `createdDate` DESC LIMIT 0,1");
      foreach($listingPhotos as $photoKey => $photo){
        $uploadPhoto = mysql_get("uploads", null, "`tableName` = 'photo_uploads' AND `fieldName` = 'photos' AND `recordNum` = {$photo['num']}", "`thumbUrlPath3`");
        $listingPhoto = $uploadPhoto['thumbUrlPath3'];
      }

      $listingAccount = mysql_get('accounts', $listingData['createdByUserNum'], null, "`email`");

      $listing = [
        "name" => $listingData['name'],
        "rating" => $listingRating,
        "image" => $listingPhoto,
        "address" => $listingAddress,
        "email" => $listingAccount['email']
      ];

      $orderItemsHtml = '<table width="100%" cellspacing="0" cellpadding="0" style="margin:0;padding:0 15px 0 15px;border: 2px solid #EAEAEA;border-radius: 10px;min-width: 100%;background: #FFFFFF;">
                            <tbody>
      ';

      $totalItems = mysql_get_query("SELECT SUM(quantity) as count FROM urbanhal_order_items WHERE ordersNum = {$order['num']}");

      

      $orderItems = mysql_select("order_items", "`ordersNum` = {$order['num']}");
      
      

      foreach($orderItems as $orderItem){

        $menuItemPrice = getOriginalPrice($orderItem['price'],$order['competitive_percentage']);

        $originalPrice = getOriginalPrice($orderItem['item_price'],$order['competitive_percentage']);

        $orderItemTotal = $menuItemPrice * $orderItem['quantity'];

        $orderItemsHtml .= '<tr>
                    <td colspan="2" align="left">
                        <p style="margin-top:10px;margin-bottom: 5px;font-style: normal;font-weight: bold;font-size: 12px;line-height: 15px;color: #000000;font-family: Montserrat,sans-serif;">
                            <b>' . $orderItem['name'] . '</b>
                        </p>';

        if(!empty($orderItem['menu_options']) && ($orderItem['menu_options'] != '[]')){
          $menuOptions = json_decode($orderItem['menu_options']);
          $options = [];
          foreach($menuOptions as $menuOption){
            $menuOption->price = getOriginalPrice($menuOption->price,$order['competitive_percentage']);
            $options[] = $menuOption->name." $".$menuOption->price." x ".$orderItem['quantity'];
          }

          $orderItemsHtml .= '<p style="margin-top:0;margin-bottom:10px;font-style: normal;font-weight: 600;font-size: 10px;line-height: 12px;color: #6A6A6A;font-family: Montserrat,sans-serif;">
                            ' . implode(", ",$options) . '
                            </p>';

          unset($options);                
        }

        $orderItemsHtml .= '<p style="margin-top:0;margin-bottom:10px;font-style: normal;font-weight: 500;font-size: 11px;line-height: 13px;color: #FF001F;font-family: Montserrat,sans-serif;">
        ' . $orderItem['note'] . '
        </p>
        </td>
        <td align="right">
        <p style="margin-top:10px;margin-bottom: 5px;font-style: normal;font-weight: bold;font-size: 18px;line-height: 22px;align-items: center;text-align: right;color: #000000;font-family: Montserrat,sans-serif;">
        <b>' . $orderItem['quantity'] . '</b>
        </p>
        <p style="margin-top: 0px;margin-bottom:5px;font-style: normal;font-weight: 500;font-size: 13px;line-height: 16px;text-align: right;color: #6A6A6A;font-family: Montserrat,sans-serif;">
        $' . formatPrice($orderItemTotal) . '
        </p>
        </td>
        </tr>';        
      }
      $orderItemsHtml .= '</tbody></table>';

      $subTotal = $order['sub_total'] - $order['competitive_price'];

      $listing_name = mysql_get("stripe_accounts", null, "`listingsNum` = {$order['listingsNum']}");

      $percentCommission = $order['order_delivery_type'] === "pickup" ? $listing_name['pickup_commission_fee'] : $listing_name['delivery_commission_fee'];

      $totalCommission = round((($subTotal * (float)$percentCommission) / 100),2);

      $orderTotal = round($subTotal - $totalCommission, 2);
      
      $pricesHtml = '<table width="100%" cellspacing="0" cellpadding="0" style="margin:0;padding:0 15px 0 15px;border: 2px solid #EAEAEA;border-radius: 10px;font-style: normal;font-weight: 500;font-size: 10px;line-height: 12px;color: #2A2A2A;min-width: 100%;background: #FAFAFA;font-family: Montserrat,sans-serif;">
      <tbody>
      <tr>
      <td colspan="2" align="left">
      <p style="font-family: Montserrat,sans-serif;font-style: normal;font-weight: 500;font-size: 10px;line-height: 12px;color: #2A2A2A;margin-top:10px;margin-bottom: 5px;">Subtotal</p>
      </td>

      <td align="right">
      <p style="font-family: Montserrat,sans-serif;font-style: normal;font-weight: bold;font-size: 10px;line-height: 12px;color: #000000;text-align: right;margin-top:10px;margin-bottom: 5px;">$'. formatPrice($subTotal) .'</p>
      </td>
      </tr>
      <tr>
      <td colspan="2" align="left">
      <p style="font-family: Montserrat,sans-serif;font-style: normal;font-weight: 500;font-size: 10px;line-height: 12px;color: #2A2A2A;margin-top:10px;margin-bottom: 5px;">FEE '.$percentCommission.'%</p>
      </td>

      <td align="right">
      <p style="font-family: Montserrat,sans-serif;font-style: normal;font-weight: bold;font-size: 10px;line-height: 12px;color: #FF001F;text-align: right;margin-top:10px;margin-bottom: 5px;">$'. formatPrice($totalCommission) . '</p>
      </td>
      </tr>';

          if($order['promo_code']){

              $orderTotal = round($subTotal - $totalCommission, 2) - $order['discount'];

              $pricesHtml .= '<tr>
                                  <td  align="left">
                                      <p style="font-family: Montserrat,sans-serif;font-style: normal;font-weight: 500;font-size: 10px;line-height: 12px;color: #2A2A2A;margin-top:10px;margin-bottom: 5px;">Promo</p>
                                  </td>
                                  <td  align="right">
                                      <p style="font-family: Montserrat,sans-serif;font-style: normal;font-weight: 600;font-size: 10px;line-height: 12px;color: #000000;margin-right: 25px;margin-top:10px;margin-bottom: 5px;">#'.$order['promo_code'].'</p>
                                  </td>
                                  <td align="right">
                                      <p style="font-family: Montserrat,sans-serif;font-style: normal;font-weight: bold;font-size: 10px;line-height: 12px;color: #9A9A9A;text-align: right;margin-top:10px;margin-bottom: 5px;">- $'. formatPrice($order['discount']) . '</p>
                                  </td>
                              </tr>';
                            }

                            $pricesHtml .=  '<tr >
                            <td colspan="3" style="border-bottom: 2px solid #EAEAEA;">
                            </td>  
                            </tr>
                            <tr>
                            <td colspan="2" align="left">
                            <p style="color: #2A2A2A;font-size: 14px;font-style: normal;font-weight: 600;line-height: 15px;font-family: Montserrat,sans-serif;margin-top:10px;margin-bottom: 10px;">PAYOUT</p>
                            </td>

                            <td align="right">
                            <p style="color: #000000;font-size: 14px;font-style: normal;font-weight: bold;line-height: 17px;font-family: Montserrat,sans-serif;margin-top:10px;margin-bottom: 10px;">$' . formatPrice($orderTotal) . '</p>
                            </td>
                            </tr>
                            </tbody>
                            </table>';

                            $mapMarker = "marker-bag.png";
                            if($order['order_delivery_type']=='delivery') {
                              $mapMarker = "marker-truck.png";
                            }
                            elseif($order['order_delivery_type']=='ship'){
                              $mapMarker = "marker-plane.png";
                            }

                            $orderAddress = trim($order['shipping_address'], ", "); 

                            $mapUrl = "https://maps.google.com/maps/api/staticmap?center=" . $orderAddress . "&zoom=15&size=300x100&scale=1&markers=icon:" . $GLOBALS['SETTINGS']['s3AssetsLink'] . $mapMarker . "|" . $orderAddress . "&key=" . $GLOBALS['SETTINGS']['googleApiKey'];

      //$utcTime = strtotime($order['createdDate']);
                            $utcTime = getOrderDate($order);

                            $localTime = utcTimeToLocalTime($utcTime, $listingData['timezone'], true, 'Y-m-d H:i:s', 'l, F d, Y @ g:i A');

      // Dompdf\Autoloader::register();
      // $dompdf = new Dompdf\Dompdf();

      // $dompdf->loadHtml($orderItemsHtml);

      // $dompdf->setPaper('A4', 'portrait'); 

      // $dompdf->render();

      // $output = $dompdf->output();

      // $attachment = "./plugins/file.pdf";

      // file_put_contents($attachment, $output);

                            $deliveryVendor = mysql_get("order_detail", null, "`ordersNum` = {$order['num']}", "`delivery_vendor`,`order_ready_time`");

                            $member = mysql_get("members", $order['membersNum'], null, "`facebook_first_name`, `facebook_last_name`");

                            $member['name'] = $member['facebook_first_name'] . " " . $member['facebook_last_name'];

                            $vendorName = ($order['order_delivery_type'] == 'delivery') ? $deliveryVendor['delivery_vendor'] : $member['name'];

                            $ltTwo = utcTimeToLocalTime(strtotime($deliveryVendor['order_ready_time']), $listingData['timezone'], true, 'Y-m-d H:i:s', 'F d, Y @ g:i A');

                            $orderInfo = [
                              "order_number" => $order['order_number'],
                              "mapUrl" => $mapUrl,
                              "orderItemsHtml" => $orderItemsHtml,
                              "pricesHtml" => $pricesHtml,
                              "date" => $localTime,
                              "address" => $orderAddress,
                              "type" => strtoupper($order['order_delivery_type']),
                              "detailDate" => $ltTwo,
                              "deliveryVendor" => ucwords($vendorName)
                            ];

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

                            $placeholders = array_merge(array_keys_prefix("order.", $orderInfo), array_keys_prefix("member.", $member), array_keys_prefix("listing.", $listing), array("unsubscribe_url" => $unsubUrl));

                            $emailHeaders = emailTemplate_loadFromDB(array(
                              'template_id'  => 'ORDER-RECEIVED-EMAIL',
                              'placeholders' => $placeholders
        //'attachments' => [$attachment]
                            ));
                            
                            $mailErrors = sendMessage($emailHeaders);
      //unlink($attachment);
                            
                            if($mailErrors) {
                              echo "Mail errror: " . $mailErrors . "\n";
                            }
                            else {
                              mysql_update("orders", $order['num'], null, ['new_order_email_sent' => 1]);
                              echo "Order email sent..\n";
                            }

                          }

                          $limit += $group;

                        }

  // return summary message
                        $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron

}

//addCronJob('urbcan_sendNewDrivethruOrderEmail', "Send new drivethru order email to listing owner", '15-20 7 * * 0-6');
// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
pluginAction_addHandlerAndLink(t('Send new drivethru order email to listing owner'), 'urbcan_sendNewDrivethruOrderEmail', 'admins');
function urbcan_sendNewDrivethruOrderEmail($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive

  echo "\nSending new order emails...\n";
  $limit       = 0;
  $group       = 500;

  $orderAcceptTime = mysql_get("order_settings", 1, null, "`accept_order_time`")['accept_order_time'];
  
  while (true) {
    $start = (int)$orderAcceptTime;
    $end = (int)$orderAcceptTime * 3;

    $orders = mysql_select("orders", "`new_order_email_sent` = 0 AND `drivethru_order` = 1 AND `order_status` = 'preparing' ORDER BY createdDate DESC LIMIT $limit, $group");

    //print_r($orders);exit();
    if(!$orders) { echo "No more orders found!...\n"; break; }
    
    $ordersInfo = $attachments = [];

    $orderNumHtml = '';

    foreach($orders as $order) {
      echo "Sending email for #{$order['order_number']}\n";
      $listingData = mysql_get("listings", $order['listingsNum'], null, "`num`, `name`, `address_1`, `city`, `state`, `zip`, `average_rating`, `timezone`, `createdByUserNum`, `email`");

      $listingAddress = trim($listingData['address_1'] . ", " . $listingData['city'], ", ");

      $listingAccount = mysql_get('accounts', $listingData['createdByUserNum'], null, "`email`");

      $utcTime = getOrderDate($order);

      $localTime = utcTimeToLocalTime($utcTime, $listingData['timezone'], true, 'Y-m-d H:i:s', 'F d, Y @ h:i A');

      $totalItems = mysql_get_query("SELECT SUM(quantity) as count FROM urbanhal_order_items WHERE ordersNum = {$order['num']}");

      $member = mysql_get("members", $order['membersNum'], null, "`facebook_first_name`, `facebook_last_name`, `phone_number`, `username`, `facebook_email`");

      $fbName = $member['facebook_first_name'];

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

        $fbName = $member['username'];

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

        $fbName = $member['facebook_email'];

      }

      $member['name'] = $member['facebook_first_name'] . " " . $member['facebook_last_name'];

      $listing = [
        "name" => $listingData['name'],
        "email" => $listingAccount['email']
      ];

      $orderItemsHtml = '<table width="100%" cellspacing="0" cellpadding="0" style="margin:0;min-width: 100%;">
      <tbody>
      <tr>
      <td align="center" colspan="3">
      <p style="font-style:normal;font-weight:600;font-size:14px;line-height:17px;text-align:center;text-transform:uppercase;color:#ff001f;font-family:Montserrat,sans-serif;margin-top:0px;margin-bottom:0px">
      <b>ORDER #' . $order['order_number'] . '</b>
      </p>
      </td>
      </tr>
      <tr>
      <td  align="left" style="padding:0 0 0 20px;">
      <p style="margin-top:10px;margin-bottom: 5px;font-size:14px;color:#000000;font-weight:600;font-style:normal;font-family:Montserrat,sans-serif;">
      '.$member['name'].'
      </p>
      <p style="margin-bottom:10px;margin-top:0px;color:#2a2a2a;font-size: 12px;font-weight:600;font-style:normal;font-family:Montserrat,sans-serif;">
      '.$member['phone_number'].'
      </p>
      </td>
      <td width="10"></td>
      <td align="right" style="padding:0 20px 0 0;">
      <p style="margin-top:10px;margin-bottom: 5px;font-size:12px;color: #6A6A6A;text-decoration: none;font-weight:600;font-style:normal;font-family:Montserrat,sans-serif;">
      <span>ITEMS</span><span style="color:#2a2a2a"> ' . $totalItems['count'] . '</span>
      </p>
      <p style="margin-bottom:10px;margin-top:0px;font-size:12px;color: #6A6A6A;text-decoration: none;font-weight:600;font-style:normal;font-family:Montserrat,sans-serif;">
      <span>DATE</span><span style="color:#2a2a2a"> ' . date("m-d h:i A", strtotime($order['drivethru_order_date'])) . '</span>
      </p>
      </td>
      </tr>
      </tbody>
      </table>
      <table width="100%" cellspacing="0" cellpadding="0" style="margin:0;padding:0 15px 0 15px;border: 2px solid #EAEAEA;border-radius: 10px;min-width: 100%;background: #FFFFFF;">
      <tbody>';

      $orderItems = mysql_select("order_items", "`ordersNum` = {$order['num']}");

      $orderItemQuantity = $orderItemsTotal = 0;
      
      foreach($orderItems as $orderItem){

        $menuItemPrice = getOriginalPrice($orderItem['price'],$order['competitive_percentage']);

        $originalPrice = getOriginalPrice($orderItem['item_price'],$order['competitive_percentage']);

        $orderItemTotal = $menuItemPrice * $orderItem['quantity'];

        $orderItemQuantity += $orderItem['quantity'];

        $orderItemsTotal += $menuItemPrice * $orderItem['quantity'];

        $orderItemsHtml .= '<tr>
        <td colspan="2" align="left" style="padding:0 0 0 10px;">
        <p style="margin-top:10px;margin-bottom: 5px;font-style: normal;font-weight: bold;font-size: 12px;line-height: 15px;color: #000000;font-family: Montserrat,sans-serif;">
        ' . $orderItem['name'] . '
        </p>
        ';

        if(!empty($orderItem['menu_options']) && ($orderItem['menu_options'] != '[]')){
          $menuOptions = json_decode($orderItem['menu_options']);
          $options = [];
          foreach($menuOptions as $menuOption){
            $menuOption->price = getOriginalPrice($menuOption->price,$order['competitive_percentage']);
            $options[] = $menuOption->name." $".$menuOption->price." x ".$orderItem['quantity'];
          }

          $orderItemsHtml .= '<p style="margin-top:0;margin-bottom:10px;font-style: normal;font-weight: 600;font-size: 10px;line-height: 12px;color: #6A6A6A;font-family: Montserrat,sans-serif;">
          ' . implode(", ",$options) . '
          </p>';

          unset($options);                
        }

        $orderItemsHtml .= '<p style="margin-top:0;margin-bottom:10px;font-style: normal;font-weight: 500;font-size: 11px;line-height: 13px;color: #FF001F;font-family: Montserrat,sans-serif;">
        ' . $orderItem['note'] . '
        </p>
        </td>
        <td align="right" style="padding:0 10px 0 0;">
        <p style="margin-top:10px;margin-bottom: 5px;font-style: normal;font-weight: bold;font-size: 18px;line-height: 22px;align-items: center;text-align: right;color: #000000;font-family: Montserrat,sans-serif;">
        ' . $orderItem['quantity'] . '
        </p>
        <p style="margin-top: 0px;margin-bottom:5px;font-style: normal;font-weight: 500;font-size: 13px;line-height: 16px;text-align: right;color: #6A6A6A;font-family: Montserrat,sans-serif;">
        $' . formatPrice($orderItemTotal) . '
        </p>
        </td>
        </tr>';        
      }

      $orderNumHtml .= '<table width="100%" cellspacing="0" cellpadding="0" style="margin:0;padding:0 15px 0 15px;border: 2px solid #EAEAEA;border-radius: 10px;min-width: 100%;background: #FFFFFF;margin-bottom:20px;">
                            <tbody>
                            <tr>
                    <td colspan="2" align="left">
                        <p style="margin-top:0px;margin-bottom: 5px;font-style: normal;font-weight: bold;font-size: 12px;color: #000000;font-family: Montserrat,sans-serif;">
                            <b> ORDER<br>' . $order['order_number'] . '</b>
                        </p>
                    </td>
                    <td align="right">
                    <p style="margin-top:10px;margin-bottom: 5px;font-style: normal;font-weight: bold;font-size: 18px;line-height: 22px;align-items: center;text-align: right;color: #000000;font-family: Montserrat,sans-serif;">
                    <b>' . $orderItemQuantity . '</b>
                    </p>
                    <p style="margin-top: 0px;margin-bottom:10px;font-style: normal;font-weight: 500;font-size: 13px;line-height: 16px;text-align: right;color: #6A6A6A;font-family: Montserrat,sans-serif;">
                    $' . formatPrice($orderItemsTotal) . '
                    </p>
                    </td>
                    </tr>
                    </tbody></table>';

      

      $orderItemsHtml .= '</tbody></table>';

      $subTotal = $order['sub_total'] - $order['competitive_price'];

      $utcTime = getOrderDate($order);

      $localTime = utcTimeToLocalTime($utcTime, $listingData['timezone'], true, 'Y-m-d H:i:s', 'F d, Y @ h:i A');

      Dompdf\Autoloader::register();
      $dompdf = new Dompdf\Dompdf();

      $dompdf->loadHtml($orderItemsHtml);

      $dompdf->setPaper('A4', 'portrait');

      $options = $dompdf->getOptions();

      $options->setDefaultFont('Montserrat');

      $dompdf->setOptions($options); 

      $dompdf->render();

      $output = $dompdf->output();

      $attachment = "./plugins/".uniqid(rand(), true) . ".pdf";

      file_put_contents($attachment, $output);

      $listingEmails = $listingAccount['email'];
      // check for empty listing email or for value "Dev" in listing email
      if($listingData['email'] && strtolower($listingData['email']) !== "dev") {
        $listingEmails .= "," . $listingData['email'];
      }

      $drivethruDate = date("l, F d, Y @ g:i A", strtotime($order['drivethru_order_date']));

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

      $placeholders = [
        'listing.name' => $listing['name'], 
        'listing.email' => $listingEmails,
        'listing.address' => $listingAddress,
        'date' => $drivethruDate,
        'facebook_first_name' => $fbName,
        'unsubscribe_url' => $unsubUrl
      ];

      if(array_key_exists($order['listingsNum'], $ordersInfo)) {

        array_push($ordersInfo[$order['listingsNum']]['attachments'],$attachment);

        array_push($ordersInfo[$order['listingsNum']]['order_ids'], $order['num']);

        $ordersInfo[$order['listingsNum']] = [

          "placeholders" => $placeholders,
          "attachments" => $ordersInfo[$order['listingsNum']]['attachments'],
          "subtotal" => $ordersInfo[$order['listingsNum']]['subtotal'] + $subTotal,
          "order_ids" => $ordersInfo[$order['listingsNum']]['order_ids']
        ];

      }
      else {

        $ordersInfo[$order['listingsNum']] = [

          "placeholders" => $placeholders,
          "attachments" => [$attachment],
          "subtotal" => $subTotal,
          "order_ids" => [$order['num']]
        ];

      }
      
    }

    foreach($ordersInfo as $listingsNum => $orderInfo){

      $ordersNum = implode(",",$orderInfo['order_ids']);

      $listing_name = mysql_get("stripe_accounts", null, "`listingsNum` = {$listingsNum}");

      $percentCommission = $listing_name['pickup_commission_fee'];

      $totalCommission = round((($orderInfo['subtotal'] * (float)$percentCommission) / 100),2);

      $orderTotal = round($orderInfo['subtotal'] - $totalCommission, 2);

      $pricesHtml = '<table width="100%" cellspacing="0" cellpadding="0" style="margin:0;padding:0 15px 0 15px;border: 2px solid #EAEAEA;border-radius: 10px;font-style: normal;font-weight: 500;font-size: 10px;line-height: 12px;color: #2A2A2A;min-width: 100%;background: #FAFAFA;font-family: Montserrat,sans-serif;">
      <tbody>
      <tr>
      <td colspan="2" align="left">
      <p style="font-family: Montserrat,sans-serif;font-style: normal;font-weight: 500;font-size: 10px;line-height: 12px;color: #2A2A2A;margin-top:10px;margin-bottom: 5px;">Subtotal</p>
      </td>

      <td align="right">
      <p style="font-family: Montserrat,sans-serif;font-style: normal;font-weight: bold;font-size: 10px;line-height: 12px;color: #000000;text-align: right;margin-top:10px;margin-bottom: 5px;">$'. formatPrice($orderInfo['subtotal']) .'</p>
      </td>
      </tr>
      <tr>
      <td colspan="2" align="left">
      <p style="font-family: Montserrat,sans-serif;font-style: normal;font-weight: 500;font-size: 10px;line-height: 12px;color: #2A2A2A;margin-top:10px;margin-bottom: 5px;">FEE '.$percentCommission.'%</p>
      </td>

      <td align="right">
      <p style="font-family: Montserrat,sans-serif;font-style: normal;font-weight: bold;font-size: 10px;line-height: 12px;color: #FF001F;text-align: right;margin-top:10px;margin-bottom: 5px;">$'. formatPrice($totalCommission) . '</p>
      </td>
      </tr>
      <tr >
      <td colspan="3" style="border-bottom: 2px solid #EAEAEA;">
      </td>  
      </tr>
      <tr>
      <td colspan="2" align="left">
      <p style="color: #2A2A2A;font-size: 14px;font-style: normal;font-weight: 600;line-height: 15px;font-family: Montserrat,sans-serif;margin-top:10px;margin-bottom: 10px;">PAYOUT</p>
      </td>

      <td align="right">
      <p style="color: #000000;font-size: 14px;font-style: normal;font-weight: bold;line-height: 17px;font-family: Montserrat,sans-serif;margin-top:10px;margin-bottom: 10px;">$' . formatPrice($orderTotal) . '</p>
      </td>
      </tr>
      </tbody>
      </table>';


      $orderInfo['placeholders']['order.pricesHtml'] = $pricesHtml;

      $orderInfo['placeholders']['order.orderNumHtml'] = $orderNumHtml;

      $emailHeaders = emailTemplate_loadFromDB(array(
        'template_id'  => 'DRIVETHRU-ORDER-RECEIVED-EMAIL',
        'placeholders' => $orderInfo['placeholders'],
        'attachments' => $orderInfo['attachments']
      ));
      
      $mailErrors = sendMessage($emailHeaders);

      foreach($orderInfo['attachments'] as $attachment){
        unlink($attachment);
      }
      
      if($mailErrors) {
        echo "Mail errror: " . $mailErrors . "\n";
      }
      else {
        mysql_update("orders", null, "`num` IN ({$ordersNum})", ['new_order_email_sent' => 1]);
        echo "Order email sent..\n";
      }

    }

    $limit += $group;

  }

  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron

}

//addCronJob('urbcan_sendPayoutToListings', "Send payouts to listings for delivered order", '05 0 * * 5');             // Run every friday
// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
pluginAction_addHandlerAndLink(t('Send payouts to listings for delivered order'), 'urbcan_sendPayoutToListings', 'admins');
function urbcan_sendPayoutToListings($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive

  include_once $GLOBALS['SETTINGS']['webRootDir'] . "/main/order-functions-v2.php";

  echo "\nSending payouts...\n";
  $limit       = 0;
  $group       = 500;

  // get last week sunday and staurday date
  //$sunday = date("Y-m-d", strtotime("last sunday") - (7 * 86400));
  //$saturday = date("Y-m-d", strtotime("last saturday"));

  $tillDate = date("Y-m-d", strtotime("-4 days"));



  // echo "SELECT DATE_FORMAT(`createdDate`, '%Y-%m-%d') order_date, count(num) orders_count, listingsNum, SUM(sub_total) as subtotal, SUM(competitive_price) as competitive, SUM(surge_price) as surge, SUM(discount) as discount FROM urbanhal_orders WHERE (DATE_FORMAT(`createdDate`, '%Y-%m-%d') BETWEEN '" . $sunday ."' AND '" . $saturday . "') AND order_status = 'delivered' GROUP BY listingsNum, order_delivery_type LIMIT $limit, $group";
  // exit;
  
  while(true) {
    $orders = mysql_select_query("SELECT DATE_FORMAT(`createdDate`, '%Y-%m-%d') order_date, DATE_FORMAT(`booking_datetime`, '%Y-%m-%d') schedule_date, num,order_status, competitive_percentage, deduct_from_payouts, promo_code, listingsNum, payout_sent, refund_amount, sub_total as subtotal, competitive_price as competitive, discount as discount, order_delivery_type FROM urbanhal_orders WHERE (((DATE_FORMAT(`createdDate`, '%Y-%m-%d')) < '". $tillDate ."' AND (`booking_datetime` IS NULL OR `booking_datetime` = '0000-00-00 00:00:00')) OR ((DATE_FORMAT(`booking_datetime`, '%Y-%m-%d')) < '". $tillDate ."' AND (`booking_datetime` IS NOT NULL OR `booking_datetime` != '0000-00-00 00:00:00'))) AND (order_status = 'delivered' || (order_status = 'refunded' and refund_amount IS NOT NULL)) AND payout_sent != 1 ORDER BY listingsNum DESC LIMIT $limit, $group");

    if(!$orders) { echo "No more orders found!...\n"; break; }
    
    $payouts = [];

    $firstDate = $lastDate = '';

    foreach ($orders as $order) {

      $discount = $refund = 0;

      if(isset($order['promo_code']) && !empty($order['promo_code'])) {

        $promoDiscount = mysql_get("promo_codes", null,"`name` = '".$order['promo_code']."'","`deduct_from_payouts`");

        if($promoDiscount['deduct_from_payouts'] == 1){

          $discount = $order['discount'];
        }

      }

      $orderDate = $order['order_date'];

      if($order['schedule_date'] != '0000-00-00')
      {
        $orderDate = $order['schedule_date'];
      }

      if($order === reset($orders)){

        $firstDate = $orderDate;

      }
      if($order === end($orders)){

        $lastDate = $orderDate;

      }

      $order['competitive_percentage'] = empty($order['competitive_percentage']) ? 0 : $order['competitive_percentage'];

      if($order['deduct_from_payouts'] == 1){

        $refundCompetitive = ($order['refund_amount'] * $order['competitive_percentage']) / 100;

        $refund = $order['refund_amount'] - $refundCompetitive;

      }

      $listing = mysql_get("stripe_accounts", null, "`listingsNum` = {$order['listingsNum']}", "`pickup_commission_fee`, `delivery_commission_fee`, `stripe_account_id`");

      $stripeFee = round(($order['subtotal'] * 2.9) / 100, 2);

      $stripeFee = $stripeFee + 0.3;

      $subTotal = $order['subtotal'] - $order['competitive'];

      $orderType = $order['order_delivery_type'];
      $commissionInPercentage = $orderType === "pickup" ? $listing['pickup_commission_fee'] : $listing['delivery_commission_fee'];

      $commission = round(($subTotal * $commissionInPercentage) / 100, 2);
      
      $total = round($subTotal - $commission - $discount - $refund - $stripeFee, 2);

      if(array_key_exists($order['listingsNum'], $payouts)) {

        array_push($payouts[$order['listingsNum']]['order_ids'], $order['num']);

        $payouts[$order['listingsNum']] = [
          "subtotal"          => $payouts[$order['listingsNum']]['subtotal'] + $subTotal,
          "total"             => $payouts[$order['listingsNum']]['total'] + $total,
          "commission"        => $payouts[$order['listingsNum']]['commission'] + $commission,
          "commission_percentage" => $payouts[$order['listingsNum']]['commission_percentage'],
          "discount"          => $payouts[$order['listingsNum']]['discount'] + $discount,
          "order_ids"         => $payouts[$order['listingsNum']]['order_ids'],
          "stripe_account_id" => $listing['stripe_account_id'],
          "refund_amount"     => $payouts[$order['listingsNum']]['refund_amount'] + $refund,
          "stripe_fee"        => $payouts[$order['listingsNum']]['stripe_fee'] + $stripeFee
        ];

      }
      else {

        echo "\n-----Calculating payouts for listing #{$order['listingsNum']}-----\n";

        $payouts[$order['listingsNum']] = [
          "subtotal"          => $subTotal,
          "total"             => $total,
          "commission"        => $commission,
          "commission_percentage" => $commissionInPercentage,
          "discount"          => $discount,
          "order_ids"         => [$order['num']],
          "stripe_account_id" => $listing['stripe_account_id'],
          "refund_amount"     => $refund,
          "stripe_fee"        => $stripeFee
        ];
      }

      mysql_update("orders", $order['num'], null, ['payout_sent' => 1]);
      
    }


    foreach ($payouts as $listingsNum => $payout) {
      $listing = mysql_get_query("SELECT urbanhal_accounts.email, urbanhal_listings.name, urbanhal_listings.timezone, urbanhal_listings.address_1, urbanhal_listings.city, urbanhal_listings.zip, urbanhal_listings.createdByUserNum, urbanhal_listings.email as listingEmail FROM urbanhal_listings INNER JOIN urbanhal_accounts ON urbanhal_accounts.num = urbanhal_listings.createdByUserNum WHERE urbanhal_listings.num = $listingsNum");

      echo "\n-----Sending payouts for #{$listing['name']}(ZIP {$listing['zip']})# from date $firstDate to $lastDate-----\n";

      echo "TOTAL {$payout['subtotal']}, ORDER FEE {$payout['commission']}, DISCOUNT {$payout['discount']}, NET PAYOUT {$payout['total']}" . "\n";

      $status = "Failed";
      $issue = "Stipe account is not connected";
      $transactionId = "";
      
      if($payout['stripe_account_id']) {
        $res = transferAmount($payout['total'], $payout['stripe_account_id'], "Payout for orders of {$listing['name']}(ZIP {$listing['zip']}) from date $firstDate to $lastDate.");

        if(is_string($res)) {
          $status = "Failed";
          $issue = $res; 
        }
        else {
          sendPayoutsEmail($payout,$listing,$payout['stripe_account_id']);
          $status = "Successful";
          $transactionId = $res->id;
          $issue = ""; 
        }
      }

      $data = [
        "orders_count" => count($payout['order_ids']),
        "listingsNum" => $listingsNum,
        "amount" => formatPrice($payout['subtotal']),
        "commission" => formatPrice($payout['commission']),
        "refund_amount" => formatPrice($payout['refund_amount']),
        "stripe_fee" => formatPrice($payout['stripe_fee']),
        "discount" => formatPrice($payout['discount']),
        "net_payout" => formatPrice($payout['total']),
        "transaction_id" => $transactionId,
        "payment_status" => $status,
        "issue" => $issue,
        "order_ids" => implode(", ", $payout['order_ids']),
        "createdDate" => date("Y-m-d H:i:s"),
        "updatedDate" => date("Y-m-d H:i:s"),
        'createdByUserNum' => $listing['createdByUserNum'],
        'updatedByUserNum' => $listing['createdByUserNum'],
        'payment_date' => date("Y-m-d H:i:s"),
        'order_dates' => date("m-d-Y", strtotime($firstDate)) . " to " . date("m-d-Y", strtotime($lastDate))
      ];

      mysql_insert("listing_payments", $data, true);

    }

    $limit += $group;

  }

  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron

}


function sendPayoutsEmail($payout,$listing,$Id){

  $orderItemsHtml = '';

  foreach($payout['order_ids'] as $num){

    $orderItems = mysql_select("order_items", "`ordersNum` = {$num}");

    $currentOrder = mysql_get("orders",$num,null,'`competitive_percentage`,`order_number`');

    $orderItemQuantity = $orderItemTotal = 0;

    foreach($orderItems as $orderItem){

      $menuItemPrice = getOriginalPrice($orderItem['price'],$currentOrder['competitive_percentage']);

      $originalPrice = getOriginalPrice($orderItem['item_price'],$currentOrder['competitive_percentage']);

      $orderItemQuantity += $orderItem['quantity'];

      $orderItemTotal += $menuItemPrice * $orderItem['quantity'];

    }

    $orderItemsHtml .= '<table width="100%" cellspacing="0" cellpadding="0" style="margin:0;padding:0 15px 0 15px;border: 2px solid #EAEAEA;border-radius: 10px;min-width: 100%;background: #FFFFFF;margin-bottom:20px;">
                            <tbody>
                            <tr>
                    <td colspan="2" align="left">
                        <p style="margin-top:0px;margin-bottom: 5px;font-style: normal;font-weight: bold;font-size: 12px;color: #000000;font-family: Montserrat,sans-serif;">
                            <b> ORDER<br>' . $currentOrder['order_number'] . '</b>
                        </p>
                    </td>
                    <td align="right">
                    <p style="margin-top:10px;margin-bottom: 5px;font-style: normal;font-weight: bold;font-size: 18px;line-height: 22px;align-items: center;text-align: right;color: #000000;font-family: Montserrat,sans-serif;">
                    <b>' . $orderItemQuantity . '</b>
                    </p>
                    <p style="margin-top: 0px;margin-bottom:10px;font-style: normal;font-weight: 500;font-size: 13px;line-height: 16px;text-align: right;color: #6A6A6A;font-family: Montserrat,sans-serif;">
                    $' . formatPrice($orderItemTotal) . '
                    </p>
                    </td>
                    </tr>
                    </tbody></table>';
  }

  $pricesHtml = '<table width="100%" cellspacing="0" cellpadding="0" style="margin:0;padding:0 15px 0 15px;border: 2px solid #EAEAEA;border-radius: 10px;font-style: normal;font-weight: 500;font-size: 10px;line-height: 12px;color: #2A2A2A;min-width: 100%;background: #FAFAFA;font-family: Montserrat,sans-serif;">
      <tbody>
      <tr>
      <td colspan="2" align="left">
      <p style="font-family: Montserrat,sans-serif;font-style: normal;font-weight: 500;font-size: 10px;line-height: 12px;color: #2A2A2A;margin-top:10px;margin-bottom: 5px;">Subtotal</p>
      </td>

      <td align="right">
      <p style="font-family: Montserrat,sans-serif;font-style: normal;font-weight: bold;font-size: 10px;line-height: 12px;color: #000000;text-align: right;margin-top:10px;margin-bottom: 5px;">$'. formatPrice($payout['subtotal']) .'</p>
      </td>
      </tr>
      <tr>
      <td colspan="2" align="left">
      <p style="font-family: Montserrat,sans-serif;font-style: normal;font-weight: 500;font-size: 10px;line-height: 12px;color: #2A2A2A;margin-top:10px;margin-bottom: 5px;">FEE '.$payout['commission_percentage'].'%</p>
      </td>

      <td align="right">
      <p style="font-family: Montserrat,sans-serif;font-style: normal;font-weight: bold;font-size: 10px;line-height: 12px;color: #FF001F;text-align: right;margin-top:10px;margin-bottom: 5px;">$'. formatPrice($payout['commission']) . '</p>
      </td>
      </tr>';

  $pricesHtml .= '<tr>
      <td  align="left">
          <p style="font-family: Montserrat,sans-serif;font-style: normal;font-weight: 500;font-size: 10px;line-height: 12px;color: #2A2A2A;margin-top:10px;margin-bottom: 5px;">Promo</p>
      </td>
      <td  align="right">
          <p style="font-family: Montserrat,sans-serif;font-style: normal;font-weight: 600;font-size: 10px;line-height: 12px;color: #000000;margin-right: 25px;margin-top:10px;margin-bottom: 5px;"></p>
      </td>
      <td align="right">
          <p style="font-family: Montserrat,sans-serif;font-style: normal;font-weight: bold;font-size: 10px;line-height: 12px;color: #9A9A9A;text-align: right;margin-top:10px;margin-bottom: 5px;">- $'. formatPrice($payout['discount']) . '</p>
      </td>
      </tr>';

  $pricesHtml .=  '<tr >
      <td colspan="3" style="border-bottom: 2px solid #EAEAEA;">
      </td>  
      </tr>
      <tr>
      <td colspan="2" align="left">
      <p style="color: #2A2A2A;font-size: 14px;font-style: normal;font-weight: 600;line-height: 15px;font-family: Montserrat,sans-serif;margin-top:10px;margin-bottom: 10px;">PAYOUT</p>
      </td>

      <td align="right">
      <p style="color: #000000;font-size: 14px;font-style: normal;font-weight: bold;line-height: 17px;font-family: Montserrat,sans-serif;margin-top:10px;margin-bottom: 10px;">$' . formatPrice($payout['total']) . '</p>
      </td>
      </tr>
      </tbody>
      </table>';

  
  $listingEmails = $listing['email'];
  // check for empty listing email or for value "Dev" in listing email
  if($listing['listingEmail'] && strtolower($listing['listingEmail']) !== "dev") {
    $listingEmails .= "," . $listing['listingEmail'];
  }

  $listingAddress = trim($listing['address_1'] . ", " . $listing['city'], ", ");

  $utcTime = date("Y-m-d H:i:s");

  $localTime = utcTimeToLocalTime($utcTime, $listing['timezone'], true, 'Y-m-d H:i:s', 'l, F d, Y @ g:i A');

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

  $placeholders = [
    'listing.zip' => $listing['zip'], 
    'listing.name' => $listing['name'], 
    'pricesHtml' => $pricesHtml, 
    'listing.email' => $listingEmails,
    'unsubscribe_url' => $unsubUrl,
    'orderItemsHtml' => $orderItemsHtml,
    'date' => $localTime,
    'listing.address' => $listingAddress,
    'id' => $Id
  ]; 

  $emailHeaders = emailTemplate_loadFromDB(array(
    'template_id'  => 'LISTINGS-PAYOUTS-EMAIL',
    'placeholders' => $placeholders,
  ));

  echo "\n-----Sending payouts email to listing-----\n";

  $mailErrors = sendMessage($emailHeaders);
  if ($mailErrors) { echo "Mail Errors: $mailErrors\r\n"; }
  else { echo "Email Sent\r\n"; }
}


function sendSocialPost($socialPost) {

  echo "Sending socail posts....\r\n";
  $limit       = 0;
  $group       = 500;


  $emailHeaders = array();
  $emailHeaders['from']     = $GLOBALS['SETTINGS']['adminEmail'];
  
  
  $emailHeaders['headers']['Reply-To'] = '';
  $emailHeaders['headers']['CC'] = '';
  $emailHeaders['headers']['BCC'] = '';
  $emailHeaders['headers']['Return-Path'] = $GLOBALS['SETTINGS']['adminEmail'];
  
  $emailHeaders['subject']  = $socialPost['title'];
  $emailHeaders['html']     = $socialPost['email_template'];

  $newsletterSettings = mysql_get('_nlb_settings', 1, null, "`manage_url`");

  $feedData = mysql_select('feed', "`section` != 'photo_uploads' AND `section` != 'photo_likes' ORDER BY `action_date` DESC LIMIT 3");

  $feeds = mysql_select('feed', "`section` = 'photo_uploads' ORDER BY `action_date` DESC LIMIT 0,9");
  $recent_moments = '';
  foreach ($feeds as $feed) {
    $record = json_decode($feed['json'], true);
    $recent_moments .='<img  style="margin-right:3px;margin-left:2px;" src="'.$record['photos'][0]['thumbUrlPath'].'" alt="" width="100" height="100" />';
  }


  $htmlTitle  = htmlencode($emailHeaders['subject']);
  $header = <<<__HTML__
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>$htmlTitle</title>
<link href="https://fonts.googleapis.com/css?family=Montserrat:100,200,300,400,500,600,700" rel="stylesheet" type="text/css">
</head>
<body>

<style type="text/css">
p { margin-bottom: 1em; }
body{
  font-family: Montserrat;
  font-size: 12px;
}
</style>


__HTML__;
// ***NOTE*** style tag is for Yahoo Mail which otherwise drops paragraph spacing - http://www.email-standards.org/blog/entry/yahoo-drops-paragraph-spacing/
// ... having a defined <title></title> helps get by spam filters

  $footer = <<<__HTML__
</body>
</html>
__HTML__;
  $emailHeaders['html'] = $header . $emailHeaders['html'] . $footer;
  
  while(true) {

    $users = mysql_select("members","`facebook_email` IS NOT NULL AND `facebook_email` != '' LIMIT $limit, $group", "`facebook_email`,`username`");

    if(!$users) { break; }

    foreach($users as $user) {
        // get email values
      $emailHeaders['to']       = $user['facebook_email'];
       // $emailHeaders['disabled'] = coalesce( @$options['override-disabled'], @$template['disabled'] );
        //$emailHeaders['html']     = $socialPost['email_template'];

      $subscriber = mysql_get("_nlb_subscribers", null, "`email` = '".$user['facebook_email']."'", "`num`");

      $emailHeaders['html'] .= "\n<img src='".$newsletterSettings['manage_url']."?o=1&amp;m=0&amp;n=".@$subscriber['num']."' height='1' width='1' alt='' />\n";

        $_preLinkRegexp        = "<a[^>]*?href=['\"]"; // match a href and area href
        $_postLinkRegexp       = "['\"][^>]*>";
        $absLinkRegexp         = "($_preLinkRegexp)(https?:[^'\"]*)($_postLinkRegexp)";
        
        $GLOBALS['CALLBACK_VARS'] = array('messageNum' => 0, 'subscriberNum' => @$subscriber['num']); 
        $emailHeaders['html'] = preg_replace_callback("/$absLinkRegexp/i", 'nlb_sendMessage_replacelink_callback', $emailHeaders['html']);
        
        unset($GLOBALS['CALLBACK_VARS']);
        
        $placeholders = array('recent_moments' => $recent_moments, 'username' => $user['username']);

        list($emailHeaders, $textPlaceholderList) = emailTemplate_replacePlaceholders($emailHeaders, $placeholders);
        
        $emailHeaders['html'] = $header . $emailHeaders['html'] . $footer;
        
        //
        //return $emailHeaders;
        $mailErrors = sendMessage($emailHeaders);
        if ($mailErrors) { echo "Mail Errors: $mailErrors\r\n"; }
        else { echo "Email Sent\r\n"; }
      }// $users foreach end

      $limit += $group;
    } // while end


  }

  function socialPostMobileNotification($socialPost){
    echo "Adding push notification....\r\n";
    
    $notifyData = $pushNotification = [];

    if($socialPost['notification_type'] == 'orders_onboarding' ){

      $notifyData['notification_type'] = $socialPost['notification_type'];

    }elseif($socialPost['notification_type'] == 'orders_listing_detail' && !empty($socialPost['listingsNum'])){

      $listingDetail = mysql_get("listings", $socialPost['listingsNum'], null, "`type`");

      $menuCategory = mysql_select_query("SELECT `urbanhal_menu_categories`.num FROM urbanhal_menu_categories INNER JOIN urbanhal_menu ON `urbanhal_menu`.category = `urbanhal_menu_categories`.num WHERE `urbanhal_menu`.listingsNum = {$socialPost['listingsNum']} AND `urbanhal_menu`.enable_order = 1 GROUP BY `urbanhal_menu_categories`.num ORDER BY `urbanhal_menu_categories`.dragSortOrder DESC LIMIT 1");

      $notifyData = [
        'notification_type'         => $socialPost['notification_type'],
        'listingsNum'               => $socialPost['listingsNum'],
        'listingType'               => strtolower($listingDetail['type']),
        'deliveryType'              => 'pickup',
        'categoryNum'               => $menuCategory[0]['num']        
      ];

    }
    elseif($socialPost['notification_type'] === "update") {
      $notifyData = [
        'notification_type' => 'update',
        'app_url'           => 'https://urbanhal.al/ios',
        'android_app_url'   => 'https://urbanhal.al/android'
      ];
    }

    $pushNotification = [
      'createdDate'               => date("Y-m-d H:i:s"),
      'app_id'                    => 'urbanhalal.com',
      'message'                   => $socialPost['title'],
      'to'                        => 'all',
      'notification_type'         => $socialPost['notification_type'],
      'notify_data'               => json_encode($notifyData)
    ];

    mysql_insert("man_push_notifications", $pushNotification, true);

  }

  function socialPostMobileSms($socialPost){

    echo "Sending sms....\r\n";
    $limit       = 0;
    $group       = 500;
    
    while(true) {

      $users = mysql_select("members","`phone_number` IS NOT NULL AND `phone_number` != '' LIMIT $limit, $group", "`phone_number`");

      if(!$users) { break; }

      foreach($users as $user) {
       
        sendSMS($user['phone_number'], "URBAN HALAL: " . $socialPost['title']);
      }// $users foreach end

      $limit += $group;
    } // while end
    

  }

addCronJob('urbcan_sendSocialPostToUsers', "Send social post to users.", '0,15,30,45,59 * * * *');             // Run every 15 minutes
// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
pluginAction_addHandlerAndLink(t('Send social post to users.'), 'urbcan_sendSocialPostToUsers', 'admins');
function urbcan_sendSocialPostToUsers(){


  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( false ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive
  

  $socialPosts = mysql_select("social_post","`sent` = 0 AND `publishDate` <= NOW() order by publishDate desc","`title`,`listingsNum`,`notification_type`,`email_template`,`send_notification`,`send_email`,`send_sms`,`num`,`sent`");

  if(!$socialPosts) { echo "No social posts found....\r\n"; }

  foreach ($socialPosts as $key => $socialPost) {

    if($socialPost['send_notification'] == 1){

      socialPostMobileNotification($socialPost);

    }

    if($socialPost['send_email'] == 1){

      sendSocialPost($socialPost);

    }

    if($socialPost['send_sms'] == 1){

      socialPostMobileSms($socialPost);

    }

    mysql_update('social_post',$socialPost['num'], null, array('sent' => 1));

  } // social foreach end

  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron

}


// addCronJob('urbcan_sendSalesEmailsToListings', "Send sales emails to listings", '05 0 * * 5');             // Run every hour
// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
pluginAction_addHandlerAndLink(t('Send sales emails to listings'), 'urbcan_sendSalesEmailsToListings', 'admins');
function urbcan_sendSalesEmailsToListings($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive

  //include_once $GLOBALS['SETTINGS']['webRootDir'] . "/main/order-functions.php";

  echo "\nSending sales emails...\n";
  $limit       = 0;
  $group       = 500;

  //$tillDate = date("Y-m-d", strtotime(str_replace('-', '/', date('Y-m-d')) . "-4 days"));
  $tillDate = "2020-10-31";

  
  while(true) {
    $orders = mysql_select_query("SELECT DATE_FORMAT(`createdDate`, '%Y-%m-%d') order_date, DATE_FORMAT(`booking_datetime`, '%Y-%m-%d') schedule_date, num, competitive_percentage, deduct_from_payouts, promo_code, order_number, listingsNum, payout_sent, refund_amount, refund_description, sub_total as subtotal, competitive_price as competitive, discount as discount, order_delivery_type FROM urbanhal_orders WHERE (((DATE_FORMAT(`createdDate`, '%Y-%m-%d')) < '". $tillDate ."' AND (`booking_datetime` IS NULL OR `booking_datetime` = '0000-00-00 00:00:00')) OR ((DATE_FORMAT(`booking_datetime`, '%Y-%m-%d')) < '". $tillDate ."' AND (`booking_datetime` IS NOT NULL OR `booking_datetime` != '0000-00-00 00:00:00'))) AND order_status = 'delivered' ORDER BY listingsNum DESC LIMIT $limit, $group");

    if(!$orders) { echo "No more orders found!...\n"; break; }
    
    $payouts = [];

    foreach ($orders as $order) {

      $refundHtml = '';

      $discount = $refund = $refundCount = $discountCount = $pickupCommission = $deliveryCommission = 0;

      if(!empty($order['promo_code'])) {

        $promoDiscount = mysql_get("promo_codes", null,"`name` = '".$order['promo_code']."'","`deduct_from_payouts`");

        if($promoDiscount['deduct_from_payouts'] == 1){

          $discount = $order['discount'];
          $discountCount++;
        }

      }


      $order['competitive_percentage'] = empty($order['competitive_percentage']) ? 0 : $order['competitive_percentage'];

      if($order['deduct_from_payouts'] == 1){

        $refundCompetitive = ($order['refund_amount'] * $order['competitive_percentage']) / 100;

        $refund = $order['refund_amount'] - $refundCompetitive;

        if($refund > 0){

          $refundHtml = 
          '<table width="100%" cellspacing="0" cellpadding="0">
          <tbody>
          <tr>
          <td style="padding: 10px 20px 0;" colspan="3">
          <table width="100%" cellspacing="0" cellpadding="0" style="margin:0;padding:0 10px 0 10px;border: 1px solid #cccccc;border-radius: 5px;font-weight: 700;font-size: 12px;min-width: 100%;">
          <tbody>
          <tr>
          <td align="center" colspan="3">
          <p style="font-size:16px;">
          <b>ORDER #' . $order['order_number'] . '</b>
          </p>
          </td>
          </tr>
          <tr>
          <td colspan="2" align="left">
          <p style="color: #d93549;margin-top:10px;font-size: 12px;margin-bottom: 5px;">REFUNDS</p>
          </td>
          <td align="right">
          <p style="color: #d93549;margin-top:10px;font-size: 12px;margin-bottom: 5px;">- $'. formatPrice($refund) . '</p>
          </td>
          </tr>
          <tr>
          <td colspan="3" align="left">
          <p style="color: #999999;margin-top:10px;font-size: 12px;margin-bottom: 5px;">'.$order['refund_description'].'</p>
          </td>
          </tr>
          </tbody>
          </table>
          </td>
          </tr>
          </tbody>
          </table>';


          $refundCount++;
        }

      }

      if(!array_key_exists($order['listingsNum'], $payouts)){

        $listing = mysql_get("stripe_accounts", null, "`listingsNum` = {$order['listingsNum']}", "`pickup_commission_fee`, `delivery_commission_fee`, `stripe_account_id`");
        
      }

      $subTotal = $order['subtotal'] - $order['competitive'];

      $orderType = $order['order_delivery_type'];
      //$commissionInPercentage = $orderType === "pickup" ? $listing['pickup_commission_fee'] : $listing['delivery_commission_fee'];

      if($orderType === "pickup"){
        $commissionInPercentage = $listing['pickup_commission_fee'];
        $commission = ($subTotal * $listing['pickup_commission_fee']) / 100;

        $pickupCommission = $commission;
      }else{
        $commissionInPercentage = $listing['delivery_commission_fee'];
        $commission = ($subTotal * $listing['delivery_commission_fee']) / 100;

        $deliveryCommission = $commission;
      }

     // $commission = ($subTotal * $commissionInPercentage) / 100;
      
      $total = $subTotal - $commission - $discount - $refund;

      if(array_key_exists($order['listingsNum'], $payouts)) {

        array_push($payouts[$order['listingsNum']]['order_ids'], $order['num']);

        $payouts[$order['listingsNum']] = [
          "subtotal"          => $payouts[$order['listingsNum']]['subtotal'] + $subTotal,
          "total"             => $payouts[$order['listingsNum']]['total'] + $total,
          "commission"        => $payouts[$order['listingsNum']]['commission'] + $commission,
          "discount"          => $payouts[$order['listingsNum']]['discount'] + $discount,
          "order_ids"         => $payouts[$order['listingsNum']]['order_ids'],
         // "stripe_account_id" => $listing['stripe_account_id'],
          "commission_percentage" => $payouts[$order['listingsNum']]['commission_percentage'],
          "refund_amount"     => $payouts[$order['listingsNum']]['refund_amount'] + $refund,
          "pickup_commission_percentage" => $payouts[$order['listingsNum']]['pickup_commission_percentage'],
          "delivery_commission_percentage" => $payouts[$order['listingsNum']]['delivery_commission_percentage'],
          "discount_count"   =>  $payouts[$order['listingsNum']]['discount_count'] + $discountCount,
          "refund_count"     =>  $payouts[$order['listingsNum']]['refund_count'] + $refundCount,
          "refund_html"      =>  $payouts[$order['listingsNum']]['refund_html'].$refundHtml,
          "pickup_commission" => $payouts[$order['listingsNum']]['pickup_commission'] + $pickupCommission,
          "delivery_commission" => $payouts[$order['listingsNum']]['delivery_commission'] + $deliveryCommission
        ];

      }
      else {

        echo "\n-----Calculating sales for listing #{$order['listingsNum']}-----\n";

        $payouts[$order['listingsNum']] = [
          "subtotal"          => $subTotal,
          "total"             => $total,
          "commission"        => $commission,
          "discount"          => $discount,
          "order_ids"         => [$order['num']],
         // "stripe_account_id" => $listing['stripe_account_id'],
          "commission_percentage" => $commissionInPercentage,
          "refund_amount"     => $refund,
          "pickup_commission_percentage" => $listing['pickup_commission_fee'],
          "delivery_commission_percentage" => $listing['delivery_commission_fee'],
          "discount_count"   => $discountCount,
          "refund_count"     => $refundCount,
          "refund_html"      => $refundHtml,
          "pickup_commission" => $pickupCommission,
          "delivery_commission" => $deliveryCommission

        ];
      }

      //mysql_update("orders", $order['num'], null, ['payout_sent' => 1]);
      
    }


    foreach ($payouts as $listingsNum => $payout) {
      
      $listingInfo = mysql_get_query("SELECT urbanhal_accounts.email, urbanhal_listings.name, urbanhal_listings.email as listingEmail FROM urbanhal_listings INNER JOIN urbanhal_accounts ON urbanhal_accounts.num = urbanhal_listings.createdByUserNum WHERE urbanhal_listings.num = $listingsNum");  
      
      $pricesHtml = '<table width="100%" cellspacing="0" cellpadding="0" style="margin:0;padding:0 10px 0 10px;border: 1px solid #cccccc;border-radius: 5px;font-weight: 700;font-size: 12px;min-width: 100%;">
      <tbody>
      <tr>
      <td colspan="2" align="left">
      <p style="color: #2a2a2a;margin-top:10px;font-size: 12px;margin-bottom: 5px;">ORDER SUBTOTAL</p>
      </td>

      <td align="right">
      <p style="color: #2a2a2a;margin-top:10px;font-size: 12px;margin-bottom: 5px;">$'. formatPrice($payout['subtotal']) .'</p>
      </td>
      </tr>';

      if($payout['pickup_commission_percentage'] != $payout['delivery_commission_percentage']){
        
        $pricesHtml .=          '<tr>
        <td colspan="2" align="left">
        <p style="color: #ffbb22;margin-top:10px;font-size: 12px;margin-bottom: 5px;">PICKUP ORDER FEE ('.$payout['pickup_commission_percentage'].'%)</p>
        </td>

        <td align="right">
        <p style="color: #ffbb22;margin-top:10px;font-size: 12px;margin-bottom: 5px;">- $'. formatPrice($payout['pickup_commission']) . '</p>
        </td>
        </tr>
        <tr>
        <td colspan="2" align="left">
        <p style="color: #ffbb22;margin-top:10px;font-size: 12px;margin-bottom: 5px;">DELIVERY ORDER FEE ('.$payout['delivery_commission_percentage'].'%)</p>
        </td>

        <td align="right">
        <p style="color: #ffbb22;margin-top:10px;font-size: 12px;margin-bottom: 5px;">- $'. formatPrice($payout['delivery_commission']) . '</p>
        </td>
        </tr>';

      }
      else{

        $pricesHtml .=          '<tr>
        <td colspan="2" align="left">
        <p style="color: #ffbb22;margin-top:10px;font-size: 12px;margin-bottom: 5px;">COMMISSION ('.$payout['commission_percentage'].'%)</p>
        </td>

        <td align="right">
        <p style="color: #ffbb22;margin-top:10px;font-size: 12px;margin-bottom: 5px;">- $'. formatPrice($payout['commission']) . '</p>
        </td>
        </tr>';
        
      }

      $pricesHtml .=          '<tr>
      <td colspan="2" align="left">
      <p style="color: #d93549;margin-top:10px;font-size: 12px;margin-bottom: 5px;">REFUNDS ('.$payout['refund_count'].')</p>
      </td>

      <td align="right">
      <p style="color: #d93549;margin-top:10px;font-size: 12px;margin-bottom: 5px;">- $'. formatPrice($payout['refund_amount']) . '</p>
      </td>
      </tr>';
/*                              <tr>
                                  <td colspan="2" align="left">
                                      <p style="color: #999999;margin-top:10px;font-size: 12px;margin-bottom: 5px;">PROMOS ('.$payout['discount_count'].')</p>
                                  </td>
                                  <td align="right">
                                      <p style="color: #999999;margin-top:10px;font-size: 12px;margin-bottom: 5px;">- $'. formatPrice($payout['discount']) . '</p>
                                  </td>
                                  </tr>*/
                                  $pricesHtml .=          '<tr>
                                  <td colspan="3" style="border-bottom: 1px solid #cccccc;">
                                  </td>  
                                  </tr>
                                  <tr>
                                  <td colspan="1" align="left">
                                  <p style="color: #2a2a2a;margin-top:10px;font-size: 14px;margin-bottom: 10px;">ORDERS '.count($payout['order_ids']).'</p>
                                  </td>
                                  <td  align="center">
                                  <p style="color: #2a2a2a;margin-top:10px;font-size: 14px;margin-bottom: 10px;">04/01 - 10/31</p>
                                  </td>
                                  <td align="right">
                                  <p style="color: #5bbc2e;margin-top:10px;font-size: 14px;margin-bottom: 10px;">$' . formatPrice($payout['total']) . '</p>
                                  </td>
                                  </tr>
                                  </tbody>
                                  </table>';  

                                  if(!empty($payout['refund_html'])) { 
                                    $payout['refund_html'] = '<table cellspacing="0" cellpadding="0">
                                    <tbody>
                                    <tr>
                                    <td align="center" style="padding: 20px 0 0;">
                                    <p style="font-size: 20px; color: #2a2a2a; font-weight: 600;">REFUNDED ORDERS</p>
                                    </td>
                                    </tr>
                                    <tr>
                                    <td style="padding: 0 0 10px;">
                                    <table border="0" cellpadding="0" cellspacing="0">
                                    <tbody>
                                    <tr>
                                    <td width="10"></td>
                                    <td width="300" height="2" style="border-top: 1px solid #ccc;"></td>
                                    <td width="10"></td>
                                    </tr>
                                    </tbody>
                                    </table>
                                    </td>
                                    </tr>
                                    </tbody>
                                    </table>' . $payout['refund_html'];
                                  }

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

                                  $placeholders = array('refundHtml' => $payout['refund_html'], 'listing.name' => $listingInfo['name'], 'pricesHtml' => $pricesHtml, 'email' => $listingInfo['email'], 'listing.email' => $listingInfo['listingEmail'], 'unsubscribe_url' => $unsubUrl); 

                                  $emailHeaders = emailTemplate_loadFromDB(array(
                                    'template_id'  => 'LISTINGS-SALES-EMAIL',
                                    'placeholders' => $placeholders,
                                  ));

                                  echo "\n-----Sending sales email to listing #$listingsNum-----\n";

                                  $mailErrors = sendMessage($emailHeaders);
                                  if ($mailErrors) { echo "Mail Errors: $mailErrors\r\n"; }
                                  else { echo "Email Sent\r\n"; }

                                }

                                $limit += $group;

                              }

  // return summary message
                              $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron

}


addCronJob('urbcan__updateOrderStatus', "update order status ready", '* * * * *');             // Run every hour
// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
pluginAction_addHandlerAndLink(t('update order status ready'), 'urbcan__updateOrderStatus', 'admins');
function urbcan__updateOrderStatus($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive

  echo "\nupdate Order Status...\n";

  while(true) {

    $ordersData = mysql_select_query("SELECT `urbanhal_orders`.num, `urbanhal_orders`.order_status, `urbanhal_orders`.order_delivery_type, `urbanhal_orders`.order_status_text, `urbanhal_members`.facebook_first_name, `urbanhal_members`.phone_number, `urbanhal_order_detail`.ready_time, `urbanhal_order_detail`.order_ready_time, `urbanhal_order_detail`.ordersNum FROM urbanhal_order_detail INNER JOIN urbanhal_orders ON `urbanhal_orders`.num = `urbanhal_order_detail`.ordersNum INNER JOIN urbanhal_members ON `urbanhal_members`.num = `urbanhal_orders`.membersNum WHERE `urbanhal_orders`.order_status='preparing' AND `urbanhal_orders`.drivethru_order = 0 AND (NOW() > `urbanhal_order_detail`.order_ready_time) ORDER BY `urbanhal_orders`.num DESC");


    /// order status text data get
    $orderStatusText = mysql_get('share_texts', 1, null,'order_ready');

    if(!$ordersData) { echo "No more orders found!...\n"; break; }

    foreach ($ordersData as $orderData) {

      /// order table data update
      $orderStatusUpdate = "ready";

      if($orderData['order_delivery_type'] === "pickup"){
        orderStatusReadySms($orderData);
      }
      mysql_update('orders', $orderData['num'], null, array("order_status" => $orderStatusUpdate, "order_status_text" => $orderStatusText['order_ready']));

      /// order details table data update
      $orderReadyTimeUpdate = date('Y-m-d H:i:s');
      
      mysql_update('order_detail', null, "`ordersNum` = ". $orderData['num'], array("ready_time" => $orderReadyTimeUpdate));
    }
  }

  
  
  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron
}


addCronJob('urbcan_updateOrderStatusPreparing', "update order status preparing", '5-10 7 * * 0-6');
// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
pluginAction_addHandlerAndLink(t('update order status preparing'), 'urbcan_updateOrderStatusPreparing', 'admins');
function urbcan_updateOrderStatusPreparing($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive

  echo "\nupdate Order Status...\n";
  $limit       = 0;
  $group       = 500;

  $orderAcceptTime = mysql_get("order_settings", 1, null, "`accept_order_time`")['accept_order_time'];
  
  while (true) {
    $start = (int)$orderAcceptTime + 5;

    $end = (int)$orderAcceptTime * 3;

    $ordersData = mysql_select_query("SELECT `urbanhal_orders`.num, `urbanhal_orders`.order_status, `urbanhal_orders`.order_status_text, `urbanhal_order_detail`.ordersNum FROM urbanhal_order_detail INNER JOIN urbanhal_orders ON `urbanhal_orders`.num = `urbanhal_order_detail`.ordersNum  WHERE `urbanhal_orders`.order_status='received' AND `urbanhal_orders`.drivethru_order = 1 AND (NOW() > DATE_ADD( `urbanhal_orders`.createdDate, INTERVAL $start SECOND)) ORDER BY `urbanhal_orders`.num DESC LIMIT $limit, $group");

    /// order status text data get
    $orderStatusText = mysql_get('share_texts', 1, null,'order_preparing');

    if(!$ordersData) { echo "No more orders found!...\n"; break; }

    foreach ($ordersData as $orderData) {

      /// order table data update
      $orderStatusUpdate = "preparing";
      mysql_update('orders', $orderData['num'], null, array("order_status" => $orderStatusUpdate, "order_status_text" => $orderStatusText['order_preparing']));

      /// order details table data update
      $orderPreparingTime = date('Y-m-d H:i:s');
      
      mysql_update('order_detail', null, "`ordersNum` = ". $orderData['num'], array("preparing_time" => $orderPreparingTime));
    }

    $limit += $group;
  }
  
  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron
}

addCronJob('urbcan_cartOrderReminder', "Checkout your cart", '* * * * *');
// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
pluginAction_addHandlerAndLink(t('Checkout your cart'), 'urbcan_cartOrderReminder', 'admins');
function urbcan_cartOrderReminder($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive



  $userdata = mysql_select_query("SELECT um.username,um.facebook_picture,um.facebook_first_name,um.facebook_email,ci.membersNum FROM urbanhal_cart_items ci INNER JOIN urbanhal_members um ON ci.membersNum = um.num WHERE ci.createdDate <  (now() - interval 24 HOUR) AND ci.cartremainderemail = 0 GROUP BY um.num");
  $cartItems = mysql_select_query("SELECT ci.num,ci.listingsNum,ci.membersNum,ci.name,ci.price,ci.quantity,ci.createdDate,ci.note,ci.menu_options,ul.address_1,ul.city,ul.name as listingname FROM urbanhal_cart_items ci INNER JOIN urbanhal_listings ul ON ci.listingsNum = ul.num WHERE ci.createdDate <  (now() - interval 1 day) AND ci.cartremainderemail = 0");
  // print_r($userdata);
  // print_r($cartItems);
  // die;
  $changeEmailStatus = $cartItemstemp = [];
  foreach ($cartItems as $key => $value) {
    if(array_key_exists($value['membersNum'], $cartItemstemp)){
      array_push($cartItemstemp[$value['membersNum']], $value);
    }else{
      $cartItemstemp[$value['membersNum']][] = $value;      
    }
    array_push($changeEmailStatus, $value['num']);
  }

  $userdatatemp = [];
  if(count($userdata) > 0){
    foreach ($userdata as $key => $value) {

      $fbName = $value['facebook_first_name'];

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

        $fbName = $value['username'];

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

        $fbName = $value['facebook_email'];

      }
      
      $html = $suggested_products = '';

      $suggested_products = suggestedProducts($value['membersNum']);

      if(array_key_exists($value['membersNum'], $cartItemstemp)){
        $value['products'] = $cartItemstemp[$value['membersNum']];
        $userdatatemp[$value['membersNum']] = $value;
        
        $html .= '<table width="100%" cellspacing="0" cellpadding="0" style="margin:0;padding:0 15px 0 15px;border: 2px solid #EAEAEA;border-radius: 10px;min-width: 100%;background: #FFFFFF;">
                            <tbody>';
        foreach ($value['products'] as $k => $v) {

          $listingAddress = trim($v['address_1'] . ", " . $v['city'], ", ");

          $listingName = $v['listingname'];

          $html .= '<tr>
                    <td colspan="2" align="left">
                        <p style="margin-top:10px;margin-bottom: 5px;font-style: normal;font-weight: bold;font-size: 12px;line-height: 15px;color: #000000;font-family: Montserrat,sans-serif;">
                            <b>' . $v['name'] . '</b>
                        </p>';

        if(!empty($v['menu_options']) && ($v['menu_options'] != '[]')){
            $menuOptions = json_decode($v['menu_options']);
            $options = [];
            foreach($menuOptions as $menuOption){
                $options[] = $menuOption->name." $".$menuOption->price." x ".$v['quantity'];
            }

        $html .= '<p style="margin-top:0;margin-bottom:10px;font-style: normal;font-weight: 600;font-size: 10px;line-height: 12px;color: #6A6A6A;font-family: Montserrat,sans-serif;">
                            ' . implode(", ",$options) . '
                            </p>';

            unset($options);                
        }

        $html .= '<p style="margin-top:0;margin-bottom:10px;font-style: normal;font-weight: 500;font-size: 11px;line-height: 13px;color: #FF001F;font-family: Montserrat,sans-serif;">
                            ' . $v['note'] . '
                        </p>
                    </td>
                    <td align="right">
                        <p style="margin-top:10px;margin-bottom: 5px;font-style: normal;font-weight: bold;font-size: 18px;line-height: 22px;align-items: center;color: #000000;font-family: Montserrat,sans-serif;">
                            <b>' . $v['quantity'] . '</b>
                        </p>
                        <p style="margin-top: 0px;margin-bottom:5px;font-style: normal;font-weight: 500;font-size: 13px;line-height: 16px;text-align: right;color: #6A6A6A;font-family: Montserrat,sans-serif;">
                            $' . $v['price'] * $v['quantity'] . '
                        </p>
                    </td>
                </tr>';        
        }
        $html .= '</tbody>
        </table>';

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

        $placeholders = [
          "facebook_first_name"=>$fbName,
          "facebook_picture"=>$value['facebook_picture'],
          "useremail"=>$value['facebook_email'],
          "products"=>$html,
          'suggested_products'=>$suggested_products,
          "listing.address"=>$listingAddress,
          "listing.name"=>$listingName,
          "unsubscribe_url" => $unsubUrl
        ];
        // print_r($placeholders);

        $emailHeaders = emailTemplate_loadFromDB(array(
          'template_id'  => 'CART-REMINDER-EMAIL',
          'placeholders' => $placeholders,
        ));

        $mailErrors = sendMessage($emailHeaders);
        if ($mailErrors) { echo "Mail Errors: $mailErrors\r\n"; }
        else { echo "Email Sent\r\n"; }
      }
    }
  }
  if(count($changeEmailStatus)>0){
    $cartItemsUpdate = implode(',', $changeEmailStatus);  
    $cartItems = mysql_do("UPDATE urbanhal_cart_items SET cartremainderemail = 1 WHERE num IN ($cartItemsUpdate)");
  }
  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron
}

function suggestedProducts($memeberId){

  $suggested_products = mysql_select_query("SELECT um.name,uoi.num as orderItemNum,um.num as menuNum,uu.urlPath,ul.name as listingName FROM urbanhal_order_items uoi INNER JOIN urbanhal_orders uo ON uo.num = uoi.ordersNum INNER JOIN urbanhal_listings ul ON ul.num  = uo.listingsNum INNER JOIN urbanhal_menu um ON um.num = uoi.productsNum LEFT JOIN urbanhal_uploads uu ON uu.recordNum = um.num AND uu.tableName = 'menu' WHERE uo.membersNum != ".$memeberId." GROUP BY uoi.productsNum ORDER BY rand() LIMIT 6");
  $html = '';
  if(count($suggested_products) > 0){
    $sp = array_chunk($suggested_products, 2);
    
    $html .= '<table border="0" cellpadding="0" cellspacing="0" class="mce-item-table">
    <tbody>';
    
    foreach ($sp as $key => $value) {
      $html .= '<tr>';
      foreach ($value as $k => $v) {
        if(empty($v['urlPath'])){
          $v['urlPath'] = $GLOBALS['SETTINGS']['s3AssetsLink']."default-menu.png";
        }

        $html .= '<td align="center" style="padding: 0; border: 1px solid #ccc; border-radius: 10px;" data-mce-style="padding: 0; border: 1px solid #ccc; border-radius: 10px;">
        <table border="0" cellpadding="0" cellspacing="0" class="mce-item-table">
        <tbody>
        <tr>
        <td align="center" style="min-width: 140px;" data-mce-style="min-width: 140px;">
        <img src="'.$v['urlPath'].'" alt="Avatar" width="140" style="border-radius: 10px 10px 0 0; width: 100%;" data-mce-src="'.$v['urlPath'].'" data-mce-style="border-radius: 10px 10px 0 0; width: 100%;" data-mce-selected="1">
        </td>
        </tr>
        <tr height="70">
        <td align="center">
        <p style="font-size: 18px; color: #5bbc2e; margin-top: 10px; margin-bottom: 0px; font-weight: 100;" data-mce-style="font-size: 18px; color: #5bbc2e; margin-top: 10px; margin-bottom: 0px; font-weight: 100;">'.$v['name'].'</p>
        </td>
        </tr>
        <tr>
        <td align="center">
        <p style="font-size: 14px; color: #2a2a2a; margin-top: 10px; margin-bottom: 0px; font-weight: bold;" data-mce-style="font-size: 14px; color: #2a2a2a; margin-top: 10px; margin-bottom: 0px; font-weight: bold;">
        <b>'.$v['listingName'].'</b>
        </p>
        </td>
        </tr>
        <tr>
        <td align="center" style="padding: 10px;">
        <table border="0" cellpadding="0" cellspacing="0">
        <tbody>
        <tr>
        <td align="center" height="20" style="border: 2px solid #e4e4e4;background: #fff;border-radius: 7px;padding: 6px 8px;vertical-align: middle;"><a href="https://urbanhal.al/ios" ><img src="https://s3-us-west-1.amazonaws.com/urban-halal/static_assets/landing_page/ios-order-logo.png" width="12" height="12" style="cursor: pointer;"></a>&nbsp;<span style="font-size: 15px;font-weight: 700;color: #4a4a4a;text-decoration: none;">ORDER</span>&nbsp;<a href="https://urbanhal.al/android"><img src="https://s3-us-west-1.amazonaws.com/urban-halal/static_assets/landing_page/android-order-logo.png" width="12" height="12" style="cursor: pointer;"></a></td>
        </tr>
        </tbody>
        </table>
        </td>
        </tr>
        <tr>
        <td style="padding: 10px;" data-mce-style="padding: 10px;"></td>
        </tr>
        </tbody>
        </table>
        </td>';
        if($k == 0){
          $html.= '<td align="center" style="padding: 0 15px;" width="20" data-mce-style="padding: 0 15px;"></td>';    
        }
      }
      $html.= '</tr>';
      $html.= '<tr><td><br/></td></tr>';  
    }
    $html.= '</tbody>
    </table>';
  }
  return $html;
}

addCronJob('driveThruSmsOnTheWay', "Drive Sms On The Way", '1,2,3,4,5,30,31,32,33,34 * * * *');
// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
pluginAction_addHandlerAndLink(t('Drive Sms On The Way'), 'driveThruSmsOnTheWay', 'admins');
function driveThruSmsOnTheWay($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive

  $updateSmsStatus = [];
  $localTime = date('Y-m-d H:i:s');

  $ordersData = mysql_select_query("SELECT `urbanhal_orders`.num, `urbanhal_orders`.order_status, `urbanhal_orders`.order_status_text, `urbanhal_order_detail`.ready_time, `urbanhal_order_detail`.order_ready_time, `urbanhal_order_detail`.ordersNum,um.phone_number,`urbanhal_orders`.order_delivery_type,`urbanhal_orders`.shipping_phone_number FROM urbanhal_order_detail INNER JOIN urbanhal_orders ON `urbanhal_orders`.num = `urbanhal_order_detail`.ordersNum INNER JOIN urbanhal_members um ON um.num = urbanhal_orders.membersNum WHERE `urbanhal_orders`.order_status='ready' AND `urbanhal_orders`.drivethru_order = 1 AND ('".$localTime."' > DATE_ADD(`urbanhal_order_detail`.ready_time,INTERVAL 5 MINUTE)) ORDER BY `urbanhal_orders`.num DESC");

  
  $orderStatusText = mysql_get('share_texts', 1, null,'drivethru_otw_sms')['drivethru_otw_sms'];

  if(count($ordersData) > 0){
    foreach ($ordersData as $orderData) {
      array_push($updateSmsStatus, $orderData['num']);
      $phone = '';
      if($orderData['order_delivery_type'] === 'pickup'){
        $phone = $orderData['phone_number'];
      }else if($orderData['order_delivery_type'] === 'delivery'){

        $phone = (isset($orderData['shipping_phone_number'])) ? $orderData['shipping_phone_number'] : $orderData['phone_number'];
      }
      $phone = $phone[0] === "+" ? $phone : "+".$phone;

      sendSMS($phone, $orderStatusText);
    }
  }

  if(count($updateSmsStatus) > 0){
    $orderItemUpdate = implode(',', $updateSmsStatus);  
    mysql_do("UPDATE urbanhal_orders SET order_status = 'otw' WHERE num IN ($orderItemUpdate)");
  }
    // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron
}


/*addCronJob('subscriptionExpire', "Subscription Expire", '* * * * *');
// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
pluginAction_addHandlerAndLink(t('Subscription Expire'), 'subscriptionExpire', 'admins');
function subscriptionExpire($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
    if (!headers_sent()) { 
      header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive

  // $localTime = utcTimeToLocalTime(time(), 'America/Los_Angeles', true, 'Y-m-d H:i:s', 'Y-m-d H:i:s');

  $userSubscription = mysql_select_query("SELECT num,subscription_end_date FROM `urbanhal_user_subscription` WHERE subscription_end_date < now() AND is_expired = 0");

  // print_r($userSubscription);die;
  if(count($userSubscription) > 0){
    $tempSub = [];
    foreach ($userSubscription as $key => $value) {
      array_push($tempSub, $value['num']);
    }

    $subUpdate = implode(',', $tempSub);  
    mysql_do("UPDATE urbanhal_user_subscription SET is_expired = 1 WHERE num IN ($subUpdate)");
  }


  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron
}*/


//addCronJob('urbcan_createDoorstepOrder', "Update drivethru order to doorstep", '1,2,3,4,5,30,31,32,33,34 * * * *');             // Run every hour
// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
pluginAction_addHandlerAndLink(t('Update drivethru order to doorstep'), 'urbcan_createDoorstepOrder', 'admins');
function urbcan_createDoorstepOrder($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive

  include_once('order-functions-v2.php');

  $localTime = date('Y-m-d H:i:s');

  // while(true) {

  $ordersData = mysql_select_query("SELECT `urbanhal_orders`.*, `urbanhal_order_detail`.delivery_vendor,`urbanhal_order_detail`.ready_time,`urbanhal_batch_listings`.delivery_vendor_push_time FROM urbanhal_order_detail INNER JOIN urbanhal_orders ON `urbanhal_orders`.num = `urbanhal_order_detail`.ordersNum  INNER JOIN `urbanhal_batch_listings` ON `urbanhal_batch_listings`.num = `urbanhal_orders`.locationsNum WHERE `urbanhal_orders`.order_status='otw' AND `urbanhal_orders`.order_delivery_type='delivery' AND `urbanhal_orders`.drivethru_order = 1 AND (`urbanhal_order_detail`.postmates_delivery_id IS NULL OR `urbanhal_order_detail`.postmates_delivery_id = '') AND ('".$localTime."' > DATE_ADD( `urbanhal_order_detail`.ready_time, INTERVAL `urbanhal_batch_listings`.delivery_vendor_push_time SECOND)) ORDER BY `urbanhal_orders`.num DESC");

    /// order status text data get
  $orderStatusText = mysql_get('share_texts', 1, null,'order_otw');

if(!$ordersData) { echo "No more orders found!...\n"; /*break;*/ }

foreach ($ordersData as $orderData) {
  echo "\r\nSending drivethru order {$orderData['num']} to doordash\r\n";

  $readytime = 15;

  $orderItems = mysql_select("order_items", "`ordersNum` = '".$orderData['num']."'", "`name`, `quantity`, `size`, `productsNum`");

  $drivethruLoc = mysql_get("batch_listings", $orderData['locationsNum'], null, "`state`, `zip_code`, `city`, `address`");
  $pickupAddress = [
    'state'=>$drivethruLoc['state'],
    'city'=>$drivethruLoc['city'],
    'zip_code'=>$drivethruLoc['zip_code'],
    'street'=>$drivethruLoc['address']
  ];

  if($orderData['delivery_vendor'] == 'doordash'){
    
    list($errorsAndAlerts) = createDoordashDelivery($orderData, $orderItems, $readytime, false, $pickupAddress);

  }else{
    $pickupAddress = $drivethruLoc['address'] . "," . $drivethruLoc['city'] . "," . $drivethruLoc['zip_code'] . " " . $drivethruLoc['state'];
    list($errorsAndAlerts) = createPostmatesDelivery($orderData, $orderItems, $readytime, false, $pickupAddress);
  }
  echo "\r\n$errorsAndAlerts\r\n";
  if (!$errorsAndAlerts) {
        /// order table data update
    $orderStatusUpdate = "otw";
    mysql_update('orders', $orderData['num'], null, array("order_status" => $orderStatusUpdate, "order_status_text" => $orderStatusText['order_otw']));
  }
}
 // }

  // return summary message
$summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron
}


//addCronJob('subscriptionAutoRenewal', "Subscription Auto Renewal", '* * * * *');
// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
pluginAction_addHandlerAndLink(t('Subscription Auto Renewal'), 'subscriptionAutoRenewal', 'admins');
function subscriptionAutoRenewal($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive

  include_once('order-functions-v2.php');  

  $date = date('Y-m-d H:i:s');

  $minRenewalAmount = mysql_get("order_settings", 1, null, "`min_renewal_amount`")["min_renewal_amount"];

  $query = "SELECT uus.num,uus.membersNum,uus.subscription_end_date,uus.subscription_price,umc.stripe_customer_id,uus.subscription_duration,uus.total_order_qty,uus.platform_fee,uus.drivethru_doorstep,uus.small_order_fee,uus.subscription_name,um.facebook_email,uus.subscriptionsNum,uus.delivery_fee,um.username,um.facebook_first_name,us.long_description,uus.subscription_type,uus.total_credits,uus.assign_credits,COALESCE(uus.previous_pending,0) as previous_pending FROM `urbanhal_user_subscription` uus INNER JOIN `urbanhal_members` um ON um.num = uus.membersNum INNER JOIN `urbanhal_member_cards` umc ON umc.membersNum = uus.membersNum INNER JOIN `urbanhal_subscriptions` us ON us.num = uus.subscriptionsNum WHERE uus.assign_credits < ".$minRenewalAmount." AND uus.is_active = 1";
  
  $userSubscription = mysql_select_query($query);

  if(count($userSubscription) > 0){
    $tempSub = [];
    $count = 1;
    foreach ($userSubscription as $key => $value) {
      
      $subscriptions_image_gif = mysql_get("uploads", null, "`tableName` = 'subscriptions' AND `fieldName` = 'image_gif' AND `recordNum` = {$value['subscriptionsNum']}", "`urlPath`");

      $value['image_gif'] = $subscriptions_image_gif['urlPath'];

      $orderTotal = $value['subscription_price'];
      $customerId = @$value['stripe_customer_id'];
      $cardStripeToken = '';
      $payText = "Subscription renewal for user {$value['facebook_email']}";
      $user = ["member_num"=>$value['num']];
      
      if($count > 1){
        $msg = '2nd payment';
        sendSMS('+919034162706', $msg);
        break;
      }

      list($errors, $chargeId) = makePayment(@$cardStripeToken, @$customerId, $orderTotal, $user, $payText);

      sendSMS('+919034162706', $payText);
      
      if($errors){
        sendSMS('+919034162706', $errors);
      }

      if(!$errors){

        $insertData = [
          "createdDate"      => $date,
          "createdByUserNum" => $value['membersNum'],
          "updatedDate"      => $date,
          "updatedByUserNum" => $value['membersNum'],
          "subscription_price"=>$value['subscription_price'],
          "subscription_duration"=>$value['subscription_duration'],
          "membersNum"=>$value['membersNum'],
          "subscription_start_date"=>$value['subscription_end_date'],
          "subscription_end_date"=>$value['subscription_type'] == 'Order' ? date('Y-m-d H:i:s',strtotime('+'.$value['subscription_duration'].' days', strtotime($value['subscription_end_date']))) : date('Y-m-d H:i:s', strtotime('+5 years')),
          "total_order_qty"=>$value['total_order_qty'],
          "pending_order_qty"=>$value['total_order_qty'],
          "platform_fee"=>$value['platform_fee'],
          "drivethru_doorstep"=>$value['drivethru_doorstep'],
          "small_order_fee"=>$value['small_order_fee'],
          "is_active"=>1,
          "subscriptionsNum"=>$value['subscriptionsNum'],
          "subscription_name"=>$value['subscription_name'],
          "delivery_fee"=>$value['delivery_fee'],
          "charge_id"=>$chargeId
        ];

        sendAutoRenwalEmail($value);

        if(mysql_insert('urbanhal_user_subscription', $insertData, true)){
          array_push($tempSub, $value['num']);
        }
      }
      $count++;
    }

    $subUpdate = implode(',', $tempSub);  
    mysql_do("UPDATE urbanhal_user_subscription SET is_active = 2,is_expired = 1 WHERE num IN ($subUpdate)");
  }

  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron
}

function sendAutoRenwalEmail($value){

  if(empty($card_type))
    $card_type = 'visa_card';

  $pricesHtml = '<table width="100%" cellspacing="0" cellpadding="0" style="margin:0;padding:0 10px 0 10px;border: 1px solid #cccccc;border-radius: 5px;font-weight: 700;font-size: 12px;min-width: 100%;">
  <tbody>
  <tr>
  <td colspan="1" align="left">
  <p style="color:#2a2a2a;margin-top:10px;font-size: 12px;margin-bottom: 10px;">
  SUBSCRIPTION TOTAL
  </p>
  </td>
  <td>
  <img width="25" src="' . $GLOBALS["SETTINGS"]['s3AssetsLink'] . $card_type . '.png" />
  </td>
  <td align="right">
  <p style="color: #5bbc2e;margin-top:10px;font-size: 12px;margin-bottom: 10px;">
  $'. formatPrice($value['subscription_price']) . '
  </p>
  </td>
  </tr>
  </tbody>
  </table>';

  $fbName = $value['facebook_first_name'];

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

    $fbName = $value['username'];

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

    $fbName = $value['facebook_email'];

  }

  $unsubUrl = $GLOBALS['SETTINGS']['websiteUrl'].'/unsubscribe.php?e='.$value['facebook_email'];
  
  $placeholders = [
    'useremail' => $value['facebook_email'],
    'facebook_first_name' => $fbName,
    'long_description'=>$value['long_description'],
    'image_gif'=>$value['image_gif'],
    'pricesHtml'=>$pricesHtml,
    'unsubscribe_url' => $unsubUrl
  ];
  
  $emailHeaders = emailTemplate_loadFromDB(array(
    'template_id'  => 'SUBSCRIPTION-AUTO-RENEWAL-EMAIL',
    'placeholders' => $placeholders,
  ));

  sendMessage($emailHeaders);
}

addCronJob('clearEmailLogs', "Clear Email Logs", '0-5 7 * * *');
pluginAction_addHandlerAndLink(t('Clear Email Logs'), 'clearEmailLogs', 'admins');
function clearEmailLogs($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive

  $maxRemainingRecords = 20000;

  //delete email logs 
  $getLogsCount = mysql_select_query("SELECT COUNT(num) as logcount FROM `urbanhal__cron_log`");

  if($getLogsCount[0]['logcount'] > $maxRemainingRecords){
    $deleteCount  = $getLogsCount[0]['logcount'] - $maxRemainingRecords;
    $sql = "DELETE FROM urbanhal__cron_log ORDER BY num ASC LIMIT ".$deleteCount;
    $result = mysql_do($sql);
  }

  //delete api logs 
  $getApiLogsCount = mysql_select_query("SELECT COUNT(num) as logcount FROM `urbanhal_api_log`");

  if($getApiLogsCount[0]['logcount'] > $maxRemainingRecords){
    $deleteCount  = $getApiLogsCount[0]['logcount'] - $maxRemainingRecords;
    $sql = "DELETE FROM urbanhal_api_log ORDER BY num ASC LIMIT ".$deleteCount;
    $result = mysql_do($sql);
  }

    //delete error logs 
  $getErrorLogsCount = mysql_select_query("SELECT COUNT(num) as logcount FROM `urbanhal__error_log`");

  if($getErrorLogsCount[0]['logcount'] > $maxRemainingRecords){
    $deleteCount  = $getErrorLogsCount[0]['logcount'] - $maxRemainingRecords;
    $sql = "DELETE FROM urbanhal__error_log ORDER BY num ASC LIMIT ".$deleteCount;
    $result = mysql_do($sql);
  }
  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron
}

addCronJob('assignBadgesToUser', "Assign Badges To User", '1,2,3,4,5,6,7,8,9,10,31,32,33,34,35,36,37,38,39,40 * * * *');

pluginAction_addHandlerAndLink(t('Assign Badges To User'), 'assignBadgesToUser', 'admins');
function assignBadgesToUser($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive

  $limit = 0;
  $group = 50;
  include_once("lib/viewer_functions.php");

  $date_time  = date('Y-m-d H:i:s');

  $badgesData = mysql_get("badges",null,"'".$date_time."' BETWEEN start_date AND end_date",'badge_type');

  if(!empty($badgesData)){
    while (true) {
      $members = mysql_select('members', "isAdmin = 0 LIMIT $limit, $group");

      if(count($members) <= 0){ echo "No more records found!\n"; break; }
      
      foreach ($members as $key => $value) {
        insertBadgeData($badgesData['badge_type'],$value);
      }
      $limit += $group;
    }
  }
  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron
}



addCronJob('sendNormalOrderToPos', "Send Normal Order To POS", '* * * * *');

pluginAction_addHandlerAndLink(t('Send Normal Order To POS'), 'sendNormalOrderToPos', 'admins');
function sendNormalOrderToPos($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive

  include_once('order-functions-v2.php');

  $limit       = 0;
  $group       = 5;

  $orderAcceptTime = mysql_get("order_settings", 1, null, "`accept_order_time`")['accept_order_time'];

  $start = (int)$orderAcceptTime;
  
  $query = "SELECT uo.num,uo.createdDate,uo.competitive_percentage,uo.competitive_price,uo.delivery_partner_tip,`total`,`listingsNum`,`order_delivery_type`,`drivethru_order`,`membersNum`,`shipping_phone_number`,`sub_total`,`shipping_state`,`shipping_city`,`shipping_zip`,`shipping_address`,`no_contact_delivery`,`order_number`,`promo_code`,`discount`,uod.num as orderDetailNum,uod.delivery_vendor,upd.pos_type,upd.access_token,upd.merchant_id,upd.location_id,um.facebook_first_name,um.phone_number FROM urbanhal_orders uo INNER JOIN urbanhal_order_detail uod ON uod.ordersNum = uo.num INNER JOIN urbanhal_pos_details upd ON upd.listing_id = uo.listingsNum INNER JOIN urbanhal_members um ON um.num = uo.membersNum WHERE `send_to_pos` = 0 AND `drivethru_order` = 0 AND `order_status` = 'received' AND (((NOW() > DATE_ADD(uo.createdDate, INTERVAL $start SECOND)) AND (`booking_datetime` IS NULL OR `booking_datetime` = '0000-00-00 00:00:00')) OR (NOW() > DATE_ADD(`booking_datetime`, INTERVAL $start SECOND)) AND (`booking_datetime` IS NOT NULL OR `booking_datetime` != '0000-00-00 00:00:00')) ORDER BY uo.createdDate DESC LIMIT $limit, $group";
  
  $orders = mysql_select_query($query);
  $orderStatusText = mysql_get('share_texts', 1, null,'order_preparing');
    // print_r($orders);die;
  if(count($orders)> 0){ 
    foreach ($orders as $key => $value) { 
      $orderItems = mysql_select("order_items", "`ordersNum` = '".$value['num']."'", "`name`,`price`,`quantity`,`size`,`productsNum`,`menu_options`");
      $value['order_items'] = $orderItems;
      $value['order_status_text'] = $orderStatusText['order_preparing'];

      if($value['pos_type'] == 1){
        sendOrderToClover($value);
      }else if($value['pos_type'] == 2){
        sendOrderToSquare($value);
      }
    }
  }

    // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron
}


addCronJob('sendDriveThruOrderToPos', "Send DriveThru Order To POS", '5-10 8 * * 0-6');

pluginAction_addHandlerAndLink(t('Send DriveThru Order To POS'), 'sendDriveThruOrderToPos', 'admins');
function sendDriveThruOrderToPos($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive


  $localTime = utcTimeToLocalTime(time(), 'America/Los_Angeles', true, 'Y-m-d H:i:s', 'Y-m-d');

  $query = "SELECT uo.`num`,uo.competitive_percentage,uo.delivery_partner_tip,uo.competitive_price,uo.membersNum,uod.num as orderDetailNum,`drivethru_order`,`drivethru_order_date`,`total`,`promo_code`,`discount`,`sub_total`,`listingsNum`,`order_delivery_type`,uod.delivery_vendor,upd.pos_type,upd.access_token,upd.merchant_id,upd.location_id,um.facebook_first_name,um.phone_number FROM  urbanhal_orders uo INNER JOIN urbanhal_order_detail uod ON uod.ordersNum = uo.num INNER JOIN urbanhal_pos_details upd ON upd.listing_id = uo.listingsNum INNER JOIN urbanhal_members um ON um.num = uo.membersNum WHERE `send_to_pos` = 0 AND uo.order_status='preparing' AND uo.drivethru_order = 1 AND ('".$localTime."' = DATE_FORMAT(uo.drivethru_order_date, '%Y-%m-%d')) ORDER BY `uo`.num DESC";

  $orders = mysql_select_query($query);

  if(count($orders)> 0){

    foreach ($orders as $key => $value) { 
      $orderItems = mysql_select("order_items", "`ordersNum` = '".$value['num']."'", "`name`,`price`,`quantity`,`size`,`productsNum`,`menu_options`");
      $value['order_items'] = $orderItems;
          //print_r($value);
      if($value['pos_type'] == 1){
        sendOrderToClover($value);
      }else if($value['pos_type'] == 2){
        sendOrderToSquare($value);
      }
    }
  }

    // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron
}

// addCronJob('addYelpID', "Get the yelp id", '* * * * *');

pluginAction_addHandlerAndLink(t('Get the yelp id'), 'addYelpID', 'admins');
function addYelpID($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive

  $limit = 0;
  $group = 1;
  $query = "select ul.num,ul.name,ul.latitude,ul.longitude,ul.zip from urbanhal_listings ul LEFT JOIN urbanhal_listings_details uld ON uld.listingsnum = ul.num WHERE uld.yelp_id IS NULL LIMIT $limit,$group";
  $listingData = mysql_select_query($query);
  // $listingData = mysql_select("urbanhal_listings", "`yelp_id` IS NULL ORDER BY num LIMIT $limit, $group",'num,name,latitude,longitude,zip');
  // print_r($listingData);
  // die('testing');

  if(count($listingData) > 0){
    foreach ($listingData as $key => $value) {
      getYelpBusinessId($value);
    }
  }

  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron
}

// addCronJob('getYelpReviews', "Get yelp review for business", '* * * * *');

pluginAction_addHandlerAndLink(t('Get yelp review for business'), 'getYelpReviews', 'admins');
function getYelpReviews($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive

  $limit = 0;
  $group = 1;
  $pastDate  = date('Y-m-d H:i:s', strtotime("-5 days"));

  // echo $pastDate;

  $listingData = mysql_select("urbanhal_listings_details", "`yelp_id` IS NOT NULL AND yelp_last_updated_date < '".$pastDate."' ORDER BY num LIMIT $limit, $group",'num,yelp_id,yelp_last_updated_date,listingsNum');
  
  // print_r($listingData);
  // die('testing');

  if(count($listingData) > 0){
    foreach ($listingData as $key => $value) {
      getYelpBusinessReviews($value);
    }
  }

  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron
}

// addCronJob('orderStatusPickedup', "change order status in for pos", '* * * * *');

pluginAction_addHandlerAndLink(t('change order status in for pos'), 'orderStatusPickedup', 'admins');
function orderStatusPickedup($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive


  $field = strtolower(date("l"));
  $time = date("H:i:s");

  $localTime = utcTimeToLocalTime(time(), 'America/Los_Angeles', true, 'Y-m-d H:i:s', 'H:i:s');

  $decimalTime = decimal($localTime);

  $query = "SELECT urbanhal_orders.num,".$field."_close FROM `urbanhal_orders` INNER JOIN urbanhal_listings on urbanhal_listings.num = urbanhal_orders.listingsNum WHERE (order_status = 'ready' || order_status = 'otw') and order_delivery_type = 'pickup'";
  $data = mysql_select_query($query);
  if(count($data) > 0){
    foreach($data as $k => $v){
      if($v[$field.'_close'] == '24hours' && $decimalTime >= '23.90'){    
        mysql_update('orders', $v['num'], null, array("order_status" => 'delivery', "order_status_text" => 'ORDER DELIVERED'));
      }else if($v[$field.'_close'] != '24hours' && $decimalTime >= $v[$field.'_close']){
        mysql_update('orders', $v['num'], null, array("order_status" => 'delivery', "order_status_text" => 'ORDER DELIVERED'));
      }
    }
  }

  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron
}

// addCronJob('getListingDataYelp', "Get Listing Data Yelp", '* * * * *');

pluginAction_addHandlerAndLink(t('Get Listing Data Yelp'), 'getListingDataYelp', 'admins');
function getListingDataYelp($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive
  $limit = 0;
  $group = 2;

  $data = mysql_select('us',"is_processed ='0' ORDER BY num LIMIT $limit, $group",'`num`,`zipcode`,`latitude`,`longitude`');
  
    if(count($data) > 0){
      foreach ($data as $key => $value) {  
        yelpListingData($value);
      }
    }
  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron
}

// addCronJob('updateYelpListingData', "Update Yelp Listing Data", '* * * * *');

pluginAction_addHandlerAndLink(t('Update Yelp Listing Data'), 'updateYelpListingData', 'admins');
function updateYelpListingData($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive
  $limit = 0;
  $group = 5;

  $data = mysql_select('urbanhal_listings_details',"is_processed = 0 AND isyelplisting = 1 ORDER BY num LIMIT $limit, $group",'`num`,`listingsnum`,`yelp_id`');

  if(count($data) > 0){
    foreach ($data as $key => $value) {
      getYelpListingDetails($value);
    }
  }

  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron
}

// addCronJob('updateYelpListingPhoto', "Update Yelp Listing Photo", '* * * * *');

pluginAction_addHandlerAndLink(t('Update Yelp Listing Photo'), 'updateYelpListingPhoto', 'admins');
function updateYelpListingPhoto($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive
  $limit = 0;
  $group = 2;

  $data = mysql_select('urbanhal_listings_details',"is_processed = 1 AND isyelplisting = 1 AND photo_processed = 0 ORDER BY num LIMIT $limit, $group",'`num`,`listingsnum`,`yelp_id`');

  if(count($data) > 0){
    foreach ($data as $key => $value) {
      getYelpListingPhotos($value);
    }
  }

  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron
}

pluginAction_addHandlerAndLink(t('Insert menu image into photo uploads'), 'menuImageToPhotoUploads', 'admins');
function menuImageToPhotoUploads($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive
  $limit = 0;
  $group = 1;

  $listings  = mysql_select_query("SELECT urbanhal_listings.num,urbanhal_uploads.urlPath FROM urbanhal_listings LEFT JOIN urbanhal_photo_uploads ON urbanhal_listings.num = urbanhal_photo_uploads.listingsNum AND urbanhal_photo_uploads.for_photo = 'photo' AND urbanhal_photo_uploads.flagged = 0 LEFT JOIN urbanhal_uploads ON urbanhal_photo_uploads.num = urbanhal_uploads.recordNum AND urbanhal_uploads.tableName = 'photo_uploads' AND urbanhal_uploads.fieldName = 'photos'");

  $listingNums = $menuUpload = $menuPhotoUpload = [];
  if(count($listings) > 0){
    foreach($listings as $listing){
      if(!($listing['urlPath'])){
        $listingNums[] = $listing['num'];
      }
    }
  }
  $listingNums = implode(',', $listingNums);
  
  $menus = mysql_select_query("SELECT `uploads`.preSaveTempId,`uploads`.urlPath,`uploads`.recordNum,`uploads`.order,`uploads`.tableName,`uploads`.fieldName,`uploads`.filePath,`uploads`.width,`uploads`.height,`uploads`.thumbFilePath,`uploads`.thumbUrlPath,`uploads`.thumbWidth,`uploads`.thumbHeight,`uploads`.thumbFilePath2,`uploads`.thumbUrlPath2,`uploads`.thumbWidth2,`uploads`.thumbHeight2,`uploads`.thumbFilePath3,`uploads`.thumbUrlPath3,`uploads`.thumbWidth3,`uploads`.thumbHeight3,`uploads`.thumbFilePath4,`uploads`.thumbUrlPath4,`uploads`.thumbWidth4,`uploads`.thumbHeight4,`uploads`.info1,`uploads`.info2,`uploads`.info3,`uploads`.info4,`uploads`.info5,`uploads`.storage,`urbanhal_menu`.listingsnum,`urbanhal_menu`.num as menuNum FROM `urbanhal_menu` INNER JOIN `urbanhal_uploads` as `uploads` ON `uploads`.recordNum = `urbanhal_menu`.num AND `uploads`.tableName = 'menu' WHERE `urbanhal_menu`.listingsNum IN (".$listingNums.") ORDER BY `urbanhal_menu`.createdDate");
 //print_r($menus); exit();
  foreach($menus as $menu){
    $menuUpload[] = $menu['menuNum'];
  }

  $uploadsMenus = mysql_select_query("SELECT `urbanhal_photo_uploads`.menu_id from `urbanhal_photo_uploads` where `urbanhal_photo_uploads`.listingsNum IN (".$listingNums.")");
//print_r($uploadsMenus);
  foreach($uploadsMenus as $uploadsMenu){
    $menuPhotoUpload[] = $uploadsMenu['menu_id'];
  }

  $menuIds = array_diff($menuUpload,$menuPhotoUpload);
  
  if($menuIds){

    $membersNum = 44;
    
    $insertUploadRecords = "INSERT INTO urbanhal_uploads (`order`,`createdTime`,`tableName`,`fieldName`,`recordNum`,`preSaveTempId`,`filePath`,`urlPath`,`width`,`height`,`thumbFilePath`,`thumbUrlPath`,`thumbWidth`,`thumbHeight`,`thumbFilePath2`,`thumbUrlPath2`,`thumbWidth2`,`thumbHeight2`,`thumbFilePath3`,`thumbUrlPath3`,`thumbWidth3`,`thumbHeight3`,`thumbFilePath4`,`thumbUrlPath4`,`thumbWidth4`,`thumbHeight4`,`info1`,`info2`,`info3`,`info4`,`info5`,`storage`) VALUES ";

    foreach($menus as $menu){
      if(in_array($menu['menuNum'], $menuIds)){

        $path_parts = pathinfo($menu['urlPath']);

        $insertRecord = mysql_insert("urbanhal_photo_uploads", ["listingsNum"=>$menu['listingsnum'],"menu_id"=>$menu['recordNum'],"flagged"=>0,"for_photo"=>"photo","points"=>"25",'createdDate' => date("Y-m-d H:i:s"),'updatedDate' => date("Y-m-d H:i:s"),'createdByUserNum' => $membersNum,'updatedByUserNum' => $membersNum,'membersNum'=>$membersNum], true);

        $insertUploadRecords.= "(".$menu['order'].",'".date('Y-m-d H:i:s')."','photo_uploads','photos',".$insertRecord.",'".$menu['preSaveTempId']."','".$menu['filePath']."','".$menu['urlPath']."',".$menu['width'].",".$menu['height'].",'".$menu['thumbFilePath']."','".$menu['thumbUrlPath']."',".$menu['thumbWidth'].",".$menu['thumbHeight'].",'".$menu['thumbFilePath2']."','".$menu['thumbUrlPath2']."',".$menu['thumbWidth2'].",".$menu['thumbHeight2'].",'".$menu['thumbFilePath3']."','".$menu['thumbUrlPath3']."',".$menu['thumbWidth3'].",".$menu['thumbHeight3'].",'".$menu['thumbFilePath4']."','".$menu['thumbUrlPath4']."',".$menu['thumbWidth4'].",".$menu['thumbHeight4'].",'".$menu['info1']."','".$menu['info2']."','".$menu['info3']."','".$menu['info4']."','".$menu['info5']."','".$menu['storage']."'),";

      }
    }

    if($insertUploadRecords){
      mysql_do(rtrim($insertUploadRecords,",")) or dieAsCaller("MySQL Error: " .mysqli()->error. "\n");
    }
  }
  
  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron
}





//addCronJob('urbcan_updateDrivethruOrderStatus', "update drivethru order status ready", '* * * * *');             // Run every hour
// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
pluginAction_addHandlerAndLink(t('update drivethru order status ready'), 'urbcan_updateDrivethruOrderStatus', 'admins');
function urbcan_updateDrivethruOrderStatus($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive

  echo "\nupdate Order Status...\n";

  $localTime = utcTimeToLocalTime(time(), 'America/Los_Angeles', true, 'Y-m-d H:i:s', 'Y-m-d H:i:s');

  while(true) {

    $ordersData = mysql_select_query("SELECT `urbanhal_orders`.num, `urbanhal_orders`.order_status, `urbanhal_orders`.order_delivery_type, `urbanhal_orders`.order_status_text, `urbanhal_members`.facebook_first_name, `urbanhal_members`.phone_number, `urbanhal_order_detail`.ready_time, `urbanhal_order_detail`.order_ready_time, `urbanhal_order_detail`.ordersNum FROM urbanhal_order_detail INNER JOIN urbanhal_orders ON `urbanhal_orders`.num = `urbanhal_order_detail`.ordersNum INNER JOIN urbanhal_members ON `urbanhal_members`.num = `urbanhal_orders`.membersNum WHERE `urbanhal_orders`.order_status='preparing' AND `urbanhal_orders`.drivethru_order = 1 AND ('".$localTime."' > DATE_SUB(`urbanhal_orders`.drivethru_order_date,INTERVAL 1 HOUR)) ORDER BY `urbanhal_orders`.num DESC");

//print_r($ordersData);exit();
    /// order status text data get
    $orderStatusText = mysql_get('share_texts', 1, null,'order_ready');

    if(!$ordersData) { echo "No more orders found!...\n"; break; }

    foreach ($ordersData as $orderData) {

      /// order table data update
      $orderStatusUpdate = "ready";

      if($orderData['order_delivery_type'] === "pickup"){
        orderStatusReadySms($orderData);
      }
      mysql_update('orders', $orderData['num'], null, array("order_status" => $orderStatusUpdate, "order_status_text" => $orderStatusText['order_ready']));

      /// order details table data update
      $orderReadyTimeUpdate = date('Y-m-d H:i:s');
      
      mysql_update('order_detail', null, "`ordersNum` = ". $orderData['num'], array("ready_time" => $orderReadyTimeUpdate));
    }
  }
  
  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron
}


//addCronJob('updateAmenitiesForListings', "Update Amenities For Listings", '* * * * *');
// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
pluginAction_addHandlerAndLink(t('Update Amenities For Listings'), 'updateAmenitiesForListings', 'admins');
function updateAmenitiesForListings($includeComments = true){

if (!inCLI()) { // send headers (for running through web with "Run Manually" link above)
if (!headers_sent()) {
  header("Content-type: text/plain");
header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
ob_disable(); // Turn off browser buffering
}
// This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
// $CMS_USER = getCurrentUserFromCMS(); // security check for web access - don't show cron filepaths unless logged in
// if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
ignore_user_abort( true ); // continue running even if user clicks stop on their browser
session_write_close(); // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
}
set_time_limit(0); // ignore PHP's max_execution_time directive

$query = "SELECT ul.num,ul.name,ul.kids_menu,ul.alcohol,ul.pray_space,ul.organic,ul.catering,ul.cash_only,ul.parking,ul.wifi,ul.wheel_chair_access,uld.is_amenitiesprocessed,uld.yelp_id,uld.num as listingDetailsNum FROM urbanhal_listings ul LEFT JOIN urbanhal_listings_details uld ON uld.listingsnum = ul.num WHERE (uld.is_amenitiesprocessed = 0 || uld.is_amenitiesprocessed IS NULL) LIMIT 0,5";

$data = mysql_select_query($query);
$amenities = mysql_select("amenities","TRUE","`num`,`name`");

$am = [];
foreach ($amenities as $key => $value) {
  $am[strtolower($value['name'])] = $value;
}

if(count($data) > 0){

  foreach ($data as $key => $value) {
    $updateValue = "=";
    if(($value['kids_menu'] == 1 || $value['kids_menu'] == '1') && isset($am['kids menu'])){
      $updateValue .= $am['kids menu']['num']."=";
    }
    if(($value['wifi'] == 1 || $value['wifi'] == '1') && isset($am['wifi'])){
      $updateValue .= $am['wifi']['num']."=";
    }
    if(($value['alcohol'] == 1 || $value['alcohol'] == '1') && isset($am['alcohol served'])){
      $updateValue .= $am['alcohol served']['num']."=";
    }
    if(($value['organic'] == 1 || $value['organic'] == '1') && isset($am['organic'])){
      $updateValue .= $am['organic']['num']."=";
    }
    if(($value['catering'] == 1 || $value['catering'] == '1') && isset($am['catering'])){
      $updateValue .= $am['catering']['num']."=";
    }
    if(($value['pray_space'] == 1 || $value['pray_space'] == '1') && isset($am['pray space'])){
      $updateValue .= $am['pray space']['num']."=";
    }
    if(($value['cash_only'] == 1 || $value['cash_only'] == '1') && isset($am['cash only'])){
      $updateValue .= $am['cash only']['num']."=";
    }
    if(($value['wheel_chair_access'] == 1 || $value['wheel_chair_access'] == '1') && isset($am['wheel chair access'])){
      $updateValue .= $am['wheel chair access']['num']."=";
    }
    if(($value['parking'] != '0' || $value['parking'] != 0) && isset($am['parking'])){
      $updateValue .= $am['parking']['num']."=";
    }

    $replaced = str_replace("=", '\t', $updateValue);
    $update = "update urbanhal_listings SET amenities='".$replaced."' where num = ".$value['num'];

    if(empty($value['listingDetailsNum'])){
      $insertData['updatedByUserNum'] = 1;
      $insertData['createdByUserNum'] = 1;
      $insertData['listingsnum'] = $value['num'];
      $insertData['is_amenitiesprocessed'] = 1;
      mysql_insert('listings_details', $insertData,true);
    }else{
      $updateArray['is_amenitiesprocessed'] = 1;
      mysql_update('listings_details',$value['listingDetailsNum'], null, $updateArray);
    }

    mysql_do($update);
  }

//update in the listing details
}else{
//send alert
}

// return summary message
$summary = "Successful";
if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; } // exit if being run manually from web
return $summary; // otherwise, return summary if being run by cron
}




//addCronJob('squareAuthorizationAccess', "Square Authoriztion Access for Listings", '* * * * *');
// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
pluginAction_addHandlerAndLink(t('Square Authoriztion Access for Listings'), 'squareAuthorizationAccess', 'admins');
function squareAuthorizationAccess($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive

  $accounts = mysql_select("accounts","TRUE","`num`,`last_name`");
  $accNums = $accessNums = $lowerAccess = [];

  if(count($accounts) > 0){
    foreach($accounts as $account){
      if(is_numeric($account['last_name'])){
        $accNums[] = $account['num'];
      }
    }
  }

  $accountNums = implode(',', $accNums);
  
  $accountAccesses = mysql_select_query("SELECT uac.userNum,uac.accessLevel from urbanhal__accesslist uac where uac.userNum IN (".$accountNums.") AND uac.tableName = 'square_authorization'");

  if(count($accountAccesses) > 0){
    foreach($accountAccesses as $accountAccess){
      if($accountAccess['accessLevel'] >= 7){
        $accessNums[] = $accountAccess['userNum'];
      }else{
        $lowerAccess[] = $accountAccess['userNum'];
      }
    }
  }

  if($lowerAccess){
    $records = implode(',', $lowerAccess);
    $updateRecords = "UPDATE  urbanhal__accesslist SET accessLevel = 7 where userNum in (".$records.") and tableName = 'square_authorization'";

    if($updateRecords){
      mysql_do($updateRecords) or dieAsCaller("MySQL Error: " .mysqli()->error. "\n");
      foreach($lowerAccess as $l){
        array_push($accessNums,$l);
      }
    }
  }
  
  $diffIds = array_diff($accNums,$accessNums);
  if($diffIds){
    $insertUploadRecords = "INSERT INTO urbanhal__accesslist (`userNum`,`tableName`,`accessLevel`,`randomSaveId`) VALUES ";

    foreach($accounts as $a){
      if(in_array($a['num'],$diffIds)){
        $randomSaveId = uniqid('', true);
        $tableName = "square_authorization";
        $insertUploadRecords .= "(".$a['num'].",'".$tableName."',7,'".mysql_escape($randomSaveId)."'),";
      }
    }

    if($insertUploadRecords){
      mysql_do(rtrim($insertUploadRecords,",")) or dieAsCaller("MySQL Error: " .mysqli()->error. "\n");
    }
  }
  
  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron
}


addCronJob('getRefreshedTokenForSquare', "Get Refreshed Access Token for square", '* * * * *');
// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
pluginAction_addHandlerAndLink(t('Get Refreshed Access Token for square'), 'getRefreshedTokenForSquare', 'admins');
function getRefreshedTokenForSquare($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive

  $limit = 0;
  $group = 1;
  $currentDate  = date('Y-m-d H:i:s');
  
  $posData = mysql_select("pos_details", "'".$currentDate."' > DATE_SUB(token_expiry_date,INTERVAL 7 DAY) AND pos_type = '2' ORDER BY num","num,refresh_token,updatedDate,merchant_id");
  
  if(count($posData) > 0){
    foreach ($posData as $key => $value) {
      refreshAccessToken($value);
    }
  }

  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron
}

// addCronJob('mondayWeeklyEmail', "New Listings On Monday", '* * * * *');
// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
pluginAction_addHandlerAndLink(t('New Listings On Monday'), 'mondayWeeklyEmail', 'admins');
function mondayWeeklyEmail($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive

  $email = getAllEmails();
  if(count($email)>0){
    $listingsMenuQuery = "SELECT ul.num,ul.name,um.name as menuName,uu.urlPath FROM `urbanhal_listings` ul INNER JOIN urbanhal_menu um ON um.listingsNum = ul.num LEFT JOIN urbanhal_uploads  uu ON uu.tableName = 'menu' and uu.recordNum = um.num WHERE ul.createdDate >= DATE_ADD(now(), INTERVAL -7 DAY) ORDER BY ul.createdDate DESC";

    $listingsMenuData = mysql_select_query($listingsMenuQuery);
  
    $object = [];
    if(count($listingsMenuData) > 0){
      foreach ($listingsMenuData as $key => $value) {
        if(array_key_exists($value['num'], $object)){
          if(count($object[$value['num']]) < 4){
            array_push($object[$value['num']], $value);
          }
        }else{
          $object[$value['num']][] = $value;
        }
      }
    }

    $products =  productsData($object);
  
    foreach ($email as $a => $e) {
      $placeholders = [
        "username"=>$e,
        'suggested_products'=>$products
      ];

      $emailHeaders = emailTemplate_loadFromDB(array(
        'template_id'  => 'MONDAY-NEW-LISTINGS',
        'placeholders' => $placeholders
      ));

      $emailHeaders['to'] = $e;
      $mailErrors = sendMessage($emailHeaders);

      if($mailErrors) {
        echo "Mail errror: " . $mailErrors . "\n";
      }
    }
  }

  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron
}

// addCronJob('wednesDayWeeklyEmail', "New Listings On WednessDay", '* * * * *');
// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
pluginAction_addHandlerAndLink(t('New Listings On WednessDay'), 'wednesDayWeeklyEmail', 'admins');
function wednesDayWeeklyEmail($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive

  $email = getAllEmails();
  if(count($email)>0){
    $orderQuery = "SELECT uo.num,uo.listingsNum,uoi.name as menuName,uu.urlPath FROM urbanhal_orders uo LEFT JOIN urbanhal_order_items uoi ON uoi.ordersNum = uo.num INNER JOIN urbanhal_uploads uu ON uu.recordNum = uoi.productsNum AND uu.tableName = 'menu'  WHERE uo.createdDate >= DATE_ADD(now(), INTERVAL -7 DAY) ORDER BY uo.num DESC";
    $orderData = mysql_select_query($orderQuery);

    $object = [];
    if(count($orderData) > 0){
      foreach ($orderData as $key => $value) {
        if(array_key_exists($value['listingsNum'], $object)){
          if(count($object[$value['listingsNum']]) < 2){
            array_push($object[$value['listingsNum']], $value);
          }
        }else{
          $object[$value['listingsNum']][] = $value;
        }
      }
    }

    $products =  productsData($object);

    foreach ($email as $a => $e) {
      $placeholders = [
        "username"=>$e,
        'suggested_products'=>$products
      ];

      $emailHeaders = emailTemplate_loadFromDB(array(
        'template_id'  => 'WEDNESDAY-NEW-LISTINGS',
        'placeholders' => $placeholders
      ));
      
      $emailHeaders['to'] = $e;
      $mailErrors = sendMessage($emailHeaders);

      if($mailErrors) {
        echo "Mail errror: " . $mailErrors . "\n";
      }
    }
  }

  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron
}

function getAllEmails(){
  $email = [];
  $subscriberSql  = "SELECT email FROM `urbanhal__nlb_subscribers` WHERE confirmed = 1";
  $subscriberData = mysql_select_query($subscriberSql);

  $memberSql = "SELECT facebook_email FROM `urbanhal_members` WHERE facebook_email IS NOT NULL || facebook_email != ''";
  $memberData = mysql_select_query($memberSql);

  if(count($subscriberData) > 0){
    foreach ($subscriberData as $key => $value) {
      array_push($email, $value['email']);
    }
  }

  if(count($memberData) > 0){
    foreach ($memberData as $key => $value) {
      array_push($email, $value['facebook_email']);
    }
  } 
  
  $email = array_unique($email);
  return $email;
}

function productsData($object){
  $html = '';
  if(count($object) > 0){
    $html .= '<table border="0" cellpadding="0" cellspacing="0" class="mce-item-table">
    <tbody>';
    foreach ($object as $key => $value) {
      $listing = mysql_get('listings', $key,null,'name');
      $html .= '<tr>
        <td style="text-align: center;margin: 0;padding: 7px 0px 7px 0px;font-size: 14px;font-weight: bold;border: 1px solid #ccc;border-radius: 5px;line-height: 15px;" colspan="3">'.$listing['name'].'</td>
      </tr> <tr><td><br></td></tr>';
      $sp = array_chunk($value, 2);
      foreach ($sp as $x => $y) {
        $html.= '<tr>';
        foreach ($y as $k => $v) {
          if(empty($v['urlPath'])){
            $v['urlPath'] = $GLOBALS['SETTINGS']['s3AssetsLink']."default-menu.png";
          }
        $html .= '<td align="center" style="padding: 0; border: 1px solid #ccc; border-radius: 10px;" data-mce-style="padding: 0; border: 1px solid #ccc; border-radius: 10px;">
        <table border="0" cellpadding="0" cellspacing="0" class="mce-item-table">
        <tbody>
        <tr>
        <td align="center" style="min-width: 140px;" data-mce-style="min-width: 140px;">
        <img src="'.$v['urlPath'].'" alt="Avatar" width="140" style="border-radius: 10px 10px 0 0; width: 100%;" data-mce-src="'.$v['urlPath'].'" data-mce-style="border-radius: 10px 10px 0 0; width: 100%;" data-mce-selected="1">
        </td>
        </tr>
        <tr>
        <td align="center">
        <p style="font-size: 14px; color: #2a2a2a; margin-top: 10px; margin-bottom: 0px; font-weight: bold;" data-mce-style="font-size: 14px; color: #2a2a2a; margin-top: 10px; margin-bottom: 0px; font-weight: bold;">
        <b>'.$v['menuName'].'</b>
        </p>
        </td>
        </tr>
        <tr>
        <td align="center" style="padding: 10px;">
        <table border="0" cellpadding="0" cellspacing="0">
        <tbody>
        <tr>
        <td align="center" height="20" style="border: 2px solid #e4e4e4;background: #fff;border-radius: 7px;padding: 6px 8px;vertical-align: middle;"><a href="https://urbanhal.al/ios" ><img src="https://s3-us-west-1.amazonaws.com/urban-halal/static_assets/landing_page/ios-order-logo.png" width="12" height="12" style="cursor: pointer;"></a>&nbsp;<span style="font-size: 15px;font-weight: 700;color: #4a4a4a;text-decoration: none;">ORDER</span>&nbsp;<a href="https://urbanhal.al/android"><img src="https://s3-us-west-1.amazonaws.com/urban-halal/static_assets/landing_page/android-order-logo.png" width="12" height="12" style="cursor: pointer;"></a></td>
        </tr>
        </tbody>
        </table>
        </td>
        </tr>
        <tr>
        <td style="padding: 10px;" data-mce-style="padding: 10px;"></td>
        </tr>
        </tbody>
        </table>
        </td>';
        }
        $html.= '</tr>';
      }
      $html.= '<tr><td><br/></td></tr>';
    }
    $html.= '</tbody>
    </table>';
  }
  return $html;
}


/*addCronJob('afterFirstOrder', "Email After First Order", '* * * * *');*/
// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
pluginAction_addHandlerAndLink(t('Email After First Order'), 'afterFirstOrder', 'admins');
function afterFirstOrder($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive

  $update = [];
  $orderQuery = "SELECT uo.membersNum,um.username,um.facebook_email,um.last_send_email,COUNT(uo.num) as orderCount FROM urbanhal_orders uo INNER JOIN urbanhal_members um ON um.num = uo.membersNum WHERE um.last_send_email = 1 GROUP BY uo.membersNum HAVING orderCount = 1";

  $orderData = mysql_select_query($orderQuery);
  $recentOrdersData = getRecentMenuItems();
  
  if(count($orderData) > 0){
    sendEmailToUsers($orderData,$recentOrdersData, 'Sales Code','SECOND-ORDER-COUPON-CODE',2);
  }

  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron
}


/*addCronJob('afterSecondOrder', "Email After Second Order", '* * * * *');*/
// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
pluginAction_addHandlerAndLink(t('Email After Second Order'), 'afterSecondOrder', 'admins');
function afterSecondOrder($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive

  $orderQuery = "SELECT uo.membersNum,um.username,um.facebook_email,um.last_send_email,COUNT(uo.num) as orderCount FROM urbanhal_orders uo INNER JOIN urbanhal_members um ON um.num = uo.membersNum WHERE um.last_send_email = 2 GROUP BY uo.membersNum HAVING orderCount = 2";

  $orderData = mysql_select_query($orderQuery);
  $recentOrdersData = getRecentMenuItems();

  if(count($orderData) > 0){
    sendEmailToUsers($orderData,$recentOrdersData, 'Sales Code','THIRD-ORDER-COUPON-CODE',3);
  }

  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron
}

/*addCronJob('afterThirdOrder', "Email After Third Order", '* * * * *');*/
// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
pluginAction_addHandlerAndLink(t('Email After Third Order'), 'afterThirdOrder', 'admins');
function afterThirdOrder($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive

  $orderQuery = "SELECT uo.membersNum,um.username,um.facebook_email,um.last_send_email,COUNT(uo.num) as orderCount FROM urbanhal_orders uo INNER JOIN urbanhal_members um ON um.num = uo.membersNum WHERE um.last_send_email = 3 GROUP BY uo.membersNum HAVING orderCount = 3";

  $orderData = mysql_select_query($orderQuery);
  $recentOrdersData = getRecentMenuItems();

  if(count($orderData) > 0){
    sendEmailToUsers($orderData,$recentOrdersData, 'Sales Code','FOURTH-ORDER-COUPON-CODE',4);
  }

  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron
}

/*addCronJob('afterFourthOrder', "Email After Fourth Order", '* * * * *');*/
// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
pluginAction_addHandlerAndLink(t('Email After Fourth Order'), 'afterFourthOrder', 'admins');
function afterFourthOrder($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    // This lines are only needed if your cron script is going to be called directly and you need to enforce security, if cron is added as a CMS "Background Task" then you can specify access rights in: pluginAction_addHandlerAndLink
    // $CMS_USER = getCurrentUserFromCMS();                                                                       // security check for web access - don't show cron filepaths unless logged in
    // if (!@$CMS_USER['isAdmin']) { die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive

  $orderQuery = "SELECT uo.membersNum,um.username,um.facebook_email,um.last_send_email,COUNT(uo.num) as orderCount FROM urbanhal_orders uo INNER JOIN urbanhal_members um ON um.num = uo.membersNum WHERE um.last_send_email = 4 GROUP BY uo.membersNum HAVING orderCount = 4";

  $orderData = mysql_select_query($orderQuery);
  $recentOrdersData = getRecentMenuItems();

  if(count($orderData) > 0){
    sendEmailToUsers($orderData,$recentOrdersData, 'Sales Code','FIFTH-ORDER-COUPON-CODE',5);
  }

  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron
}

function sendEmailToUsers($orderData,$recentOrdersData,$couponCode,$template,$emailStatus){
    $update = [];

    foreach ($orderData as $key => $value) {
      array_push($update,$value['membersNum']);
      $products = menuData($recentOrdersData);

      $placeholders = [
        'coupon_code'=> $couponCode,
        'facebook_email'=>$value['facebook_email'],
        "username"=>$value['username'],
        'suggested_products'=>$products,
      ];

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

      $mailErrors = sendMessage($emailHeaders);

      if($mailErrors) {
        echo "Mail errror: " . $mailErrors . "\n";
      }
    }

    if(count($update)){
      $updatestr = implode(',', $update);
      $sql = "UPDATE `urbanhal_members` SET last_send_email = ".$emailStatus." WHERE num IN (".$updatestr.")";
      mysql_do($sql);
    }
}

// addCronJob('sendListingEmail', "Send Marketing email to Listings", '* * * * *');
// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
pluginAction_addHandlerAndLink(t('Send Marketing email to Listings'), 'sendListingEmail', 'admins');
function sendListingEmail($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive
 
  $limit       = 0;
  $group       = 1;
  $query = "SELECT urbanhal_listings.num,email,send_marketing_email FROM `urbanhal_listings` LEFT JOIN `urbanhal_listings_details` ON urbanhal_listings_details.listingsnum = urbanhal_listings.num WHERE email IS NOT NULL AND email != '' AND (send_marketing_email = 0 || send_marketing_email IS NULL)  LIMIT $limit,$group";
  $listingData = mysql_get_query($query);

  if(isset($listingData)){
    $placeholders = [];
    $placeholders['email'] = $listingData['email'];

    $emailHeaders = emailTemplate_loadFromDB(array(
      'template_id'  => 'USER-MARKETING-EMAIL',
      'placeholders' => $placeholders,
    ));
    
    $mailErrors = sendMessage($emailHeaders);

    if($mailErrors) {
      echo "Mail errror: " . $mailErrors . "\n";
    }

    if(!isset($listingData['send_marketing_email'])){
      $insertData = mysql_insert("urbanhal_listings_details", array("listingsnum" => $listingData['num'],'isyelplisting'=>0,'send_marketing_email'=>1), true);
    }else{
      mysql_update('listings_details', null, "`listingsnum` = ".$listingData['num'], array("send_marketing_email" => 1));      
    }

    createCrmRecord($listingData['num'],'Email','Email sent');
  }

  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron
}

addCronJob('updateDeliveryOrderToDelivered', "Update Delivery Order To Delivered", '* * * * *');
// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
pluginAction_addHandlerAndLink(t('Update Delivery Order To Delivered'), 'updateDeliveryOrderToDelivered', 'admins');
function updateDeliveryOrderToDelivered($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
    set_time_limit(0);  // ignore PHP's max_execution_time directive

    $localTime = date('Y-m-d H:i:s');
    $order_status = 'delivered';
    $ordersData = mysql_select_query("SELECT `uo`.num, `uo`.order_status, `uo`.order_status_text, `uod`.ready_time, `uod`.order_ready_time, `uod`.ordersNum,`uo`.order_delivery_type,`uo`.shipping_phone_number FROM urbanhal_order_detail uod INNER JOIN urbanhal_orders  uo ON `uo`.num = `uod`.ordersNum WHERE `uo`.order_status='otw' AND `uo`.order_delivery_type = 'delivery' AND ('".$localTime."' > DATE_ADD(`uod`.`otw_time`,INTERVAL 55 MINUTE)) ORDER BY `uo`.num DESC");

    $orderStatusText = mysql_get('share_texts', 1, null,'order_delivered');
    
    if(count($ordersData) > 0){
      foreach ($ordersData as $key => $value) {
        updateOrderStatus($value,$orderStatusText['order_delivered'],$localTime,$order_status,'delivered_time');
      }
      echo "Order status changed to delivered";
    }else{
      echo "No data Found";
    }

  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron
}




addCronJob('updateDeliveryOrderToOtw', "Update Delivery Order To Otw", '* * * * *');
// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
pluginAction_addHandlerAndLink(t('Update Delivery Order To Otw'), 'updateDeliveryOrderToOtw', 'admins');
function updateDeliveryOrderToOtw($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
    set_time_limit(0);  // ignore PHP's max_execution_time directive

    $localTime = date('Y-m-d H:i:s');
    $order_status = 'otw';
    $ordersData = mysql_select_query("SELECT `uo`.num, `uo`.order_status, `uo`.order_status_text, `uo`.membersNum, `uo`.listingsNum, `uo`.order_delivery_type, `uod`.ready_time, `uod`.order_ready_time, `uod`.ordersNum FROM urbanhal_order_detail uod INNER JOIN urbanhal_orders  uo ON `uo`.num = `uod`.ordersNum WHERE `uo`.order_status = 'ready' AND `uo`.order_delivery_type = 'delivery' AND ('".$localTime."' > DATE_ADD(`uod`.ready_time,INTERVAL 5 MINUTE)) ORDER BY `uo`.num DESC");

    $orderStatusText = mysql_get('share_texts', 1, null,'order_otw');
    
    if(count($ordersData) > 0){
      foreach ($ordersData as $key => $value) {
        updateOrderStatus($value,$orderStatusText['order_otw'],$localTime,$order_status,'otw_time');
      }
      echo "Order status changed to on-the-way";
    }else{
      echo "No data Found";
    }

  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron
}



//addCronJob('stripeConnectReminderEmail', "Stripe Connect Reminder Email", '* * * * *');
// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
pluginAction_addHandlerAndLink(t('Stripe Connect Reminder Email'), 'stripeConnectReminderEmail', 'admins');
function stripeConnectReminderEmail($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
    set_time_limit(0);  // ignore PHP's max_execution_time directive

    $limit       = 0;
    $group       = 5;
    $listingData = mysql_select_query("SELECT `ul`.name, `ul`.email, `usa`.stripe_account_id, `ul`.num, `uld`.stripe_reminder_email FROM urbanhal_listings ul LEFT JOIN urbanhal_listings_details uld ON `uld`.listingsnum = `ul`.num LEFT JOIN urbanhal_stripe_accounts usa ON `usa`.listingsNum = `ul`.num WHERE (`usa`.stripe_account_id IS NULL OR `usa`.stripe_account_id = '') AND `ul`.enable_order = 1 AND `ul`.email IS NOT NULL AND `ul`.email != '' AND (`uld`.stripe_reminder_email = 0 || `uld`.stripe_reminder_email IS NULL) ORDER BY `ul`.num DESC LIMIT $limit,$group");
//print_r($listingData);exit();
    if(count($listingData) > 0){
      foreach ($listingData as $listing) {
        $tempData = [
          'listingName'=>$listing['name'],
          'email'=>$listing['email']
        ];
        $emailHeaders = emailTemplate_loadFromDB(array(
          'template_id' => 'STRIPE-CONNECT-REMINDER-EMAIL',
          'placeholders' => $tempData,
        ));

        $mailErrors = sendMessage($emailHeaders);

        if ($mailErrors) { echo "Mail Error: $mailErrors\r\n"; }
        else{ 
          echo "Mail Sent\r\n"; 
          
          if(!isset($listing['stripe_reminder_email'])){
            $insertData = mysql_insert("urbanhal_listings_details", array("listingsnum" => $listing['num'],'isyelplisting'=>0,'stripe_reminder_email'=>1), true);
          }else{
            mysql_update('listings_details', null, "`listingsnum` = ".$listing['num'], array("stripe_reminder_email" => 1));      
          }
        }
        
      }
      
    }else{
      echo "No Listing Found";
    }
  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron
}



//addCronJob('duplicateYelpReviewsDelete', "Duplicate Yelp Reviews Delete", '* * * * *');
// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
pluginAction_addHandlerAndLink(t('Duplicate Yelp Reviews Delete'), 'duplicateYelpReviewsDelete', 'admins');
function duplicateYelpReviewsDelete($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
    set_time_limit(0);  // ignore PHP's max_execution_time directive

    $limit       = 0;
    $group       = 5;
    
    $array = ['-16aafzzsPA0faUld8pzuw'];

    foreach($array as $key=>$value){
      $query = "SELECT num FROM urbanhal_reviews WHERE yelp_reviewId = '".$value."'";
      $result = mysql_select_query ($query);
      if(count($result) > 0){
        $ids = array_column($result, 'num');

        $deleteIdsArray = array_slice($ids,1,count($ids));
        $deleteIdsStr = implode(',', $deleteIdsArray);
        $deleteIn =  "DELETE FROM urbanhal_reviews WHERE num IN (".$deleteIdsStr.")";
        mysql_do($deleteIn);

      }


    }
  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron
}

/*addCronJob('reviewsCountUpdate', "Reviews Count Update", '* * * * *');*/
// Plugin Menu - Add link to allow users to "Run Manually", this can be useful for testing
pluginAction_addHandlerAndLink(t('Reviews Count Update'), 'reviewsCountUpdate', 'admins');
function reviewsCountUpdate($includeComments = true){

  if (!inCLI()) {  // send headers (for running through web with "Run Manually" link above)
  if (!headers_sent()) { 
    header("Content-type: text/plain");
      header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
      ob_disable();              // Turn off browser buffering
    }
    ignore_user_abort( true ); // continue running even if user clicks stop on their browser
    session_write_close();     // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress
  }
  set_time_limit(0);  // ignore PHP's max_execution_time directive

    $limit       = $_REQUEST['limit'];
    $group       = $_REQUEST['group'];
  
    $listingReviewData = mysql_select_query("SELECT count(num) as count,listingsNum FROM `urbanhal_reviews` Group by listingsNum LIMIT $limit,$group");
    
    if(count($listingReviewData) > 0){
      $temp = [];
      foreach ($listingReviewData as $key => $value) {
        $array = array("reviews"=>$value['count']);
        mysql_update('listings',$value['listingsNum'],null,$array);
        array_push($temp,$value['listingsNum']);  
      }
      echo  "Listing reviews updatetd ". implode(',', $temp);
    }


  // return summary message
  $summary = "Successful";
  if (@$_REQUEST['_pluginAction'] == __FUNCTION__) { exit; }  // exit if being run manually from web
  return $summary;  // otherwise, return summary if being run by cron
}