<?php
// api/profile_images.php
// Stores profile pictures as physical files under /uploads/profile_pictures.
// PostgreSQL should store only the returned relative path.

header('Content-Type: application/json; charset=UTF-8');

function profileRespond(int $code, ?array $body = null): void {
    http_response_code($code);
    if ($body !== null) {
        echo json_encode($body, JSON_UNESCAPED_SLASHES);
    }
    exit;
}

function normalizeProfilePath(string $path): string {
    $path = trim(str_replace('\\', '/', $path));
    $path = ltrim($path, '/');
    return $path;
}

function absoluteProfilePath(string $relativePath): ?string {
    $relativePath = normalizeProfilePath($relativePath);
    $prefix = 'uploads/profile_pictures/';
    if (!str_starts_with($relativePath, $prefix)) {
        return null;
    }

    $fileName = basename($relativePath);
    if ($fileName === '' || $fileName === '.' || $fileName === '..') {
        return null;
    }

    return dirname(__DIR__) . DIRECTORY_SEPARATOR . 'uploads'
        . DIRECTORY_SEPARATOR . 'profile_pictures'
        . DIRECTORY_SEPARATOR . $fileName;
}

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$uploadDir = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'uploads'
    . DIRECTORY_SEPARATOR . 'profile_pictures';

if ($method === 'POST') {
    if (!isset($_FILES['file']) || !is_array($_FILES['file'])) {
        profileRespond(400, ['detail' => 'No profile image was supplied. Use multipart field "file".']);
    }

    $file = $_FILES['file'];
    $error = (int)($file['error'] ?? UPLOAD_ERR_NO_FILE);
    if ($error !== UPLOAD_ERR_OK) {
        $messages = [
            UPLOAD_ERR_INI_SIZE => 'Image exceeds the server upload_max_filesize limit.',
            UPLOAD_ERR_FORM_SIZE => 'Image exceeds the form size limit.',
            UPLOAD_ERR_PARTIAL => 'Image upload was incomplete.',
            UPLOAD_ERR_NO_FILE => 'No image was uploaded.',
            UPLOAD_ERR_NO_TMP_DIR => 'Server temporary upload directory is missing.',
            UPLOAD_ERR_CANT_WRITE => 'Server could not write the uploaded image.',
            UPLOAD_ERR_EXTENSION => 'A PHP extension stopped the upload.',
        ];
        profileRespond(400, ['detail' => $messages[$error] ?? 'Unknown upload error.']);
    }

    $size = (int)($file['size'] ?? 0);
    $maxBytes = 5 * 1024 * 1024; // 5 MB source-image limit.
    if ($size <= 0) {
        profileRespond(400, ['detail' => 'Uploaded image is empty.']);
    }
    if ($size > $maxBytes) {
        profileRespond(413, ['detail' => 'Profile image is too large. Maximum source size is 5 MB.']);
    }

    $tmpName = (string)($file['tmp_name'] ?? '');
    if ($tmpName === '' || !is_uploaded_file($tmpName)) {
        profileRespond(400, ['detail' => 'Invalid uploaded file.']);
    }

    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mime = (string)$finfo->file($tmpName);
    $allowed = [
        'image/jpeg' => 'jpg',
        'image/png' => 'png',
        'image/webp' => 'webp',
    ];
    if (!isset($allowed[$mime])) {
        profileRespond(415, ['detail' => 'Only JPEG, PNG and WebP profile images are allowed.']);
    }

    if (!is_dir($uploadDir) && !mkdir($uploadDir, 0755, true) && !is_dir($uploadDir)) {
        profileRespond(500, ['detail' => 'Could not create uploads/profile_pictures directory.']);
    }
    if (!is_writable($uploadDir)) {
        profileRespond(500, ['detail' => 'uploads/profile_pictures is not writable by PHP.']);
    }

    try {
        $random = bin2hex(random_bytes(8));
    } catch (Throwable $e) {
        $random = str_replace('.', '', uniqid('', true));
    }

    $extension = $allowed[$mime];
    $fileName = 'profile_' . date('Ymd_His') . '_' . $random . '.' . $extension;
    $destination = $uploadDir . DIRECTORY_SEPARATOR . $fileName;

    if (!move_uploaded_file($tmpName, $destination)) {
        profileRespond(500, ['detail' => 'Could not move profile image into the uploads folder.']);
    }

    $relativePath = 'uploads/profile_pictures/' . $fileName;
    profileRespond(201, [
        'message' => 'Profile image uploaded successfully.',
        'path' => $relativePath,
    ]);
}

if ($method === 'DELETE') {
    $raw = file_get_contents('php://input');
    $decoded = json_decode($raw, true);
    if (!is_array($decoded)) {
        profileRespond(400, ['detail' => 'Supply JSON containing the profile image path.']);
    }

    $relativePath = normalizeProfilePath((string)($decoded['path'] ?? ''));
    $absolutePath = absoluteProfilePath($relativePath);
    if ($absolutePath === null) {
        profileRespond(400, ['detail' => 'Only files inside uploads/profile_pictures can be removed.']);
    }

    if (!is_file($absolutePath)) {
        profileRespond(404, ['detail' => 'Profile image file was already absent.']);
    }

    if (!unlink($absolutePath)) {
        profileRespond(500, ['detail' => 'Profile image file could not be removed.']);
    }

    profileRespond(200, ['message' => 'Profile image removed.']);
}

profileRespond(405, ['detail' => 'Only POST and DELETE are supported.']);
