<?php
/**
 * Avatar upload endpoint
 * POST /avatar-api/upload.php
 * Body (JSON): { "staticId": "12345", "image": "data:image/png;base64,..." }
 * Returns: { "url": "https://cloud.nextshift-studio.store/avatar-api/avatars/12345/avatar.png" }
 *
 * Protected by a shared secret token in config.php
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, X-Token');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

require_once __DIR__ . '/config.php'; // defines AVATAR_SECRET and BASE_URL

// ── Auth ─────────────────────────────────────────────────────────────────────
$token = $_SERVER['HTTP_X_TOKEN'] ?? '';
if ($token !== AVATAR_SECRET) {
    http_response_code(403);
    echo json_encode(['error' => 'Forbidden']);
    exit;
}

// ── Parse body ───────────────────────────────────────────────────────────────
$body = json_decode(file_get_contents('php://input'), true);
if (!$body) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid JSON']);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'];

// ── DELETE ────────────────────────────────────────────────────────────────────
if ($method === 'DELETE') {
    $staticId = preg_replace('/[^0-9]/', '', $body['staticId'] ?? '');
    if ($staticId === '') {
        http_response_code(400);
        echo json_encode(['error' => 'Missing staticId']);
        exit;
    }
    $file = __DIR__ . '/avatars/' . $staticId . '/avatar.png';
    if (file_exists($file)) {
        unlink($file);
    }
    echo json_encode(['ok' => true]);
    exit;
}

// ── POST (upload) ─────────────────────────────────────────────────────────────
if ($method !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

$staticId = preg_replace('/[^0-9]/', '', $body['staticId'] ?? '');
if ($staticId === '') {
    http_response_code(400);
    echo json_encode(['error' => 'Missing or invalid staticId']);
    exit;
}

$image = $body['image'] ?? '';
if (empty($image)) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing image']);
    exit;
}

// Strip data URI prefix if present
$image = preg_replace('/^data:image\/\w+;base64,/', '', $image);
$imageData = base64_decode($image, true);
if ($imageData === false) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid base64 data']);
    exit;
}

// Verify it's actually a PNG/JPEG (magic bytes check)
$magic = substr($imageData, 0, 4);
$isPng  = (substr($magic, 0, 4) === "\x89PNG");
$isJpeg = (substr($magic, 0, 2) === "\xFF\xD8");
if (!$isPng && !$isJpeg) {
    http_response_code(400);
    echo json_encode(['error' => 'Only PNG/JPEG images allowed']);
    exit;
}

// Save file
$dir = __DIR__ . '/avatars/' . $staticId;
if (!is_dir($dir)) {
    mkdir($dir, 0755, true);
}

$filePath = $dir . '/avatar.png';
if (file_put_contents($filePath, $imageData) === false) {
    http_response_code(500);
    echo json_encode(['error' => 'Failed to save image']);
    exit;
}

$url = BASE_URL . '/avatars/' . $staticId . '/avatar.png';
echo json_encode(['url' => $url]);
