<?php

	include "library.php";

	$cxn = start_code();

	$cxn_common = db_common_login();


	
			/* get variables */

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

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

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


			/* start page */

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


			/* check parameters */

	crash_if_missing( $listing_id, "listing_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( "Deletion cancelled<br><br>" );
	else
	{
			/* get the file extension */

		$query = "SELECT * FROM photos WHERE listing_id = ".$listing_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_".$listing_id."_".$photo_number."_sm.".$data['file_extension'] );
			unlink( $pathroot."/photos/photo_".$listing_id."_".$photo_number."_l.".$data['file_extension'] );

			$query = "DELETE FROM photos WHERE listing_id = ".$listing_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 listing_id = ".$listing_id, $cxn))
			{
				if (! query_has_rows( "SELECT id FROM photos WHERE listing_id = ".$listing_id." AND primary_photo = 'yes'", $cxn))
				{
					$query = "SELECT MAX(photo_number) as new_primary_photo FROM photos WHERE listing_id = ".$id;
					$result = run_query( $query, $cxn );
					$data = get_row( $result );

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

			echo black( "Photo deleted successfully<br><br>" );
		}
	}

	echo show_link( "Return", "manage_photos.php", "listing_id", $listing_id );
?>

