<?php
session_start();
	
	//echo getcwd();
	require('../photo.php');
	$pArray = [];
	
	//If we were passed something then confirm that it exists.
	$fp = fopen("../Photos.txt", 'rb');
	if (!$fp) {
		echo "reached here";
		echo "<b> could not open file<p>";
		exit;
	}
	
	//run until we find the entry matching the passed data
	while (!feof($fp)) {
		$temp = fgets($fp, 999);
		
		if (!$temp)
			break;
		$photo = new Photo();
		$photo->fillFromJSON($temp);
			
		array_push($pArray, $photo);
	}
		
	fclose($fp);
	
	//print_r($_POST); echo "<br>";
	
	$fp = fopen("../Photos.txt", 'wb');
	if (!$fp) {
		echo "reached write open file";
		echo "<b> could not open file<p>";
		exit;
	}
	
	for($i =0; $i < count($pArray); $i++){
		
		//check if matching
		if($pArray[$i]->fileName == $_POST['fileName'] && $pArray[$i]->user == $_SESSION['valid_user']) { // || $User == "admin"))
			if(isset($_POST['Edit_Me'])){
				//Editing
				if($pArray[$i]->view != $_POST['view']){ //if we swap from either public or private
					$pArray[$i]->view = $_POST['view'];					
				}
				
				$pArray[$i]->theDate = $_POST['theDate'];
				$pArray[$i]->theTime = $_POST['theTime'];
				$pArray[$i]->theLong = $_POST['theLong'];
				$pArray[$i]->theLat = $_POST['theLat'];
				$pArray[$i]->theCity = $_POST['theCity'];
				//put the updated info here
				
				$newPhoto = json_encode($pArray[$i]);
				fwrite($fp, $newPhoto, strlen($newPhoto));
				fwrite($fp, "\n");
			}
			else{
				//we're deleting 
				$file = "../uploads/".$pArray[$i]->fileName;
				if(!unlink($file)){
					echo "could not delete file1";
					print_r(error_get_last());
				}
				$file = "../uploads/".pathinfo($pArray[$i]->fileName, PATHINFO_FILENAME)."Pin.png";
				if(!unlink($file)){
					echo "could not delete file2";
					print_r(error_get_last());
				}
				$file = "../uploads/".pathinfo($pArray[$i]->fileName, PATHINFO_FILENAME)."PPin.png";
				if(!unlink($file)){
					echo "could not delete file3";
					print_r(error_get_last());
				}
			}
		}
		else{
			//echo "no match";
			$newPhoto = json_encode($pArray[$i]);
			fwrite($fp, $newPhoto, strlen($newPhoto));
			fwrite($fp, "\n");
		}
	}
	fclose($fp);
	
	echo '<script>window.location.href = "../liveIndex.php"</script>';
?>

<!-- <a href="../liveIndex.php">Return</a> -->