<?php

$db_host = "localhost";
$db_user = "gt";
$db_pass = 'dyBKmffRvvxMHfV8';
$db_name = 'dev_slowtwitch';
$is_live = true;

if ( $is_live ) {

    $db_name = 'slowtwitch';
    $db_user = 'slowtwitch';
    $db_pass = 'k9volqlAcpq';
    $db_host = '192.168.1.10';

}

$db_tables = array(
  'coach' => 'gforum_Coaches',
  'retailer' => 'gforum_Retailers',
  'runshop' => 'gforum_Runshops',
  'race' => 'gforum_Triathlons',
  'fitter' => 'gforum_Fitters',
  'triclub' => 'gforum_Triclubs',
  'roadshow' => 'gforum_Roadshow'
);


if ( isset($_POST['action'] )) {

  if ( $_POST["action"] == 'test' ) {
    connectdb( 'runshop' );

    fetchJson( 'runshop' );

    echo 'testing';
  }

}

if (is_ajax()) {
  if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
    $action = $_POST["action"];
    switch($action) { //Switch case for value of action
      case "test": return_json(); break;
    }
  }
}

//Function to check if the request is an AJAX request
function is_ajax() {

  return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && 
  strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';

}

function return_json(){
  $return = $_POST;

  echo json_encode($return);
}

function connectdb( $slug = null ) {

  $data = array();

  global $db_host, $db_user, $db_pass, $db_name;
  global $db_tables;

  if ( $slug !== null && $db_tables[$slug] ) {

    $table = $db_tables[$slug];

    $mysqli = new mysqli( $db_host, $db_user, $db_pass, $db_name);
    if ( $mysqli->connect_errno ) {
        echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " 
        . $mysqli->connect_error;
    }

    // Select all the rows in the markers table
    $query = select_table( $slug );

    /* Prepared statement, stage 1: prepare */
    if ( ! ($stmt = $mysqli->prepare( $query ) ) ) {
        echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
        return;
    }

    /* Execute statement */
    if ( !$stmt->execute() ) {
        echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
        return;
    }

    /* Get results */
    if ( !( $result = db_get_result( $stmt ) ) ) {
        echo "Getting result set failed: (" . $stmt->errno . ") " . $stmt->error;
        return;
    }

    $id = $slug . '_id';
    $name = $slug . '_name';
    $lat = $slug . '_lat';
    $lng = $slug . '_lng';
    $info1 = $slug . '_address';
    $info2 = $slug . '_address_two';
    $info3= $slug . '_city';
    $info4 = $slug . '_state';
    $phone = $slug . '_phone';
    $email = $slug . '_email';
    $website = $slug . '_website';
    $details = '';

    if ( $slug == 'coach')
      $details = '/coaches/individual.php?coach_id=';

    if ( $slug == 'retailer')
      $details = '/retailers/individual.php?retailer_id=';

    if ( $slug == 'fitter')
      $details = '/fitters/individual.php?fitter_id=';

    if ( $slug == 'runshop')
      $details = '/runshops/individual.php?runshop_id=';

    if ( $slug == 'triclub')
      $details = '/triclubs/individual.php?triclub_id=';

    if ( $slug == 'roadshow' ) {
      $details = '/roadshow/individual.php?roadshow_id=';
    }

    if ( $slug == 'race' ) {
      $name = 'name';
      $lat = 'lat';
      $lng = 'lng';
      $info1 = 'date';
      $info2 = 'swim';
      $info3 = 'bike';
      $info4 = 'run';
      $id = 'uid';
      $phone = 'phone';
      $email = 'email';
      $details = '/individual.php?uid=';
    }



    // Iterate through the rows, printing XML nodes for each
    while ( $row = array_shift( $result )  ) {

      if ( $row[$lat] && $row[$lng] ) {
        $data[] = array(
          'category' => $slug,
          'name' => htmlentities ($row[$name]),
          'lat' => $row[$lat],
          'lng' => $row[$lng],
          'info1' => htmlentities ($row[$info1]),
          'info2' => htmlentities ($row[$info2]),
          'info3' => htmlentities ($row[$info3]),
          'info4' => htmlentities ($row[$info4]),
          'phone' => htmlentities ($row[$phone]),
          'email' => htmlentities ($row[$email]),
          'website' => htmlentities ($row[$website]),
          'details' => $details . $row[$id],
        );
      }
    }


    /* explicit close recommended */
    $stmt->close();
    $mysqli->close();

  } else {

    $data = 'no data';

  }

  $data = json_encode( $data );
  return $data;

}

function select_table( $slug = null ) {

  global $db_tables;
  $query = '';

  if ( $slug !== null ) {

    $table = $db_tables[$slug];

    if ( $table ) {

      if ( $slug == 'race' ) {
        $today = date('Y-m-d');
        $query  ='SELECT * FROM ' . $table  . ' WHERE date >= "' .$today . '"';
      } else {
        $query  ='SELECT * FROM ' . $table  . ' WHERE ' . $slug . '_lat <> 0 AND ' .$slug . '_lng <> 0';
      }

    }
  }
  return $query;
}


function db_get_result( $Statement ) {
    $RESULT = array();
    $Statement->store_result();
    for ( $i = 0; $i < $Statement->num_rows; $i++ ) {
        $Metadata = $Statement->result_metadata();
        $PARAMS = array();
        while ( $Field = $Metadata->fetch_field() ) {
            $PARAMS[] = &$RESULT[ $i ][ $Field->name ];
        }
        call_user_func_array( array( $Statement, 'bind_result' ), $PARAMS );
        $Statement->fetch();
    }
    return $RESULT;
}


?>
