<?php

#include '/home/jjglover/phptosql/GLSeditor.php';

#test files
#include '/JJCodeDepot/DBfiles/GLSeditor.php';

#$DBH = new PDO("mysql:host=$host;dbname=$db_name", $username, $password);
#$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

#$targetHTMLid = $_POST['targetImage'];

$DBH = createGLSEdit();
$targetdir = '/srv/www/goallinestats/AHA/teamimages/';

$imageFileName = $_FILES['targetImage']['name'];
$imageFileType = $_FILES['targetImage']['type'];
$imageFileSize = $_FILES['targetImage']['size'];

$profile = $_POST['teamProfile'];

$targetid = substr($profile, strpos($profile, "-")+1);
$targetclass = substr($profile, 0, strpos($profile, "-"));


$uploadOk = 1;
print_r($_FILES);

if (empty($profile)) {
	echo "Please choose where you would like to submit this picture!";
	exit();
} elseif (empty($_FILES)) {
	echo "Please choose a picture to upload!";
	exit();
} else {
	if($imageFileType != "image/jpg" && $imageFileType != "image/png" && $imageFileType != "image/jpeg" && $imageFileType != "image/gif" ) {
		echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
		echo "Result Extension: ".$imageFileType;
		$uploadOk = 0;
	}
	if($imageFileSize == 0) {
		$uploadOk = 0;
		echo "No files were submitted!";
	}
	
	$findImage = $DBH->prepare('SELECT imagelocation FROM CSSteamassignment WHERE TeamidRef = :idteamassignment AND TeamtableRef = :profiletype LIMIT 1');
	$findImage->bindParam(':idteamassignment', $targetid, PDO::PARAM_INT);
	$findImage->bindParam(':profiletype', $targetclass, PDO::PARAM_STR);
	$findImage->execute();
	$pictureexist = $findImage->rowCount;

	if ($pictureexist > 0) {
		$updateTeamImageInsert = $DBH->prepare('UPDATE CSSteamassignment SET imagelocation = :filename WHERE TeamidRef = :idassigned AND TeamtableRef = :profiletype');
		$updateTeamImageInsert->bindParam(':idassigned', $targetid, PDO::PARAM_INT);
		$updateTeamImageInsert->bindParam(':profiletype', $targetclass, PDO::PARAM_STR);
		$updateTeamImageInsert->bindParam(':filename', $imageFileName, PDO::PARAM_STR);
		$updateTeamImageInsert->execute();
	} else {
		$prepTeamImageInsert = $DBH->prepare('INSERT INTO CSSteamassignment (TeamidRef, TeamtableRef, imagelocation) VALUES (:idassigned, :profiletype, :filename)');
		$prepTeamImageInsert->bindParam(':idassigned', $targetid, PDO::PARAM_INT);
		$prepTeamImageInsert->bindParam(':profiletype', $targetclass, PDO::PARAM_STR);
		$prepTeamImageInsert->bindParam(':filename', $imageFileName, PDO::PARAM_STR);
		$prepTeamImageInsert->execute();
	}
	
	if ($uploadOk == 0) {
		echo "Sorry, your file was not uploaded.";
	// if everything is ok, try to upload file
	} else {
		if (move_uploaded_file($_FILES["targetImage"]["tmp_name"], $targetdir.$imageFileName)) {
			echo "The file ". basename( $_FILES["targetImage"]["name"]). " has been uploaded.";
		} else {
			echo "Sorry, there was an error uploading your file.";
		}
	}
}
?>