<?php

	include "library.php";

	$cxn = start_code();

	$cxn_common = db_common_login();


	
			/* get variables */

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

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

	$photo_number = val( $_GET, "photonumber" );
	$delete = val( $_GET, "delete" );


			/* start page */

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


			/* check parameters */

	crash_if_missing( $id, "id missing in delete_photo", $cxn );

	crash_if_missing( $pathroot, "pathroot missing in delete_photo", $cxn );

	crash_if_missing( $photo_number, "photo_number missing in delete_photo", $cxn );

	crash_if_missing( $delete, "delete missing in delete_photo", $cxn );


	if ($delete == "no")
		echo black( "<br>Deletion cancelled<br><br><br>" );
	else
	{
			/* get the file extension */

		$query = "SELECT * FROM photos WHERE member_id = ".$id." AND photo_number = ".$photo_number;

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

		if (query_num_rows($result) == 0)
			crash( "Internal error photo not found", $cxn );
		else
		{
			$data = get_row( $result );

			$primary_photo = $data['primary_photo'];

//			unlink( $pathroot."/photos/photo_".$id."_".$photo_number.".".$data['file_extension'] );
			unlink( $pathroot."/photos/photo_".$id."_".$photo_number."_sm.".$data['file_extension'] );
			unlink( $pathroot."/photos/photo_".$id."_".$photo_number."_l.".$data['file_extension'] );

			$query = "DELETE FROM photos WHERE member_id = ".$id." AND photo_number = ".$photo_number;

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

				/* if we deleted the primary photo set the most recently added photo to be the primary */

			if (query_has_rows( "SELECT id FROM photos WHERE member_id = ".$id, $cxn))
			{
				if (! query_has_rows( "SELECT id FROM photos WHERE member_id = ".$id." AND primary_photo = 'yes'", $cxn))
				{
					$query = "SELECT MAX(photo_number) as new_primary_photo FROM photos WHERE member_id = ".$id;
					$result = run_query( $query, $cxn );
					$data = get_row( $result );

					$query = "UPDATE photos SET primary_photo = 'yes' WHERE member_id = ".$id." AND photo_number = ".$data['new_primary_photo'];
					$result = run_query( $query, $cxn );
				}
			}

			echo black( "<br>Photo deleted successfully<br><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" );

?>