<?php

	include "library.php";
	
	$cxn = start_code();
	
	$cxn_common = db_common_login();
	

	ini_set( "post_max_size", "16M" );	
	ini_set( "upload_max_filesize", "16M" );	

	
		/* get variables */

	$pathroot = val( $_SESSION, "pathroot" );
	$id = val( $_SESSION, "id" );


//      Monitor execution time and memory usage
//	include "ubench/Ubench.php";
//	$bench = new Ubench;
//    $bench->start();


	page_header( "", $cxn, $cxn_common );

		/* check the member id  */

	crash_if_missing( $id, "id is not set in upload photos", $cxn );

	if ($_FILES['file']['name'] == "")
		echo black( "<br>No file is selected. Please go back to the Upload Photos screen and click on the 'Choose File' button.<br>" );
	else
	{
			/* get the new photo number */

//		$query = "SELECT MAX(photo_number) as max_photo_number FROM photos WHERE member_id = ".$id;

		$query = "SELECT new_photo_number FROM profile WHERE id = ".$id;

		$result = run_query( $query, $cxn );

		$data = get_row( $result );

//		$photo_number = $data['max_photo_number'] + 1;

		$photo_number = $data['new_photo_number'];

		$new_photo_number = $data['new_photo_number'] + 1;

		$query = "UPDATE profile SET new_photo_number = ".$new_photo_number." WHERE id = ".$id;

		$result = run_query( $query, $cxn );


			/* extract the file extension */

		$filename = $_FILES['file']['name'];

		$pos = strlen( $filename ) - 1;

		while ($pos > 0 and substr( $filename, $pos, 1 ) != ".")
			$pos = $pos - 1;

		$file_extension = substr( $filename, $pos+1, strlen( $filename ) - $pos - 1);
			

			/* upload the file */

		$destfile = $pathroot."/photos/photo_".$id."_".$photo_number.".".$file_extension;

		if (move_uploaded_file( $_FILES['file']['tmp_name'], $destfile ))
			chmod( $destfile, 0744 );
		else
		{
			echo black( "The file that you've selected could not be uploaded<br><br>" );
			
			print_r(error_get_last());
			
        	echo show_home_link();			
			
			exit();
		}

		$im = @imagecreatefromjpeg( $destfile );

	    if (!$im)
		{
			echo black( "The file that you have uploaded is not a valid JPG file" );
			unlink( $destfile );
			exit;
		}

			/* get the image width and height */

		list( $width, $height, $type, $attr ) = getimagesize( $destfile );

		if ($height == 0)
			$aspect_ratio = 1;
		else
			$aspect_ratio = $width / $height;


			/* create the smaller resolution file */

		$destfile_sm = $pathroot."/photos/photo_".$id."_".$photo_number."_sm.".$file_extension;

		$new_width = 120 * $aspect_ratio;
		$new_height = 120;

		$image_p = imagecreatetruecolor( $new_width, $new_height );

		$image = imagecreatefromjpeg( $destfile );

		imagecopyresampled( $image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height );

		imagejpeg( $image_p, $destfile_sm, 90 );		/* the 90 is the percentage of original image quality (compression) */


				// release memory
		imagedestroy( $image_p );
		imagedestroy( $image );			


			/* create the larger resolution file */

		$destfile_l = $pathroot."/photos/photo_".$id."_".$photo_number."_l.".$file_extension;

		$new_width2 = 380 * $aspect_ratio;
		$new_height2 = 380;

		$image_p2 = imagecreatetruecolor( $new_width2, $new_height2 );

		$image2 = imagecreatefromjpeg( $destfile );

		imagecopyresampled( $image_p2, $image2, 0, 0, 0, 0, $new_width2, $new_height2, $width, $height );

		imagejpeg( $image_p2, $destfile_l, 100 );		/* the 100 is the percentage of original image quality (compression) */


				// release memory
		imagedestroy( $image_p2 );
		imagedestroy( $image2 );			


			/* delete the original file */
			
//		unlink( $pathroot."/photos/photo_".$id."_".$photo_number.".".$file_extension );


			/* save a record to the database */

		$uploaded_datetime = date("Y-m-d H:i:s");


			/* insert as primary if there isn't one already (this should only happen when zero photos for the member) */

		if (query_has_rows( "SELECT id FROM photos WHERE member_id = ".$id." AND primary_photo = 'yes'", $cxn ))
			$query = "INSERT INTO photos (member_id, photo_number, file_extension, primary_photo, aspect_ratio, version, uploaded_datetime) values ($id, $photo_number, '$file_extension', 'no', $aspect_ratio, '', '".$uploaded_datetime."')";
		else
			$query = "INSERT INTO photos (member_id, photo_number, file_extension, primary_photo, aspect_ratio, version, uploaded_datetime) values ($id, $photo_number, '$file_extension', 'yes', $aspect_ratio, '', '".$uploaded_datetime."')";

		$result = run_query( $query, $cxn );


//			// don't send a reminder message about photos once they have uploaded one
//
//		$sent = date("Y-m-d H:i:s");
//
//		if (! query_has_rows( "SELECT id FROM sys_message WHERE sent_to_id = ".$id." AND type = 'post_photo_email_not_needed'", $cxn ))
//		{
//			$query = "INSERT INTO sys_message (sent_to_id, type, sent) VALUES (".$id.", 'post_photo_email_not_needed', '".$sent."')";
//			$result2 = run_query( $query, $cxn );
//		}
			
		echo black( "Photo uploaded successfully<br><br>If your photo needs to be rotated, this can be done on the 'Photos' tab from the home page.<br><br>" );

        show_photo( $id, 100, $photo_number, true, false, $cxn );
	}


//      Monitor execution time and memory usage
//    $bench->end();
//    echo "Elapsed time: ".$bench->getTime()."<br>";
//    echo "Peak memory usage: ".$bench->getMemoryPeak()."<br>";
//    echo "Current memory usage: ".$bench->getMemoryUsage()."<br>";


    echo "<br><br>";

	echo show_home_link();

		// don't go back to the photos screen because a browser back button will upload the photo twice	
//	echo show_link( "Return", "manage_photos.php" );

//	echo "</body>";
	
?>