<?php

  function api_logCommand($user = array(), $data = array()){
    if(@$_REQUEST['_log']){

      $command = "";      
      if(isset($_REQUEST['create']))          { $command = 'create'; }
      elseif(isset($_REQUEST['read']))        { $command = 'read';   }
      elseif(isset($_REQUEST['update']))      { $command = 'update'; }
      elseif(isset($_REQUEST['delete']))      { $command = 'delete'; }
      elseif(isset($_REQUEST['upload']))      { $command = 'upload'; }
      elseif(isset($_REQUEST['search']))      { $command = 'search'; }
      elseif(isset($_REQUEST['sms_promote'])) { $command = 'sms_promote'; }
      elseif(isset($_REQUEST['signup']))      { $command = 'signup'; }
      elseif(isset($_REQUEST['login']))       { $command = 'login';  }
      elseif(isset($_REQUEST['check_user_exists']))       { $command = 'check_user_exists';  }
      elseif(isset($_REQUEST['signup']))       { $command = 'signup';  }

      //Storing the upload data in the log is taking up  a lot of space. Stop upload data being saved.
      if(isset($_REQUEST['uploadData']))      { unset($_REQUEST['uploadData']); }

      $date                           = date('Y-m-d H:i:s');
      $insertData                     = array();
      $insertData['createdDate']      = $date;
      $insertData['createdByUserNum'] = $user['num'];
      $insertData['updatedDate']      = $date;
      $insertData['updatedByUserNum'] = $user['num'];
      $insertData['command_type']     = $command;
      $insertData['section']          = strtolower($_REQUEST['_section']);
      $insertData['recordNum']        = @intval($_REQUEST['num']);
      $insertData['membersNum']       = $user['num'];
      $insertData['date']             = $date;
      $insertData['insertData']       = (isset($_REQUEST['insertData']))? json_encode($_REQUEST['insertData']) : "" ;
      $insertData['requestData']      = json_encode($_REQUEST);
      mysql_insert('api_log', $insertData, true);

    }
  }

  function api_setUserAsCreator($user, $data){
    $schemaFields = getSchemaFields(@$_REQUEST['_section']);
    if( isset($schemaFields['createdByUserNum']) && isset($user['num']) )         { $data['createdByUserNum'] = $user['num']; }
    if( isset($schemaFields['updatedByUserNum']) && isset($user['num']) )         { $data['updatedByUserNum'] = $user['num']; }
    if( isset($schemaFields['createdDate'])      && !isset($data['createdDate'])) { $data['createdDate'] = date('Y-m-d H:i:s'); }
    if( isset($schemaFields['updatedDate'])      && !isset($data['updatedDate'])) { $data['updatedDate'] = date('Y-m-d H:i:s'); }
    if( isset($schemaFields['membersNum'])       && isset($user['num']) )         { $data['membersNum'] = $user['num']; }
    return $data;
  }

  function shutDownFunction() { 
    $error = error_get_last();
    if(@$error['message'] && ( $error['type'] === 1 || $error['type'] === 1024 )){ 
      echo json_encode(array('success' => "", 'errors' => $error['message']));
      exit;
    } 
  }

  //Used to validate a users access token.
  function api_verifyFacebookToken($accessToken, $userId){
    $appSecretProof = hash_hmac('sha256', $accessToken, $GLOBALS['FACEBOOKAPI_APP_SECRET']); 
    list($details, $statusCode) = getPage("https://graph.facebook.com/me?fields=" . implode(",",$GLOBALS['FACEBOOK_USER_FIELDS']) . "&access_token=" . urlencode($accessToken) . "&appsecret_proof=" . urlencode($appSecretProof), 20 );
    $userDetails = json_decode($details, true);

    if(!$statusCode) {
      sendMessage(emailTemplate_loadFromDB(array(
        'template_id'  => 'FACEBOOK-API-ISSUE',
        'placeholders' => ['a' => 'placeholder'], //we must send placeholders
      )));
      trigger_error("https://graph.facebook.com/me?access_token not responding. Got status code $statusCode: $details\n", E_USER_WARNING);
      exit;
    }

    if(isset($userDetails['error']) && $userDetails['error'] ){
      $validToken = false;
      $error      = $userDetails['error']['message'];
    }elseif($userDetails['id'] != $userId){
      $validToken = false;
      $error      = "User ID sent does not match that of the token.\n";
    }else{
      $validToken = true;
      $error      = "";
    }
    return array($validToken, $error);
  }

  function api_getUserFBDetails($accessToken){
    $appSecretProof = hash_hmac('sha256', $accessToken, $GLOBALS['FACEBOOKAPI_APP_SECRET']); 
    list($details, $statusCode) = getPage("https://graph.facebook.com/me?fields=" . implode(",",$GLOBALS['FACEBOOK_USER_FIELDS']) . "&access_token=" . urlencode($accessToken) . "&appsecret_proof=" . urlencode($appSecretProof), 20 );

    if(!$statusCode) {
      sendMessage(emailTemplate_loadFromDB(array(
        'template_id'  => 'FACEBOOK-API-ISSUE',
        'placeholders' => ['a' => 'placeholder'], //we must send placeholders
      )));
      trigger_error("https://graph.facebook.com/me?access_token not responding. Got status code $statusCode: $details\n", E_USER_WARNING);
      exit;
    }
    $userDetails   = json_decode($details, true);
    if($userDetails['error']) {
      trigger_error($userDetails['error']['message'], E_USER_WARNING);
      echo $userDetails['error']['message'];
      exit;
    }else{
      $userDetails['picture'] = @$userDetails['picture']['data']['url']; //Get the users photo
      return $userDetails;
    }
  }

  // check fields that require "unique" values
  function api_getUniqueFieldErrors($fieldLabel, $tableName, $fieldName, $fieldValue, $recordNum) {
    $error = '';
    // check if value already in use
    $where         = "`$fieldName` = '".mysql_escape($fieldValue)."'";
    if ($recordNum) { $where .= " AND num != '".mysql_escape($recordNum)."'"; } # ignore records existing value (which might be the same)
    $count = mysql_count($tableName, $where);
    if ($count > 0) {
      $error = sprintf(t("'%s' value must be unique. The selected value is already in use!"), $fieldLabel) . "\n";
    }
    return $error;
  }

  function api_encryptPasswordFields($values){
    if(accountsTable() == $_REQUEST['_section']){
      if(isset($values['password'])){
        $passwordText = @$values['password'];
        if (@$SETTINGS['advanced']['encryptPasswords']) { $passwordHash = getPasswordDigest($passwordText); }
        else                                            { $passwordHash = $passwordText; }
        $values['password'] = $passwordHash;
      }
    }
    return $values;
  }

  //Check if a user owns the record they want delete/update/upload to.
  function api_userOwnsRecord($user, $sectionRules, $action){
    if(!isset($user['num']))                                       { return "No user found"; }
    if(!isset($_REQUEST['num']))                                   { return "No record found"; }
    if(!in_array($action, $sectionRules['ownRecordsOnly:values'])) { return ''; }
    if(!mysql_count($_REQUEST['_section'], mysql_escapef("`num` = ? AND `createdByUserNum` = ?", $_REQUEST['num'], $user['num']))){
      return "You cannot update this record as you did not create it.\n";
    }
  }

  function api_loginRequired($sectionRules){
    $crudTypes = array( 'create', 'read', 'update','delete', 'upload' );
    foreach($crudTypes as $command){
      if( isset($_REQUEST[$command]) && isset($sectionRules['noLoginTo:values']) ){
        if(in_array($command, $sectionRules['noLoginTo:values'])){ return false; }
      }
    }
    return true;
  }


  function api_validateInsertData($values, $section){
    $errorsAndAlerts = "";
    error_log("Validating insert data for section: " . $section);
    error_log("Values to validate: " . print_r($values, true));

    //Basic error check values
    $schemaFields = getSchemaFields($section);
    error_log("Schema fields: " . print_r($schemaFields, true));
    
    if (!$schemaFields) {
        error_log("Error: Could not load schema fields for section '$section'");
        return "Error: Could not load schema fields for section '$section'";
    }

    foreach($values as $field => $value){
        error_log("Checking field: $field with value: " . print_r($value, true));
        
        if(!isset($schemaFields[$field])){ 
            $error = "Field '$field' not found in schema for section '$section'";
            error_log($error);
            $errorsAndAlerts .= $error . "\n"; 
        }
        else {
            $fieldSchema = $schemaFields[$field];
            error_log("Field schema: " . print_r($fieldSchema, true));
            
            // Check for required fields
            if (!empty($fieldSchema['isRequired']) && empty($value)) {
                $error = "Field '$field' is required but has no value";
                error_log($error);
                $errorsAndAlerts .= $error . "\n";
            }
            
            // Check for unique fields
            if (!empty($fieldSchema['isUnique']) && $value != '') {
                $uniqueError = api_getUniqueFieldErrors($field, $section, $field, $value, null);
                if ($uniqueError) {
                    error_log("Unique field error: " . $uniqueError);
                    $errorsAndAlerts .= $uniqueError;
                }
            }
        }
    }
    
    error_log("Validation result: " . $errorsAndAlerts);
    return $errorsAndAlerts;
  }

  function api_validFacebookUser(){

    $errorsAndAlerts = "";
    $user            = array();
    
    if(!isset($_REQUEST['_facebook_id']))           { $errorsAndAlerts .= "No Facebook ID sent\r\n"; }
    if(!isset($_REQUEST['_facebook_access_token'])) { $errorsAndAlerts .= "No Facebook access token Sent\r\n"; }

    foreach (array('_facebook_id','_facebook_access_token') as $field) { // v1.10 remove leading and trailing whitespace
      $_REQUEST[$field] = preg_replace("/^\s+|\s+$/s", '', @$_REQUEST[$field]);
    }



    $user    = mysql_get(accountsTable(),null, mysql_escapef("`facebook_id` = ? AND `facebook_access_token` = ? ", $_REQUEST['_facebook_id'], $_REQUEST['_facebook_access_token']));
    if(!$user){ $user = array(); } //False being returned, updated code so that it
    $schema  = getSchemaFields(accountsTable());


    //The user already exists in the table.
    if($user){
      //Check if the user logged in more than an hour ago. If the did, verify their account.
      $secondsSinceLastupdate = time() - strtotime($user['lastLoginDate']) ;
      if($secondsSinceLastupdate > $GLOBALS['CHECK_FACEBOOK_ACCOUNT'] ){
        list($validToken, $error) = api_verifyFacebookToken($_REQUEST['_facebook_access_token'], $_REQUEST['_facebook_id']);
        if($validToken){
          $fbUserDetails                    = api_getUserFBDetails($_REQUEST['_facebook_access_token']);
          if($fbUserDetails){
            $columnsToValues                  = array();
            $columnsToValues['lastLoginDate'] = date('Y-m-d H:i:s');
            $columnsToValues['is_new_user']   = 0;
            $columnsToValues                  = array_merge($columnsToValues, facebookUtil_userInsertArray($fbUserDetails,$schema, @$_REQUEST['_facebook_access_token']));
            $columnsToValues['username']      = $columnsToValues['facebook_first_name']." ".$columnsToValues['facebook_last_name'][0].".";
            mysql_update(accountsTable(), $user['num'], null, $columnsToValues);
          }else{
            $error = "User details not found from Facebook API!\r\n";
          }
        }
      }
    //User isn't in the database, so add them.
    }else{
      list($validToken, $error) = api_verifyFacebookToken($_REQUEST['_facebook_access_token'], $_REQUEST['_facebook_id']);
      
      if($validToken){

        $fbUserDetails = api_getUserFBDetails($_REQUEST['_facebook_access_token']);

        //FB user detials found
        if($fbUserDetails){        
          //If the user ID is already in the DB, update the access token.
          if ( mysql_count(accountsTable(), mysql_escapef("`facebook_id` = ? ", $_REQUEST['_facebook_id']))){
            $columnsToValues                          = array();
            $columnsToValues['facebook_id']           = $user['id'];
            $columnsToValues['facebook_access_token'] = $_REQUEST['_facebook_access_token'];
            $columnsToValues['is_new_user']           = 0;
            $columnsToValues                          = array_merge($columnsToValues, facebookUtil_userInsertArray($fbUserDetails,$schema, @$_REQUEST['_facebook_access_token']));
            $columnsToValues['username']              = $columnsToValues['facebook_first_name']." ".$columnsToValues['facebook_last_name'][0].".";
            mysql_update(accountsTable(), null, mysql_escapef("`facebook_id` = ? ", $_REQUEST['_facebook_id']), $columnsToValues);
            $user = mysql_get(accountsTable(),null, mysql_escapef("`facebook_id` = ? AND `facebook_access_token` = ? ", $_REQUEST['_facebook_id'], $_REQUEST['_facebook_access_token']));
          

          //If the user ID isn't in the DB, create an account.
          }else{

            $date                                 = date('Y-m-d H:i:s');
            $insertArray                          = array();
            $insertArray['createdDate']           = $date;
            $insertArray['createdByUserNum']      = "0";
            $insertArray['updatedDate']           = $date;
            $insertArray['updatedByUserNum']      = "0";
            $insertArray['facebook_email']        = $fbUserDetails['email'];
            $insertArray['password']              = getPasswordDigest(substr(md5(microtime()),rand(0,26),10));
            $insertArray['lastLoginDate']         = $date;
            $insertArray['expiresDate']           = "0000-00-00 00:00:00";
            $insertArray['neverExpires']          = "1";
            $insertArray['isAdmin']               = "0";
            $insertArray['disabled']              = "0";
            $insertArray['facebook_id']           = $_REQUEST['_facebook_id'];
            $insertArray['facebook_access_token'] = $_REQUEST['_facebook_access_token']; 
            $insertArray['is_new_user']           = 1;
            $insertArray['is_badge_publish']      = 1;
            $insertArray['is_checkin_publish']    = 1;
            $insertArray['is_review_publish']     = 1;
            $insertArray['is_rating_publish']     = 1;
            $insertArray['reviews']               = 0;
            $insertArray['check_ins']             = 0;
            $insertArray['photo_count']           = 0;
            $insertArray['ratings']               = 0;
            $insertArray['badge_count']           = 0;
            $insertArray['followers']             = 0;
            $insertArray['following']             = 1;
            $insertArray                          = array_merge($insertArray, facebookUtil_userInsertArray($fbUserDetails,$schema));
            $insertArray['username']              = $insertArray['facebook_first_name']." ".$insertArray['facebook_last_name'][0].".";

            $userNum  = mysql_insert(accountsTable(), $insertArray, true);
            $user     = mysql_get(accountsTable(), $userNum);
            //Update the record so that it registers as being created by the owner.
            mysql_update(accountsTable(), $userNum, null, array('createdByUserNum' => $userNum, 'updatedByUserNum' => $userNum));

            followAppCreator($userNum);

            //email user letting them know they've joined.
            if($insertArray['facebook_email']){

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

              $insertArray['unsubscribe_url'] = $unsubUrl;
              
              $template_id = 'USER-SIGNUP-APP';
              
              if(isset($_REQUEST['origin'])) {
                $template_id = 'USER-SIGNUP-SPLASH';
              }
              // Abhishek : change avatar in email template based on gender
              // $insertArray['user_avatar'] = "male-avatar-large.png";
              // if($insertArray['facebook_gender'] == 'female'){
              //   $insertArray['user_avatar'] = "female-avatar-large.png";
              // }
              $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 .="<div style='height: 100px; width: 31%; float: left; margin-left: 5px; margin-bottom: 5px;'>
                  <img style='border-radius: 8px; height: 100px; width: 100%;' src='".$record['photos'][0]['thumbUrlPath']."'/></div>";
              }
              $insertArray['foodie_moments'] = $foodie_moments;
              $emailHeaders = emailTemplate_loadFromDB(array(
                'template_id'  => $template_id,
                'placeholders' => $insertArray,
              ));
              $mailErrors = sendMessage($emailHeaders);
              if ($mailErrors) { $errorsAndAlerts = "Mail Error: $mailErrors\n"; }
            }

            //Update the subscribers table.
            //Abhishek no longer adding new user to subscribe list
            // if(!mysql_count('_nlb_subscribers', "`email` = '".mysql_escape_string($insertArray['facebook_email'])."'")){
            //   $insertData                = array();
            //   $insertData['createdDate'] = $date; 
            //   $insertData['email']       = $insertArray['facebook_email'];
            //   $insertData['confirmed']   = '1';
            //   $insertData['authkey']     = substr( md5(rand()), 0, 7);
            //   mysql_insert('_nlb_subscribers', $insertData, true);
            // }
          }
        }else{
          $error = "No user details returned by the API!\r\n";
        }
      }
    }

    if(@$error){
      $errorsAndAlerts .= $error;
    }
    return array($user, $errorsAndAlerts);

  }

  function api_validUser(){
    foreach (array('_username','_password') as $field) { // v1.10 remove leading and trailing whitespace
      $_REQUEST[$field] = preg_replace("/^\s+|\s+$/s", '', @$_REQUEST[$field]);
    }

    $accountsTable    = $GLOBALS['TABLE_PREFIX'] . accountsTable();
    $passwordValue    = $GLOBALS['SETTINGS']['advanced']['encryptPasswords'] ? getPasswordDigest($_REQUEST['_password']) : $_REQUEST['_password'];
    $query            = mysql_escapef("SELECT username FROM `$accountsTable` WHERE password = ? AND ? IN (`username`,`email`)", $passwordValue, $_REQUEST['_username']);
    $usernames        = array_pluck(mysql_select_query($query), 'username');
    return ($usernames);
  }

  function facebookUtil_userInsertArray($user,$schema, $accessToken = ''){
    $columnsToValues = array();
    //Update any other fields which we have set locally.
    foreach($GLOBALS['FACEBOOK_USER_FIELDS'] as $field){
      if(isset($schema['facebook_'. $field])){
        //Convert the value for saving in the DB
        if(is_bool($user[$field])){
          $value = ($user[$field])? '1' : '0';
        }elseif(is_string($user[$field])){
          $value = $user[$field];
        }elseif(is_array($user[$field])){
          $value = implode(",", $user[$field]);
        }else{
          $value = @$user[$field];
        }
        //Add the value to the DB
        $columnsToValues['facebook_'. $field] = $value;
      }
    }   
    $columnsToValues['facebook_user_friends'] = json_encode(facebookUtil_getFacebookFriends($user['id'], $accessToken), true);
    return $columnsToValues;
  }

  function api_formatData($data){
    foreach($data as $rowKey => $row){
      foreach($row as $fieldKey => $value){
        if(contains(".", $fieldKey)){
          list($keyOne, $keyTwo) = explode(".", $fieldKey);
          $data[$rowKey][$keyOne][$keyTwo] = $value;
          unset($data[$rowKey][$fieldKey]);
        }
        if(contains(":", $fieldKey)){
          $newKey = str_replace(":", "_", $fieldKey);
          $data[$rowKey][$newKey] = $value;
          unset($data[$rowKey][$fieldKey]);
        }
      }
    }
    return $data;

  }

  function createOrUpdateUser($userData, $requestHeaders){

    $isNewUser = true;

    if(isset($requestHeaders['Facebook-Id'])){

      if($user = mysql_get(accountsTable(), null, mysql_escapef("`facebook_id` = ? ", $requestHeaders['Facebook-Id']))){
        $userData['phone_number']                   = $user['phone_number'];
        $userData['password']                       = $user['password'];
        $userData['facebook_picture']               = (empty( $user['facebook_picture']) || strpos($user['facebook_picture'], "default-profile-none") !== FALSE ) ? $userData['facebook_picture'] : $user['facebook_picture'];
        $userData['facebook_email']                 = $user['facebook_email'] ? $user['facebook_email'] : $userData['facebook_email'];
        $userData['username']                       = $userData['username'] ? $userData['username'] : $user['username'];
        $userData['facebook_gender']                = $userData['facebook_gender'] ? $userData['facebook_gender'] : $user['facebook_gender'];

        $columnsToValues                            = array();
        $columnsToValues['lastLoginDate']           = date('Y-m-d H:i:s');
        $columnsToValues['is_new_user']             = 0;
        $columnsToValues['facebook_id']             = $requestHeaders['Facebook-Id'];
        $columnsToValues['facebook_access_token']   = $requestHeaders['Facebook-Access-Token'];
        $columnsToValues                            = array_merge($columnsToValues, $userData);
        
        mysql_update(accountsTable(), null, mysql_escapef("`facebook_id` = ? ", $requestHeaders['Facebook-Id']), $columnsToValues);

        $user = mysql_get(accountsTable(),null, mysql_escapef("`facebook_id` = ? AND `facebook_access_token` = ? ", $requestHeaders['Facebook-Id'], $requestHeaders['Facebook-Access-Token']));

        $isNewUser = false;

      }elseif(!empty($userData['facebook_email']) && $user = mysql_get(accountsTable(), null, mysql_escapef("`facebook_email` = ? ", $userData['facebook_email']))){
        
        $userData['phone_number']                   = $user['phone_number'];
        $userData['password']                       = $user['password'];
        $userData['facebook_picture']               = (empty( $user['facebook_picture']) || strpos($user['facebook_picture'], "default-profile-none") !== FALSE ) ? $userData['facebook_picture'] : $user['facebook_picture'];
        $userData['username']                       = $userData['username'] ? $userData['username'] : $user['username'];
        $userData['facebook_email']                 = $user['facebook_email'] ? $user['facebook_email'] : $userData['facebook_email'];
        $userData['facebook_gender']                = $userData['facebook_gender'] ? $userData['facebook_gender'] : $user['facebook_gender'];

        $columnsToValues                            = array();
        $columnsToValues['lastLoginDate']           = date('Y-m-d H:i:s');
        $columnsToValues['is_new_user']             = 0;
        $columnsToValues['facebook_id']             = $requestHeaders['Facebook-Id'];
        $columnsToValues['facebook_access_token']   = $requestHeaders['Facebook-Access-Token'];
        $columnsToValues                            = array_merge($columnsToValues, $userData);
    
        mysql_update(accountsTable(), null, mysql_escapef("`facebook_email` = ? ", $userData['facebook_email']), $columnsToValues);

        $user = mysql_get(accountsTable(),null, mysql_escapef("`facebook_id` = ? AND `facebook_access_token` = ? ", $requestHeaders['Facebook-Id'], $requestHeaders['Facebook-Access-Token']));

        $isNewUser = false;
      }else{
        $userData['facebook_id']             = $requestHeaders['Facebook-Id'];
        $userData['facebook_access_token']   = $requestHeaders['Facebook-Access-Token'];
      }

    }
    elseif($user = mysql_get("members", null, "`facebook_email` = '" . mysqli_real_escape_string(mysqli(), $userData['facebook_email']) . "'")){
      $isNewUser = false;
    }

    
    if($isNewUser){

      $date                              = date('Y-m-d H:i:s');
      $userData['password']              = !empty($userData['password']) ? password_hash($userData['password'], PASSWORD_BCRYPT) : '';
      $userData['createdDate']           = $date;
      $userData['createdByUserNum']      = "0";
      $userData['updatedDate']           = $date;
      $userData['updatedByUserNum']      = "0";
      $userData['lastLoginDate']         = $date;
      $userData['expiresDate']           = "0000-00-00 00:00:00";
      $userData['neverExpires']          = "1";
      $userData['isAdmin']               = "0";
      $userData['disabled']              = "0";
      $userData['is_new_user']           = 1;
      $userData['is_badge_publish']      = 1;
      $userData['is_checkin_publish']    = 1;
      $userData['is_review_publish']     = 1;
      $userData['is_rating_publish']     = 1;
      $userData['reviews']               = 0;
      $userData['check_ins']             = 0;
      $userData['photo_count']           = 0;
      $userData['ratings']               = 0;
      $userData['badge_count']           = 0;
      $userData['followers']             = 0;
      $userData['following']             = 1;
      $userData['rank']                  = 0;
      $userData['points']                = 0;

      if(!$userData['facebook_picture']){
        $userData['facebook_picture'] = $GLOBALS['SETTINGS']['defaultUserPic'];
      }

      $userNum  = mysql_insert(accountsTable(), $userData, true);
      $user     = mysql_get(accountsTable(), $userNum);
      //Update the record so that it registers as being created by the owner.
      mysql_update(accountsTable(), $userNum, null, array('createdByUserNum' => $userNum, 'updatedByUserNum' => $userNum));

      followAppCreator($userNum);

      //email user letting them know they've joined.
      if($userData['facebook_email']){
        
        $template_id = 'USER-SIGNUP-APP';
        
        if(isset($_REQUEST['origin'])) {
          $template_id = 'USER-SIGNUP-SPLASH';
        }
        
        $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 .="<div style='height: 100px; width: 31%; float: left; margin-left: 5px; margin-bottom: 5px;'>
            <img style='border-radius: 8px; height: 100px; width: 100%;' src='".$record['photos'][0]['thumbUrlPath3']."'/></div>";
        }
        
        $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'];
        }
        

        // $tags = mysql_select("tags", "TRUE ORDER BY `count` DESC LIMIT 5", "`name`, `count`");
        // $tagHtml = [];
        // foreach($tags as $key => $s){
        //   $tagHtml['taghtml'] .= "<p style='font-weight: 500;font-size: 14px;'>{$s['name']}<span style='margin-left: 10px;'>{$s['count']}</span></p>";
        // }

        // echo"<pre>";print_r($tagHtml);echo"</pre>";
        $unsubUrl = $GLOBALS['SETTINGS']['websiteUrl'].'/unsubscribe.php?e='.$userData['facebook_email'];
        $placeholders = array_merge(["username" => $userData['username'], "facebook_email" => $userData['facebook_email'], "facebook_picture" => $userData['facebook_picture'], "facebook_first_name" => $userData['facebook_first_name'], "foodie_moments" => $foodie_moments, "unsubscribe_url" => $unsubUrl], $listingsCuisineCount);

        $emailHeaders = emailTemplate_loadFromDB(array(
          'template_id'  => $template_id,
          'placeholders' => $placeholders,
        ));
        // print_r($emailHeaders);
        $mailErrors = sendMessage($emailHeaders);
        if ($mailErrors) { $errorsAndAlerts = "Mail Error: $mailErrors\n"; }
      }

      //Update the subscribers table.
      // if(!mysql_count('_nlb_subscribers', "`email` = '".mysqli_real_escape_string(mysqli(), $userData['facebook_email'])."'")){
      //   $insertData                = array();
      //   $insertData['createdDate'] = $date; 
      //   $insertData['email']       = $userData['facebook_email'];
      //   $insertData['confirmed']   = '1';
      //   $insertData['authkey']     = substr( md5(rand()), 0, 7);
      //   mysql_insert('_nlb_subscribers', $insertData, true);
      // }


    }// new user if end
    
    // if(!$user['username']){ $user['username'] = ""; }
    // if(!$user['facebook_email']){ $user['facebook_email'] = ""; }
    unset($user['password'], $user['card_code'], $user['facebook_id'], $user['facebook_access_token']);
    return $user;

  }

  // Abhishek : have user `followed creator of app automatically 
  function followAppCreator($userNum){
    $followingUser = mysql_get(accountsTable(), null, "`facebook_email` = 'javed@illumemag.com'");
    if($followingUser){
      $values = array();
      $values['createdDate']           = date('Y-m-d H:i:s');
      $values['createdByUserNum']      = $userNum;
      $values['updatedDate']           = date('Y-m-d H:i:s');
      $values['updatedByUserNum']      = $userNum;
      $values['membersNum']            = $userNum;
      $values['followingNum']          = $followingUser['num'];
      mysql_insert('user_follows', $values, true);
    }
  }

  function makeSearchWhere($request, $where, $searchText, $query, $fields, $listingsSchema){

    if($query){
        $searchWords = explode(' ', $query);
        $lastWord    = end($searchWords);
        $where       .= " AND ( ";
        foreach($fields as $key => $field){
          if($key != 0){ $where .= " OR "; }
          $where .= " ( ";
          foreach($searchWords as $key => $word){
            if($key != 0){ $where .= " OR "; }
            $where .= $field . " LIKE '%" . mysqli_real_escape_string(mysqli(),$word) . "%'"; 
          }
          $where .= ") ";
        }
        $where .= ") ";
      }

      if($searchText){
        $where       .= " AND ( ";
        foreach($fields as $key => $field){
          if($key != 0){ $where .= " OR "; }
          $where .= " ( ";
          
            $where .= $field . " LIKE '%" . mysqli_real_escape_string(mysqli(),$searchText) . "%'"; 
         
          $where .= ") ";
        }
        $where .= " OR ( `num` IN (SELECT DISTINCT listingsNum FROM `urbanhal_menu` WHERE name LIKE '%" . mysqli_real_escape_string(mysqli(),$searchText) . "%') )";
        $where .= ") ";
      }

      // Abhishek: where condition to check listings which has pork menu
      if(isset($request['pork'])){
        $porkVals = explode(",", $request['pork']);
        if(count($porkVals) === 1 && intval($request['pork']) === 1){
          $where .= "AND num IN (SELECT DISTINCT listingsNum FROM `urbanhal_menu` WHERE name LIKE '%pork%') ";
        }
      }
    //$where = "TRUE ";
      
      foreach($listingsSchema as $field => $fieldData){
        if(isset($request[$field]) && in_array($fieldData['type'], array('none', 'list', 'checkbox', 'textbox', 'textfield', 'date') ) ){
          $values = explode(",", $request[$field]);
          $where  .= "AND ( ";
          foreach($values as $key => $value){
            if( $key > 0 ) { $where .= " OR "; }
            if($field === 'type')
              $where .= "listings.`".mysqli_real_escape_string(mysqli(),$field)."` LIKE '%".mysqli_real_escape_string(mysqli(),$value)."%'";  
            else
              $where .= "listings.`".mysqli_real_escape_string(mysqli(),$field)."` = '".mysqli_real_escape_string(mysqli(),$value)."'";  
          }
          $where .= " ) ";
        }elseif( isset($request[$field."_match"]) && in_array($fieldData['type'], array('none', 'list', 'checkbox', 'textbox', 'textfield', 'date')) ){
          $values = explode(",", $request[$field."_match"]);
          $where  .= "AND ( ";
          foreach($values as $key => $value){
            if($key > 0) { $where .= " OR "; }
            $where .= " listings.`".mysqli_real_escape_string(mysqli(),$field)."` = '".mysqli_real_escape_string(mysqli(),$value)."'"; 
          }  
          $where .= " ) ";
        }elseif( isset($request[$field."_keyword"])&& in_array($fieldData['type'], array('none', 'list', 'checkbox', 'textbox', 'textfield', 'date')) ){
          $values = explode(",", $request[$field."_keyword"]);
          $where  .= "AND ( ";
          foreach($values as $key => $value){
            if($key > 0) { $where .= " OR "; }
            $where .= " listings.`".mysqli_real_escape_string(mysqli(),$field)."` LIKE '%".mysqli_real_escape_string(mysqli(),$value)."%'";
          }
          $where .= " ) ";
        }elseif( isset($request[$field."_prefix"]) && in_array($fieldData['type'], array('none', 'list', 'checkbox', 'textbox', 'textfield', 'date')) ){
          $values = explode(",", $request[$field."_prefix"]);
          $where  .= "AND ( ";
          foreach($values as $key => $value){
            if($key > 0) { $where .= " OR "; }
            $where .= " listings.`".mysqli_real_escape_string(mysqli(),$field)."` LIKE '".mysqli_real_escape_string(mysqli(),$value)."%'";
          }
          $where .= " ) ";
        }elseif( isset($request[$field."_empty"]) && in_array($fieldData['type'], array('none', 'list', 'checkbox', 'textbox', 'textfield', 'date')) ){
          $where .= "AND ( listings.`".mysqli_real_escape_string(mysqli(),$field)."` = '' OR  listings.`".mysqli_real_escape_string(mysqli(),$field."_empty")."` IS NULL ) ";   
        }elseif( isset($request[$field."_min"])&& in_array($fieldData['type'], array('none', 'list', 'checkbox', 'textbox', 'textfield', 'date')) ){
          $where .= "AND listings.`".mysqli_real_escape_string(mysqli(),$field)."` >= '".mysqli_real_escape_string(mysqli(),$request[$field."_min"])."'";  
        }elseif( isset($request[$field."_max"]) && in_array($fieldData['type'], array('none', 'list', 'checkbox', 'textbox', 'textfield', 'date')) ){
          $where .= "AND listings.`".mysqli_real_escape_string(mysqli(),$field)."` <= '".mysqli_real_escape_string(mysqli(),$request[$field."_max"])."'";  
        }
      }

      return $where;
  }

  function getSearchQuery($selectOptions, $SETTINGS){

    $query = "SELECT SQL_CALC_FOUND_ROWS `listings`.* $selectOptions
      FROM `urbanhal_listings` as `listings`
      WHERE";

      // LEFT JOIN {$SETTINGS['mysql']['tablePrefix']}reviews as reviews
      // ON listings.num = reviews.listingsNum
      // LEFT JOIN {$SETTINGS['mysql']['tablePrefix']}menu as menu
      // ON listings.num = menu.listingsNum
      // LEFT JOIN {$SETTINGS['mysql']['tablePrefix']}members as members
      // ON members.num = listings.membersNum

      // $finalQuery = $query." ($where)
      // GROUP BY listings.num
      // ORDER BY $orderBy
      // LIMIT $limit, $limitQty";
      // // print_r($finalQuery);
      // $rows = mysql_select_query($finalQuery);

      return $query;
  }

  function getSearchResults($query, $where, $orderBy, $limit, $limitQty){

    $finalQuery = $query." ($where)
      GROUP BY listings.num
      ORDER BY $orderBy
      LIMIT $limit, $limitQty";
      // print_r($finalQuery);
      $rows = mysql_select_query($finalQuery);

      return $rows;

  }

  function getJwtToken($data, $clientKeyId, $userType = "user"){

    $client = mysql_get('client_keys', $clientKeyId, null, "`access_key`, `key_status`");

    /**
     * Supported hashing algorithms.
     *
     * @var array[]
     */
    $supportedAlgorithms = [
        'HS256' => ['hash_hmac', 'SHA256'],
        'HS384' => ['hash_hmac', 'SHA384'],
        'HS512' => ['hash_hmac', 'SHA512'],
        'RS256' => ['openssl', 'SHA256'],
        'RS384' => ['openssl', 'SHA384'],
        'RS512' => ['openssl', 'SHA512'],
    ];


    $header = [
            'typ' => 'JWT',
            'alg' => 'HS256',
        ];

    if ($usertype == "user") {
      $userData = [
          'id' => $data['num'],
          'username' => $data['username'],
          'email' => $data['facebook_email']
        ];
    }
    else {
      $userData = [
          'id' => $data['num'],
          'name' => $data['name'],
          'phone' => $data['phone_number']
        ];
    }
        
    $payload = [
      'data' => $userData,
      'expires' => time() + (60)
    ];

    $segments[] = url_safe_base64_encode(jsonEncode($header));
    $segments[] = url_safe_base64_encode(jsonEncode($payload));

    // Sign the JWT with the given key
    $dataToSign = implode('.', $segments);

    list($function, $algorithm) = $supportedAlgorithms['HS256'];

    $signature = hash_hmac($algorithm, $dataToSign, $client['access_key'], true);

    $encodeSign = url_safe_base64_encode($signature);

    $segments[] = $encodeSign;

    return implode(".", $segments);
  }

  /**
  * Encodes given data using URL-safe Base64 encoding.
  *
  * @param  string $input
  * @return string
  */
  function url_safe_base64_encode($input)
  {
      return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));
  }

  /**
  * Converts the given data to its JSON representation.
  *
  * @param  mixed $data
  * @return string
  * @throws JsonException
  */
  function jsonEncode($data)
  {
      return json_encode($data);
  }

  function verifyToken($requestHeaders, &$api_access_token, $clientKeyId = '', $isRefresh = false, $userType = "user"){

    $token = $requestHeaders['Authorization'];

    $member = new ArrayObject();
    $errors = '';
    $clientToken = mysql_get('member_tokens', null, "`user_type` = '$userType' AND `token` = '".mysqli_real_escape_string(mysqli(), $token)."'");

    if ($clientToken) {
      
      if ($userType == 'user') {
        $member = mysql_get("members", $clientToken['membersNum']);
      }
      else{
        $member = mysql_get("drivers", $clientToken['membersNum']);
      }
      
      $api_access_token = $clientToken['token'];
      
      if($isRefresh){
        $newToken = getJwtToken($member, $clientKeyId, $userType);
        mysql_update("member_tokens", $clientToken['num'], null, array("token" => $newToken, "expiry_date" => date("Y-m-d H:i:s", time() + (60 * 60 * 24))));
        $api_access_token = $newToken;
      }else{
        if(time() >= strtotime($clientToken['expiry_date'])){
          $errors .= "Token Expired";
        }
      
      }
    }else{
      
      $errors .= "Invalid Token";

    }

    if($errors || !verifyRequestTime($requestHeaders['TimeStamp'], $errors)){
          $jsonData = ['success' => "false", 'errors' => $errors, 'urban_data' => [], 'user' => new ArrayObject(), 'meta' => null ];
          echo json_encode($jsonData);
          exit;
      }

    return $member;

  }

  function verifyClientKey($requestHeaders){

    $errors = '';

    $client_key = '';

    if(isset($requestHeaders['Access-Key'])){
      $client = mysql_get('client_keys', null, "`access_key` = '".mysqli_real_escape_string(mysqli(), $requestHeaders['Access-Key'])."'", "`num`, `access_key`, `key_status`");

      $client_key = $client['num'];

      if(!$client['key_status']){
        $errors = "Invalid key!";
      }
      elseif($client['access_key'] !== $requestHeaders['Access-Key']){
        $errors = "Invalid key!";
      }
    }else{
      $errors = "Access key is not set in header.";
    }

    if($errors || !verifyRequestTime($requestHeaders['TimeStamp'], $errors)){
      $jsonData = ['success' => 'false', 'errors' => $errors, 'urban_data' => [], 'user' => new ArrayObject(), 'meta' => null ];
      echo json_encode($jsonData);
      exit;
    }

    return [$client_key, $errors];
  }

  function verifyRequestTime($requestTime, &$errors){
    $time1 = time() - (60 * 2);
    $time2 = time() + (60 * 2);
    if(strtotime($requestTime) < $time1 || strtotime($requestTime) > $time2){
      $errors .= "Unauthenticate";
      return false;
    }

    return true;
  }

  function insertOrUpdateMemberToken($clientKeyId, $membersNum, $token, $userType = "user"){
    if(mysql_count("member_tokens", "`user_type` = '$userType' AND `membersNum` = ".intval($membersNum))){
      mysql_update("member_tokens", null, "`membersNum` = $membersNum", array("token" => $token, "expiry_date" => date("Y-m-d H:i:s", time() + (60 * 60 * 24))));
    }else{
      $date = date('Y-m-d H:i:s');
      $insertArray = array();
      $insertArray['createdDate']           = $date;
      $insertArray['createdByUserNum']      = $membersNum;
      $insertArray['updatedDate']           = $date;
      $insertArray['updatedByUserNum']      = $membersNum;
      $insertArray['key_id']                = $clientKeyId;
      $insertArray['membersNum']            = $membersNum;
      $insertArray['expiry_date']           = date("Y-m-d H:i:s", time() + (60 * 60 * 24));
      $insertArray['token']                 = $token;
      $insertArray['user_type']             = $userType;
      mysql_insert('member_tokens', $insertArray, true);
    }
  }