<?php

	session_start();

	include "library.php";

			/* get variables */

	$domain = $_SERVER[ 'HTTP_HOST' ];
	$pathroot = $_SESSION['pathroot'];
	$id = $_SESSION['id'];

	$photo_number = $_GET['photonumber'];
	$delete = $_GET['delete'];

	$cxn = db_login();
	
			/* start page */

	page_header( "", $cxn );

	if ($delete == "no")
		echo "Deletion cancelled.";
	else
	{
			/* check the member id  */

		if ($_SESSION['id'] == "")
			echo "Internal error, ID is not set in delete photo";
		else
		if ($photo_number == "")
			echo "Internal error, photo number is not set in delete photo";
		else
		{
				/* get the file extension */

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

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

			if (mysql_num_rows($result) == 0)
				echo "Internal error photo not found";
			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'] );

				$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 */

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

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

				if (mysql_num_rows($result) != 0)
				{
					$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 "Photo deleted successfully<br><br><a href='http://".$domain."/manage_photos.php?".SID."'>Return to photos page</a>";
			}
		}
	}
?>

