<?php

function pnpoly($px, $py, $x, $y) {
  $npol = count($px);
  $c = false;
  for ($i = 0, $j = $npol - 1; $i < $npol; $j = $i++) {
    if (((($py[$i] <= $y) && ($y < $py[$j])) ||
         (($py[$j] <= $y) && ($y < $py[$i]))) &&
        ($x < ($px[$j] - $px[$i]) * ($y - $py[$i]) / ($py[$j] - $py[$i]) + $px[$i]))
      $c = !$c;
  }
  return $c;
}

// Check for coordinates being in zipcode
function isInZipcodeArea($pointLong, $pointLat, $zipcode) {
  global $db;  
  // $plzp_polygons  = $db->getOne("SELECT plzp_polygons FROM phoenix_special.plz_polygon WHERE plzp_code = '$zipcode'");  
  $plzp_polygons  = getOneStmt("SELECT plzp_polygons FROM phoenix_special.plz_polygon WHERE plzp_code = '$zipcode'", "plzp_polygons");
  $polygons = explode("|", $plzp_polygons);
  foreach($polygons as $polygon) {  
    $polygonPointsX = array();
    $polygonPointsY = array();
    $points = explode(",", $polygon);
    foreach($points as $point) {
      list($plzp_x_deg, $plzp_y_deg) = explode(" ", $point);
      array_push ($polygonPointsX, $plzp_x_deg);
      array_push ($polygonPointsY, $plzp_y_deg);
    }
    if (pnpoly($polygonPointsX, $polygonPointsY, $pointLong, $pointLat))
      return true;
  }
  return false;
}

function findZipcodeArea($pointLong, $pointLat) {
  global $db;

  // Init  
  $maxSearchRadius = 5;
  $maxSearches = 10;
  $geoEarthRadius = 6371.0;
  $tblZipcode = "phoenix_special.plz_geodb";
  $fldLat = "plzg_breite";
  $fldLong = "plzg_laenge";
  $fldZipcode = "plzg_code";

  $max_search_radius = 0;
  $plz_sql = "";
  do {
    $max_search_radius += $maxSearchRadius;
    $plz_sql_clause = "";
    if ($plz_sql != "") 
       $plz_sql_clause = " AND " . $fldZipcode . " NOT IN ($plz_sql)";
    $sqlQuery = "SELECT " . $fldZipcode . " AS plz FROM " . $tblZipcode . " WHERE " .
      "(ACOS((SIN(" . deg2rad($pointLat) . ")*SIN(RADIANS(" . $fldLat . "))) + " .      "(COS(" . deg2rad($pointLat) . ")*COS(RADIANS(" . $fldLat . "))*COS(RADIANS(" . $fldLong . ")-" .
      deg2rad($pointLong) . "))) * " . $geoEarthRadius . ") < " . $max_search_radius . $plz_sql_clause;

    $res = $db->query($sqlQuery);
    if (DB::isError($res)) die ("$PHP_SELF: " . $result->getMessage());
    $i = 0;

    while ($row = $res->fetch_assoc()):
      if (isInZipcodeArea($pointLong, $pointLat, $row["plz"])) {
        return $row["plz"];
      }
      if ($plz_sql != "")
        $plz_sql .= ",";
      $plz_sql .= "'" . $row["plz"] . "'";  
    endwhile;

    $res->free();
  } while($max_search_radius < $maxSearchRadius * $maxSearches);
  return "";
}
?>
