<?php

header('Content-Type: application/json');

$method = $_SERVER['REQUEST_METHOD'];
$target_dir = "uploads/";

// Ensure the uploads directory exists and is writable
if (!is_dir($target_dir)) {
    mkdir($target_dir, 0777, true);
}

switch ($method) {
    case 'GET':
        if (isset($_GET['filename'])) {
            $filename = $_GET['filename'];
            $filepath = $target_dir . $filename;

            if (file_exists($filepath)) {
                header('Content-Type: ' . mime_content_type($filepath));
                header('Content-Length: ' . filesize($filepath));
                
                readfile($filepath);
                exit;
            } else {
                http_response_code(404);
                echo json_encode(['error' => 'File not found']);
                exit;
            }
        } else {
            echo json_encode(['error' => 'Filename is required']);
        }
        break;

    case 'POST':
        if (!empty($_FILES["photo"]["name"])) {
            $target_file = $target_dir . basename($_FILES["photo"]["name"]);
            $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

            $uploadOk = 1;

            // Check if file already exists
            if (file_exists($target_file)) {
                echo json_encode(['error' => 'Sorry, file already exists.']);
                $uploadOk = 0;
            }

            // Check file size (limit to 5MB)
            if ($_FILES["photo"]["size"] > 5000000) {
                echo json_encode(['error' => 'Sorry, your file is too large.']);
                $uploadOk = 0;
            }

            // Allow certain file formats
            $allowed_formats = array("jpg", "jpeg", "png", "gif");
            if (!in_array($imageFileType, $allowed_formats)) {
                echo json_encode(['error' => 'Sorry, only JPG, JPEG, PNG & GIF files are allowed.']);
                $uploadOk = 0;
            }

            // Check if $uploadOk is set to 0 by an error
            if ($uploadOk == 0) {
                echo json_encode(['error' => 'Sorry, your file was not uploaded.']);
            } else {
                // Attempt to upload the file
                if (move_uploaded_file($_FILES["photo"]["tmp_name"], $target_file)) {
                    echo json_encode(['message' => 'The file ' . basename($_FILES["photo"]["name"]) . ' has been uploaded.']);
                } else {
                    echo json_encode(['error' => 'Sorry, there was an error uploading your file.']);
                }
            }
        } else {
            echo json_encode(['error' => 'No file uploaded.']);
        }
        break;

    default:
        echo json_encode(['error' => 'Invalid request method']);
        break;
}
?>
