<?php


/**
 * Implements HOOK_form_alter().
 */
function diy_suche_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'views_exposed_form' && $form['#id'] == 'views-exposed-form-heimwerker-suchen-page') {
    $form['#validate'][] = 'diy_suche_search_form_custom_validation';

    // if the search was submitted before add a hidden field, to prevent JS from removing latlon code
    // eg: user searches for Tulln (with geocoding) -> latlon field is filled
    // user changes keywords for fulltext search
    // latlon should stay in hiddenfield geofield field

    // if this field is set, latlon will not be deleted
    if(!isset($_GET['author_field_geofield_latlon'])) {
      $form['diy_latlon_delete'] = array(
        '#type' => 'hidden',
        '#value' => 1
      );
    }
  }

  if($form_id == 'views_exposed_form' && $form['#id'] == 'views-exposed-form-inserate-suche-map-page') {
    $form['#validate'][] = 'diy_suche_search_form_inserate_custom_validation';

    // if the search was submitted before add a hidden field, to prevent JS from removing latlon code
    // eg: user searches for Tulln (with geocoding) -> latlon field is filled
    // user changes keywords for fulltext search
    // latlon should stay in hiddenfield geofield field

    // if this field is set, latlon will not be deleted
    if(!isset($_GET['field_geofield_latlon_1'])) {
      $form['diy_latlon_delete'] = array(
        '#type' => 'hidden',
        '#value' => 1
      );
    }
  }

}

/**
 * Submit function to add address search value to fulltext field
 */
function diy_suche_search_form_custom_validation($form, &$form_state) {
  // no geocoding -> use address input for fulltext search ("Maler Tulln")
  if(empty($form_state['input']['author_field_geofield_latlon']) && !empty($form_state['input']['address'])) {
    form_set_value($form['search_api_views_fulltext'], $form_state['input']['search_api_views_fulltext'] . ' ' . $form_state['input']['address'], $form_state);
  }
}

/**
 * Submit function to add address search value to fulltext field
 */
function diy_suche_search_form_inserate_custom_validation($form, &$form_state) {
  // no geocoding -> use address input for fulltext search ("Maler Tulln")
  if(empty($form_state['input']['field_geofield_latlon_1']) && !empty($form_state['input']['address'])) {
    form_set_value($form['search_api_views_fulltext'], $form_state['input']['search_api_views_fulltext'] . ' ' . $form_state['input']['address'], $form_state);
  }
}

function diy_suche_views_post_execute(&$view) {

	if ($view->name=='inserate_suche_map') {
	
		if(isset($view->exposed_raw_input['sort_by']) && $view->exposed_raw_input['sort_by']=='php') {
			// Sort by anzahl anfragen
		  	$new=array();
		  	$tmp=array();
		  	$ori=$view->result;
			foreach($view->result as $key => $value) {
	    		$nid=$value->entity;
				$anzahl=views_count_anfragen( $nid );
				$tmp[$anzahl][]=$ori[$key];
			}
			ksort($tmp);
			
			foreach($tmp as $key => $array) {
				foreach($array as $key2 => $record) {
					$new[]=$record;
				}
			} 
			$view->result=$new;
		}
  }


  if ($view->name=='heimwerker_suchen') {
		
  		$new=array();
  		$tmp=array();
  		
  		if($view->exposed_raw_input['sort_by']=='changed') {
	  		$ori=$view->result;

        $latlon = array();
        if(isset($view->exposed_input['author_field_geofield_latlon'])) {
          $latlon=explode(',', $view->exposed_input['author_field_geofield_latlon']);
        }

        $geocoding = false;

        if(!empty($latlon) & count($latlon) > 1) {
          $startlat=$latlon[0];
          $startlon=$latlon[1];

          $geocoding = true;
        }

	  		
	  		
	  		foreach($view->result as $key => $value) {
				
          $node=node_load($value->entity);	// Branche node

          if($node) {
            $profile2=profile2_load_by_user(user_load($node->uid), $type_name = 'anbieterprofil');
          }

          // distance
          if($geocoding && isset($profile2)) {
            $thisuser=user_load($node->uid);
            $lat=$thisuser->field_geofield[LANGUAGE_NONE][0]['lat'];
            $lon=$thisuser->field_geofield[LANGUAGE_NONE][0]['lon'];
            $distance=distance($startlat, $startlon, $lat, $lon, $unit='K');
            $max_entfernung=$profile2->field_max_entfernung[LANGUAGE_NONE][0]['value'];

            /*
             * substract max anbieterdistance aus profile2
             */
            if (($max_entfernung-$distance) < -10) $distancefactor = 0;
            if (($max_entfernung-$distance) < -5 && ($max_entfernung-$distance) >= -10) $distancefactor=0.4;
            if (($max_entfernung-$distance) < 0 && ($max_entfernung-$distance) >= -5) $distancefactor=0.8;
            if (($max_entfernung-$distance) >= 0) $distancefactor=1.0;
            if ( $distance <= 5) $distancefactor=1.2;
          }

          if(isset($profile2) && is_object($profile2)) {
            $voting_array = fivestar_get_votes($entity_type='profile2', $profile2->pid, 'ingesamt');
            $empfehlungen = count(flag_get_entity_flags('profile2', $profile2->pid, 'recommended'));
          }


          $gesamtfactor = 0;
          if(isset($voting_array['average']['value'])) {
            $gesamtfactor = $voting_array['average']['value']/100;
          }

          $abofactor=0;
          if($node) {
            $abo = _inserate_abo_id($node->uid);

            switch ($abo) {
              case 20:
                $abofactor=0.3;
                break;
              case  999999999:
                $abofactor=0.5;
                break;
              default:
                $abofactor=0;
            }
          }

          $empfehlungsfactor=0;
          if(isset($empfehlungen)) {
            if (!$empfehlungen) 						$empfehlungsfactor=0;
            if (in_array($empfehlungen, array(1,2) ))	$empfehlungsfactor=0.3;
            if (in_array($empfehlungen, array(3,4) ))	$empfehlungsfactor=0.4;
            if ($empfehlungen>4)						$empfehlungsfactor=0.5;
          }


          if($geocoding) {
            $overall = ($gesamtfactor + $empfehlungsfactor + $abofactor) * $distancefactor;
          } else {
            $overall = ($gesamtfactor + $empfehlungsfactor + $abofactor);
          }

          $tmp[$overall*100][]=$ori[$key];
			  }

        krsort($tmp);	// keysort reverse
        foreach($tmp as $key => $array) {
          foreach($array as $key2 => $record) {
              $new[]=$record;
          }
        }
			
        $view->result=$new;
		  		
  		}
  		
  		// Distanz
  		if($view->exposed_raw_input['sort_by']=='php') {
	  		$ori=$view->result;
  			
  			$latlon=explode(',', $view->exposed_input['author_field_geofield_latlon']);
  			$startlat=$latlon[0];
  			$startlon=$latlon[1];
	  		foreach($view->result as $key => $value) {
	  		
				$node=node_load($value->entity);	// Branche node
				
				$profile2=profile2_load_by_user(user_load($node->uid), $type_name = 'anbieterprofil');
				$thisuser=user_load($node->uid);
				$lat=$thisuser->field_geofield[LANGUAGE_NONE][0]['lat'];
				$lon=$thisuser->field_geofield[LANGUAGE_NONE][0]['lon'];
				$distance=distance($startlat, $startlon, $lat, $lon, $unit='K');
#				$distance=round($distance, 2);
#				dpm($thisuser->name);
#				dpm($thisuser->field_inserat_addresse[LANGUAGE_NONE][0]['locality']);
#				dpm($distance.' km');

				$tmp[$distance*1000][]=$ori[$key];
	  		}
	  		ksort($tmp);
			foreach($tmp as $key => $array) {
				foreach($array as $key2 => $record) {
						$new[]=$record;
				}
			} 
			$view->result=$new;
  		}


		
  }


  // other views might go here

}


function views_count_anfragen( $nid ) {

	$view = views_get_view('number_of_bewerbungen');
	$view->set_arguments( array( $nid ) );
	$view->set_display('block_1');
	$view->pre_execute();
	$view->execute();
	$result= $view->result;
	$anzahl=$result[0]->node_title;

#	dpm('row1: '.$anzahl);
#	dpm($row1);
#	dpm(row2);
#	dpm($row2);

	return $anzahl;
}

/*::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
	/*::                                                                         :*/
	/*::  This routine calculates the distance between two points (given the     :*/
	/*::  latitude/longitude of those points). It is being used to calculate     :*/
	/*::  the distance between two locations using GeoDataSource(TM) Products    :*/
	/*::                                                                         :*/
	/*::  Definitions:                                                           :*/
	/*::    South latitudes are negative, east longitudes are positive           :*/
	/*::                                                                         :*/
	/*::  Passed to function:                                                    :*/
	/*::    lat1, lon1 = Latitude and Longitude of point 1 (in decimal degrees)  :*/
	/*::    lat2, lon2 = Latitude and Longitude of point 2 (in decimal degrees)  :*/
	/*::    unit = the unit you desire for results                               :*/
	/*::           where: 'M' is statute miles                                   :*/
	/*::                  'K' is kilometers (default)                            :*/
	/*::                  'N' is nautical miles                                  :*/
	/*::  Worldwide cities and other features databases with latitude longitude  :*/
	/*::  are available at http://www.geodatasource.com                          :*/
	/*::                                                                         :*/
	/*::  For enquiries, please contact sales@geodatasource.com                  :*/
	/*::                                                                         :*/
	/*::  Official Web site: http://www.geodatasource.com                        :*/
	/*::                                                                         :*/
	/*::         GeoDataSource.com (C) All Rights Reserved 2013                  :*/
	/*::                                                                         :*/
	/*::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
function distance($lat1, $lon1, $lat2, $lon2, $unit) {

/**
	echo distance(32.9697, -96.80322, 29.46786, -98.53506, "M") . " Miles<br>";
	echo distance(32.9697, -96.80322, 29.46786, -98.53506, "K") . " Kilometers<br>";
	echo distance(32.9697, -96.80322, 29.46786, -98.53506, "N") . " Nautical Miles<br>";

**/

	 
	  $theta = $lon1 - $lon2;
	  $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
	  $dist = acos($dist);
	  $dist = rad2deg($dist);
	  $miles = $dist * 60 * 1.1515;
	  $unit = strtoupper($unit);
	 
	  if ($unit == "K") {
	    return ($miles * 1.609344);
	  } else if ($unit == "N") {
	      return ($miles * 0.8684);
	    } else {
	        return $miles;
	  }
}
	 
	 

