<?php

$httpApiUrl = "https://api.rescuegroups.org/http/json";

function generatePage($animalID) {
	$result = getDetail($animalID);

	if ($result[data][$animalID][animalStatus] == "Available") {

		$info = array(
			"name" => $result[data][$animalID][animalName],
			"gender" => $result[data][$animalID][animalSex],
			"breed" => $result[data][$animalID][animalBreed],
			"bdate" => $result[data][$animalID][animalBirthdate],
		);

		$result[data][$animalID][sections] = getCPRDesc($result[data][$animalID][animalDescriptionPlain], $info);
	} else {
		$result[data][$animalID][sections] = getSOSDesc($result[data][$animalID][animalDescriptionPlain], $result[data][$animalID][animalSex], $result[data][$animalID][animalBirthdate]);
	}

	return $result;
}

// ===========================================================================================================
// This function takes and animal ID and looks up the animal at rescuegroups.org
//
// ===========================================================================================================
function getSOSDetail($animalID) {

	$result = getDetail($animalID);


	// call Parse SOS Desc
	$result[data][$animalID][sections] = getSOSDesc($result[data][$animalID][animalDescriptionPlain], $result[data][$animalID][animalSex],
	    $result[data][$animalID][animalBirthdate]);

	return $result;
}

// ===========================================================================================================
// This function takes and animal ID and looks up the animal at rescuegroups.org
//
// ===========================================================================================================
function getCPRDetail($animalID) {

	$result = getDetail($animalID);


	// call Parse SOS Desc

	$info = array(
		"name" => $result[data][$animalID][animalName],
		"gender" => $result[data][$animalID][animalSex],
		"breed" => $result[data][$animalID][animalBreed],
		"bdate" => $result[data][$animalID][animalBirthdate],
	);

	$result[data][$animalID][sections] = getCPRDesc($result[data][$animalID][animalDescriptionPlain], $info);

	return $result;
}

// ===========================================================================================================
// This function takes and animal ID and looks up the animal at rescuegroups.org
//
// ===========================================================================================================
function getDetail($animalID) {

	$apiKey = "Ugg4l7nq";

	// fields used for the detail page
	$fields = array("animalID", "animalActivityLevel", "animalAdoptionFee", "animalAltered", "animalRescueID",
		"animalBirthdate", "animalBirthdateExact", "animalGeneralAge","animalBreed",
		"animalColor", "animalDescriptionPlain", "animalEarType",
		"animalEnergyLevel", "animalExerciseNeeds", "animalGeneralAge",
		"animalGeneralSizePotential", "animalGroomingNeeds", "animalIndoorOutdoor",
		"animalLocationDistance", "animalLocationCitystate", "animalName",
		"animalOKWithCats", "animalRescueID", "animalSex",
		"animalShedding", "animalStatus", "animalTailType",
		"animalPictures", "animalVideos", "animalVideoUrls");

	$filter = array(
		"fieldName" => "animalID",
		"operation" => "equal",
		"criteria" => $animalID,
	);

	$data = array(
		"apikey" => "Ugg4l7nq",
		"objectType" => "animals",
		"objectAction" => "publicSearch",
		"search" => array(
			"calcFoundRows" => "Yes",
			"resultStart" => 0,
			"resultLimit" => 200,
			"resultSort" => "animalName",
			"fields" => $fields,
			"filters" => array($filter),
		),
	);

	$result = postToApi($data);

	// show Error if there is a problem with the call to Rescue Groups
	if (!$result) {
		echo "login issue with the API.";
		exit;
	}

	// debugObject($result);
	return $result;
}

// =========================================================================================================
// Function that pulls in the list of animals that match SOS dogs (status = sponsorship)
// =========================================================================================================
function getSOSList() {

    $cache_file='sos_list.txt';
    $expire_time = time() - (5 * 60); // 5 minutes

    if( file_exists($cache_file) ) {
      if (filectime($cache_file) > $expire_time ) {
      	$result = unserialize(file_get_contents($cache_file));
    //   	debugObject($result);
      	return $result;
      } else {
      	unlink($cache_file);
      }
    }


	$filter = array(
		"fieldName" => "animalStatus",
		"operation" => "equal",
		"criteria" => "Sponsorship",
	);

	$result = getList($filter);

    file_put_contents($cache_file, serialize($result));
	return $result;
}

// =========================================================================================================
// Function that pulls in the list of animals that match CPR dogs (status = available)
// =========================================================================================================
function getCPRList($animalName) {

    $cache_file='cpr_list.txt';
    $expire_time = time() - (5 * 60); // 5 minutes

    if( file_exists($cache_file) ) {
      if (filectime($cache_file) > $expire_time ) {
      	$result = unserialize(file_get_contents($cache_file));
    //   	debugObject($result);
      	return $result;
      } else {
      	unlink($cache_file);
      }
    }

	$filter =
	array("fieldName" => "animalStatus",
		"operation" => "equal",
		"criteria" => array("Sponsorship", "Available"),
	);

	// debugObject($filter2);

	$result = getList($filter);
    file_put_contents($cache_file, serialize($result));

	return $result;
}

// =========================================================================================================
// Function that pulls in the list of animals based on filter
// =========================================================================================================
function getList($filter) {
	$apiKey = "Ugg4l7nq";

	// fields used for the summary
	$fields = array("animalID",
		"animalName",
		"animalSpecies",
		"animalStatus",
		"animalRescueID",
		"animalBreed",
		"animalPictures",
		"animalAdoptionFee");

	$data = array(
		"apikey" => $apiKey,
		"objectType" => "animals",
		"objectAction" => "publicSearch",
		"search" => array(
			"calcFoundRows" => "Yes",
			"resultStart" => 0,
			"resultLimit" => 200,
			"resultSort" => "animalName",
			"fields" => $fields,
			"filters" => array($filter),
		),
	);

	$result = postToApi($data);

	// show Error if there is a problem with the call to Rescue Groups
	if (!$result) {
		echo "login issue with the API.";
		exit;
	}

	return $result;
}

// ===========================================================================================================
// Function that formats description for SOS Summary
// ===========================================================================================================
function getSOSDesc($desc, $gender, $birthdate) {

	$section = 0;
	foreach (preg_split('~[\r\n]+~', $desc) as $line) {
		if (empty($line) or ctype_space($line)) {
			continue;
		}

		if (preg_match("/^Please note/i", $line)) {
			continue;
		}

		if (preg_match("/^All about me/i", $line)) {
			$section = 1;
			continue;
		}

		if (preg_match("/^Foster Home/i", $line)) {
			$section = 2;
			continue;
		}

		if (preg_match("/^Why am I with a rescue group\? /i", $line)) {
			$section = 3;
			$line = preg_replace('/Why am I with a rescue group\? /i', '', $line);
		}

		switch ($section) {
		case 1:
			$values = preg_split('/[:?]/', $line);

			if (preg_match("/^Age:/i", $line)) {
			    $age = date_diff(date_create($birthdate), date_create('now'))->y;
			    $values[0] = "Estimated Birthdate";
			    $values[1] = " " . $birthdate;
			}
			
            
			$result["about"] .= "<strong>" . $values[0] . ":</strong>" . $values[1] . "<br>\n";
			
			if (preg_match("/^Name:/i", $line)) {
				$result["about"] .= "<strong>Gender:</strong> " . $gender . "<br>\n";
			}
			break;
		case 3:
			$result["biography"] .= "<p>" . $line . "</p>\n";
			break;
		case 2:
			$result["sponsorship"] .= "<p>" . $line . "</p>\n";
			break;
		}

	}

	$result["more"] = "<p>If you would like more information on this dog or any of our SOS dogs and our farm sanctuary for senior and special needs pets, please email info@carolinapoodlerescue.org or call 864-489-3559 and leave a message. We would love to tell you more about our assisted living facility for senior and special needs pets.</p>\n";

	$result["more"] .= "<p>Please note - we do not ship dogs.  If you are interested in adopting, please take a look at the distance between the foster home location and your location and make sure you are willing to make that trip.</p>\n";

	return $result;
}

// ===========================================================================================================
// Function that formats description for SOS Summary
// ===========================================================================================================
function getCPRDesc($desc, $info) {

	foreach (preg_split('~[\r\n]+~', $desc) as $line) {

		# Blank lines to skip
		if (empty($line) or ctype_space($line)) {continue;}

		if (preg_match("/^Please note/i", $line)) {continue;}
		if (preg_match("/^My age/i", $line)) {continue;}

		if (preg_match('/^Date into Rescue/i', $line)) {
			$values = preg_split('/:\s+/', $line, 2);
			$info["date_into_rescue"] = $values[1];
			continue;
		}

		if (preg_match('/^Reason for being in rescue/i', $line)) {
			$values = preg_split('/:\s+/', $line, 2);
			$info["reason_in_rescue"] = $values[1];
			continue;
		}
		if (preg_match('/^Spayed/i', $line)) {
			$values = preg_split('/:\s+/', $line, 2);
			$info["spayed"] = $values[1];
			continue;
		}
		if (preg_match('/^Special needs/i', $line)) {
			$values = preg_split('/\?\s+/', $line, 2);
			$info["special_needs"] = $values[1];
			continue;
		}
		if (preg_match('/^What kind of home would be best for me/i', $line)) {
			$values = preg_split('/[:\?]\s+/', $line, 2);
			$info["home"] = $values[1];
			continue;
		}
		if (preg_match('/^What is my personality like/i', $line)) {
			$values = preg_split('/[:\?]\s+/', $line, 2);
			$info["personality"] = $values[1];
			continue;
		}
		if (preg_match('/^How do I act when I first meet new people/i', $line)) {
			$values = preg_split('/[:\?]\s+/', $line, 2);
			$info["new_people"] = $values[1];
			continue;
		}
		if (preg_match('/^Other tips and tidbits/i', $line)) {
			$values = preg_split('/[:\?]\s+/', $line, 2);
			$info["tidbits"] = $values[1];
			continue;
		}
		if (preg_match('/^House trained/i', $line)) {
			$values = preg_split('/[:\?]\s+/', $line, 2);
			$info["house_trained"] = $values[1];
			continue;
		}
		if (preg_match('/Weight:/i', $line)) {
			$values = preg_split('/: +/', $line);
			if (preg_match('/Height:/i', $values[1])) {
				$values2 = preg_split('/Height:/', $values[1]);
				$info["weight"] = $values2[0];
				$info["height"] = $values2[1];
				// $values[1] = $values2[0];
				// $line = $values2[1];
				continue;
			} else {
				$info["weight"] = $values[1];
				// $info["height"] = $matches[1];
			}
		}

		if (preg_match('/Height:/i', $line)) {
			$values = preg_split('/: +/', $line);
			$info["height"] = $values[1];
		}

		if (preg_match('/^Adoption Fee[:\?]/i', $line)) {
			$values = preg_split('/[:\?]\s+/', $line, 2);
			$info["adoptFee"] = $values[1];
		}
		if (preg_match('/^Fence needed\?/i', $line)) {
			$values = preg_split('/\?\s+/', $line);
			$info["fence"] = $values[1];
		}
		if (preg_match('/^Foster Location:/i', $line)) {
			$values = preg_split('/\:\s+/', $line);
			$info["location"] = $values[1];
		}
	}

	$result["about"] .= "<strong>Name:</strong> " . $info["name"] . "<br>\n";
	$result["about"] .= "<strong>Sex:</strong> " . $info["gender"] . "<br>\n";
	$result["about"] .= "<strong>Spayed/Neutered:</strong> " . $info["spayed"] . "<br>\n";
	$result["about"] .= "<strong>Breed:</strong> " . $info["breed"] . "<br>\n";
	$result["about"] .= "<strong>Weight:</strong> " . $info["weight"] . "<br>\n";
	$result["about"] .= "<strong>Height:</strong> " . $info["height"] . "<br>\n";
	$result["about"] .= "<strong>Estimated Birthdate:</strong> " . $info["bdate"] . "<br>\n";
	$result["about"] .= "<strong>Fence Needed:</strong> " . $info["fence"] . "<br>\n";
	$result["about"] .= "<strong>Location:</strong> " . $info["location"] . "<br>\n";
	$result["about"] .= "<strong>Adoption Fee:</strong>" . $info["adoptFee"] . "<br>\n";

	$result["story"] = "<p><strong>Date into rescue:</strong> " . $info["date_into_rescue"] . "</p>\n";
	$result["story"] .= "<p><strong>Reason for being in rescue?</strong> " . $info["reason_in_rescue"] . "</p>\n";
	$result["story"] .= "<p><strong>Special Needs?</strong> " . $info["special_needs"] . "</p>\n";
	$result["story"] .= "<p><strong>What kind of home would be best for me?</strong> " . $info["home"] . "</p>\n";
	$result["story"] .= "<p><strong>What is my personality like?</strong> " . $info["personality"] . "</p>\n";
	$result["story"] .= "<p><strong>How do I act when I meet new people?</strong> " . $info["new_people"] . "</p>\n";
	$result["story"] .= "<p><strong>Tips and Tidbits:</strong> " . $info["tidbits"] . "</p>\n";
	$result["story"] .= "<p><strong>House trained?</strong> " . $info["house_trained"] . "</p>\n";

	// hard coded portion of the home section
	// $result["home"] .= "\n<p><strong>House trained?</strong> Dogs can be house trained if they are in the right environment and are allowed to follow a schedule as long as a physical reason doesn't keep them from being trained.  A dog house trained in my home may not be in yours.  We will help you teach your new dog this necessary skill and based on your schedule</p>";

	// hard coded application section

	$result["application"] = "<p>Please note - we do not ship or transport our dogs. If you are interested in adopting a dog, take a look at the distance between the dog's location and your location and make sure you are able to make the trip.</p>\n\n";

	$result["application"] .= "<p>Thank you for your interest in a dog who needs a new home. This description contains all that we currently know about this dog. We have no perfect dogs - but many of our dogs have proven to be perfect for a certain someone. We urge all of our potential adopters not to fall in love with a picture. When screening applications, we look at the entire home and then make suggestions based on what would be a good fit for your home. You are not being screened for a specific dog although we are looking to see what type of dog interests you - poodles or non poodles, age, temperament, personality, etc. Our goal is to match you with the best possible pet for you and your home. We want to create furever families.</p>\n\n";

	$result["application"] .= "<p>If you would like to receiving our monthly newsletters and learn more about how to support dogs in need, please email info@carolinapoodlerescue.org or fill out our contact form and ask to join our mailing list.</p>\n\n";

	$result["application"] .= "<p>Thank you for considering CPR!</p>\n\n";

	// Hard Coded more section
	$result["more"] = "<p>Please note - we do not ship dogs.  If you are interested in adopting, please take a look at the distance between the foster home location and your location and make sure you are willing to make that trip.  Most of our dogs are at our farm in Pacolet, South Carolina. </p>\n\n";
	$result["more"] .= "<p>To apply, please visit our webpage at www.carolinapoodlerescue.org and visit the tab on the left that directions you to the online application.</p>";
	$result["more"] .= "<p>Please note that when screening applications, we look at the entire home and then make suggestions based on what would be a good fit for your home.   You are not being screened for a specific dog although we are looking to see what type of dog interests you - poodles or non poodles, color, age, etc.  Others here may be a better fit for you.  It is very difficult to get to know a living animal from a picture and a short description.  Since we are constantly getting in new dogs, this may be a  dog not in our listings yet.  We want you to be very happy with your new companion and will make suggestions based on what you tell us about you.</p>";
	$result["more"] .= "<p>Thank you for considering CPR.</p>";

	// debugObject($info);
	// debugObject($result);
	// debugObject($desc);

	return $result;
}

// ===========================================================================================================
// Function that computes the picture x and y sizes
// ===========================================================================================================
function getSize($maxSize, $x, $y) {
	//echo "maxsize = " . $maxSize . " x = " . $x . " y - " . $y . "<br>";

	if ($x < 1) {
		$x = $maxSize;
	}

	if ($y < 1) {
		$y = $maxSize;
	}

	if ($x > $y) {
		$resX = $maxSize;
		$resY = ceil($maxSize * $y / $x);
	} else {
		$resY = $maxSize;
		$resX = ceil($maxSize * $x / $y);
	}

	return array($resX, $resY);
}

// ===========================================================================================================
// Function that filters SOS from animalName
// ===========================================================================================================
function filterSOSname($name) {return preg_split('/-/', $name)[0];}

// ===========================================================================================================
// Function that prints the contents of any variable to the screen
// ===========================================================================================================
function debugObject($variable) {

	echo "<pre>";
	print_r($variable);
	echo "</pre>";

}

// ===========================================================================================================
// These functions are provided by rescue groups.  They are unchanged from what is provided from the sample at
// Reference 1: https://userguide.rescuegroups.org/display/APIDG/Full+working+PHP+example
// Reference 2: https://userguide.rescuegroups.org/display/APIDG/v2
// =========================================================================================================
function postJson($url, $json) {

	// create a new cURL resource
	$ch = curl_init();

	// set options, url, etc.
	curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
	curl_setopt($ch, CURLOPT_POST, 1);

	//curl_setopt($ch, CURLOPT_VERBOSE, true);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

	// grab URL and pass it to the browser
	$result = curl_exec($ch);

	if (curl_errno($ch)) {

		// TODO: Handle errors here
		return array(
			"result" => "",
			"status" => "error",
			"error" => curl_error($ch),
		);
	} else {
		// close cURL resource, and free up system resources
		curl_close($ch);
	}

	return array(
		"status" => "ok",
		"error" => "",
		"result" => $result,
	);
}

// =========================================================================================================
function postToApi($data) {
	$resultJson = postJson($GLOBALS["httpApiUrl"], json_encode($data));

	if ($resultJson["status"] == "ok") {
		$result = json_decode($resultJson["result"], true);
		$jsonError = getJsonError();
		if (!$jsonError && $resultJson["status"] == "ok") {
			return $result;
		} else {
			return array(
				"status" => "error",
				"text" => $result["error"] . $jsonError,
				"errors" => array(),
			);
		}
	} else {
		return false;
	}

}

// =========================================================================================================
function getJsonError() {

	switch (json_last_error()) {
	case JSON_ERROR_NONE:
		return false;
		break;

	case JSON_ERROR_DEPTH:
		return "Maximum stack depth exceeded";
		break;

	case JSON_ERROR_STATE_MISMATCH:
		return "Underflow or the modes mismatch";
		break;

	case JSON_ERROR_CTRL_CHAR:
		return "Unexpected control character found";
		break;

	case JSON_ERROR_SYNTAX:
		return "Syntax error, malformed JSON";
		break;

	case JSON_ERROR_UTF8:
		return "Malformed UTF-8 characters, possibly incorrectly encoded";
		break;

	default:
		return "Unknown error";
		break;
	}
}

// End block for JSON post
// =========================================================================================================
// ===========================================================================================================
// End of provided procedures by rescuegroups.org
// ===========================================================================================================
