<?php
/**
 * Filename 	: image-uploader.php
 * Created by	: Andy Christian S. Loyola
 * Author		: Andy Christian S. Loyola <acl20032003@gmail.com>
 */

 
 
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_FILES['file']) && $_FILES['file']['error'] === UPLOAD_ERR_OK) {
        $fileTmpPath = $_FILES['file']['tmp_name'];
        $fileName = $_FILES['file']['name'];
        $fileSize = $_FILES['file']['size'];
        $fileType = $_FILES['file']['type'];
        $fileNameCmps = explode(".", $fileName);
        $fileExtension = strtolower(end($fileNameCmps));

        $allowedfileExtensions = ['jpg', 'gif', 'png', 'jpeg'];
        if (in_array($fileExtension, $allowedfileExtensions)) {
            $uploadFileDir = './uploads/';
            $dest_path = $uploadFileDir . $fileName;
            
            // Check if file already exists and handle renaming
            $counter = 1;
            $originalFileName = pathinfo($fileName, PATHINFO_FILENAME);
            while (file_exists($dest_path)) {
                $newFileName = $originalFileName . '_' . $counter . '.' . $fileExtension;
                $dest_path = $uploadFileDir . $newFileName;
                $counter++;
            }
            
            if (move_uploaded_file($fileTmpPath, $dest_path)) {
                $response = ['location' => $dest_path];
                echo json_encode($response);
            }
			else {
                $response = ['location' => ''];
                echo json_encode($response);
            }
        }
		else {
            $response = ['location' => ''];
            echo json_encode($response);
        }
    }
	else {
        $response = ['location' => ''];
        echo json_encode($response);
    }
}
else {
    $response = ['location' => ''];
    echo json_encode($response);
}
?>
