<?php
declare(strict_types=1);

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/market_common.php';

function market_image_extension(string $mime): ?string {
    return match ($mime) {
        'image/jpeg' => 'jpg',
        'image/png' => 'png',
        'image/webp' => 'webp',
        default => null,
    };
}

function market_upload_error_message(int $error): string {
    switch ($error) {
        case UPLOAD_ERR_INI_SIZE:
        case UPLOAD_ERR_FORM_SIZE:
            return 'The server rejected this image because it exceeds PHP upload_max_filesize. Increase upload_max_filesize and post_max_size in php.ini, then restart Apache.';
        case UPLOAD_ERR_PARTIAL:
            return 'The image upload was interrupted. Reconnect and send the image again.';
        case UPLOAD_ERR_NO_FILE:
            return 'The request reached the server without image bytes. The app must attach each photo as images[].';
        case UPLOAD_ERR_NO_TMP_DIR:
            return 'PHP has no temporary upload folder. Configure upload_tmp_dir in php.ini.';
        case UPLOAD_ERR_CANT_WRITE:
            return 'The server cannot write the uploaded image. Check the PHP temporary folder and uploads folder permissions.';
        case UPLOAD_ERR_EXTENSION:
            return 'A PHP extension stopped the image upload. Check the PHP/Apache error log.';
        default:
            return 'The server could not receive the image. PHP upload error code: ' . $error . '.';
    }
}

function market_make_thumbnail(string $source, string $destination, string $mime): bool {
    if (!extension_loaded('gd')) return false;
    $src = match ($mime) {
        'image/jpeg' => @imagecreatefromjpeg($source),
        'image/png' => @imagecreatefrompng($source),
        'image/webp' => function_exists('imagecreatefromwebp') ? @imagecreatefromwebp($source) : false,
        default => false,
    };
    if (!$src) return false;
    $width = imagesx($src);
    $height = imagesy($src);
    if ($width <= 0 || $height <= 0) { imagedestroy($src); return false; }
    $maxWidth = 720;
    $ratio = min(1, $maxWidth / $width);
    $newWidth = max(1, (int)round($width * $ratio));
    $newHeight = max(1, (int)round($height * $ratio));
    $thumb = imagecreatetruecolor($newWidth, $newHeight);
    if ($mime === 'image/png') {
        imagealphablending($thumb, false);
        imagesavealpha($thumb, true);
    }
    imagecopyresampled($thumb, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
    $saved = match ($mime) {
        'image/jpeg' => imagejpeg($thumb, $destination, 78),
        'image/png' => imagepng($thumb, $destination, 6),
        'image/webp' => function_exists('imagewebp') ? imagewebp($thumb, $destination, 78) : false,
        default => false,
    };
    imagedestroy($thumb);
    imagedestroy($src);
    return (bool)$saved;
}

try {
    rvu_ensure_market_tables($pdo);
    $user = rvu_market_require_user($pdo);
    $method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');

    if ($method === 'POST') {
        // PHP empties both arrays when post_max_size is exceeded.
        if ((int)($_SERVER['CONTENT_LENGTH'] ?? 0) > 0 && empty($_POST) && empty($_FILES)) {
            rvu_market_json(['detail' => 'The images exceed PHP post_max_size. Increase post_max_size and upload_max_filesize in php.ini, then restart Apache.'], 413);
        }
        $itemId = (int)($_POST['item_id'] ?? 0);
        if ($itemId <= 0) rvu_market_json(['detail' => 'item_id is required.'], 422);
        $item = rvu_market_fetch_item($pdo, $itemId, (int)$user['id']);
        if (!$item) rvu_market_json(['detail' => 'Listing not found.'], 404);
        if (!rvu_market_can_manage($user, $item['seller_user_id'])) {
            rvu_market_json(['detail' => 'You cannot upload media to this listing.'], 403);
        }

        $countStmt = $pdo->prepare("SELECT COUNT(*) FROM campus_market_media WHERE item_id = ? AND media_type='image'");
        $countStmt->execute([$itemId]);
        $existingCount = (int)$countStmt->fetchColumn();
        $files = $_FILES['images'] ?? null;
        if (!$files || !isset($files['name']) || !is_array($files['name'])) {
            rvu_market_json(['detail' => 'Select at least one image.'], 422);
        }
        $incomingCount = count($files['name']);
        if ($existingCount + $incomingCount > 6) {
            rvu_market_json(['detail' => 'A listing can contain a maximum of 6 pictures.'], 422);
        }

        $root = realpath(__DIR__ . '/..');
        if ($root === false) throw new RuntimeException('Application root could not be resolved.');
        $uploadDir = $root . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'market';
        $thumbDir = $uploadDir . DIRECTORY_SEPARATOR . 'thumbs';
        if (!is_dir($uploadDir) && !mkdir($uploadDir, 0775, true) && !is_dir($uploadDir)) {
            throw new RuntimeException('Unable to create marketplace upload directory.');
        }
        if (!is_dir($thumbDir) && !mkdir($thumbDir, 0775, true) && !is_dir($thumbDir)) {
            throw new RuntimeException('Unable to create marketplace thumbnail directory.');
        }

        $finfo = new finfo(FILEINFO_MIME_TYPE);
        $insert = $pdo->prepare("INSERT INTO campus_market_media
            (item_id, media_type, media_path, thumbnail_path, file_size, position)
            VALUES (?, 'image', ?, ?, ?, ?) RETURNING id");
        $created = [];

        for ($i = 0; $i < $incomingCount; $i++) {
            $error = (int)$files['error'][$i];
            if ($error !== UPLOAD_ERR_OK) throw new RuntimeException(market_upload_error_message($error));
            $tmp = (string)$files['tmp_name'][$i];
            $size = (int)$files['size'][$i];
            if ($size <= 0 || $size > 8 * 1024 * 1024) {
                throw new RuntimeException('Each marketplace image must be no larger than 8 MB.');
            }
            $mime = (string)$finfo->file($tmp);
            $ext = market_image_extension($mime);
            if ($ext === null) throw new RuntimeException('Only JPEG, PNG and WebP images are allowed.');

            $token = bin2hex(random_bytes(12));
            $name = 'market_' . $itemId . '_' . $token . '.' . $ext;
            $thumbName = 'market_' . $itemId . '_' . $token . '_thumb.' . $ext;
            $destination = $uploadDir . DIRECTORY_SEPARATOR . $name;
            $thumbDestination = $thumbDir . DIRECTORY_SEPARATOR . $thumbName;
            if (!move_uploaded_file($tmp, $destination)) throw new RuntimeException('Failed to save marketplace image.');

            $mediaPath = 'uploads/market/' . $name;
            $thumbPath = market_make_thumbnail($destination, $thumbDestination, $mime)
                ? 'uploads/market/thumbs/' . $thumbName
                : $mediaPath;

            $position = $existingCount + $i;
            $insert->execute([$itemId, $mediaPath, $thumbPath, $size, $position]);
            $created[] = [
                'id' => (int)$insert->fetchColumn(),
                'type' => 'image',
                'path' => $mediaPath,
                'thumbnail_path' => $thumbPath,
                'file_size' => $size,
            ];
        }
        rvu_market_json(['data' => $created], 201);
    }

    if ($method === 'DELETE') {
        $mediaId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
        if ($mediaId <= 0) rvu_market_json(['detail' => 'Media id is required.'], 422);
        $stmt = $pdo->prepare("SELECT m.*, i.seller_user_id FROM campus_market_media m INNER JOIN campus_market_items i ON i.id=m.item_id WHERE m.id=? LIMIT 1");
        $stmt->execute([$mediaId]);
        $media = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$media) rvu_market_json(['detail' => 'Media not found.'], 404);
        if (!rvu_market_can_manage($user, $media['seller_user_id'] !== null ? (int)$media['seller_user_id'] : null)) {
            rvu_market_json(['detail' => 'You cannot delete this media.'], 403);
        }
        $pdo->prepare('DELETE FROM campus_market_media WHERE id=?')->execute([$mediaId]);
        rvu_market_remove_physical_media([$media]);
        rvu_market_json(['message' => 'Image removed.']);
    }

    rvu_market_json(['detail' => 'Unsupported request.'], 405);
} catch (Throwable $e) {
    rvu_market_json(['detail' => 'Marketplace media server error: ' . $e->getMessage()], 500);
}
