<?php

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

$uploadDir = '/fcsc/';

if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

$action = $_GET['action'] ?? '';

if ($action === 'upload') {
    if (!isset($_FILES['image']) || $_FILES['image']['error'] !== UPLOAD_ERR_OK) {
        http_response_code(400);
        echo json_encode(['error' => 'No image uploaded or upload error']);
        exit;
    }

    $tmpPath = $_FILES['image']['tmp_name'];
    $mimeType = mime_content_type($tmpPath);

    if (strpos($mimeType, 'image/') !== 0) {
        http_response_code(400);
        echo json_encode(['error' => 'Invalid file type. Only images are allowed.', 'detected' => $mimeType]);
        exit;
    }

    // Generate UUIDv4
    $uuid = sprintf(
        '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        mt_rand(0, 0xffff), mt_rand(0, 0xffff),
        mt_rand(0, 0xffff),
        mt_rand(0, 0x0fff) | 0x4000,
        mt_rand(0, 0x3fff) | 0x8000,
        mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
    );

    // Get extension from mime type
    $extensions = [
        'image/jpeg' => 'jpg',
        'image/png' => 'png',
        'image/gif' => 'gif',
        'image/webp' => 'webp',
        'image/svg+xml' => 'svg',
        'image/bmp' => 'bmp',
        'image/ico' => 'ico',
        'image/x-icon' => 'ico'
    ];

    $ext = $extensions[$mimeType] ?? 'bin';
    $filename = $uuid . '.' . $ext;
    $destPath = $uploadDir . $filename;

    if (move_uploaded_file($tmpPath, $destPath)) {
        echo json_encode([
            'success' => true,
            'id' => $uuid,
            'filename' => $filename,
            'mime' => $mimeType
        ]);
    } else {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to save image']);
    }

} elseif ($action === 'read') {
    $filename = $_GET['filename'] ?? '';

    if (empty($filename)) {
        http_response_code(400);
        echo json_encode(['error' => 'Missing filename']);
        exit;
    }

    $filename = basename($filename);
    $filePath = $uploadDir . $filename;

    if ($filename === 'secret-recipe.txt') {
        if (!isset($_COOKIE['FLAG']) || $_COOKIE['FLAG'] !== getenv('FLAG')) {
            http_response_code(403);
            echo json_encode(['error' => 'Forbidden']);
            exit;
        } else {
            http_response_code(200);
            header('Content-Disposition: attachment; filename="secret-recipe.txt"');
            echo json_encode(['success' => true, 'content' => file_get_contents($filePath), 'flag' => getenv('FLAG')]);
            exit;
        }
    }

    if (!file_exists($filePath)) {
        http_response_code(404);
        echo json_encode(['error' => 'Image not found']);
        exit;
    }

    $mimeType = mime_content_type($filePath);

    header('Content-Type: ' . $mimeType);
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    readfile($filePath);
    exit;

} else {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid action. Use action=upload or action=read']);
}
