<?php
require_once __DIR__ . '/config.php';
$me = must_auth();
ensure_app_schema();

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $st = db()->prepare("SELECT chat_wallpaper FROM users WHERE username=? LIMIT 1");
    $st->execute(array($me));
    $row = $st->fetch();
    ok(array('wallpaper' => $row ? $row['chat_wallpaper'] : ''));
}

if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
    db()->prepare("UPDATE users SET chat_wallpaper='' WHERE username=?")->execute(array($me));
    ok(array('wallpaper' => ''));
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') fail('Method not allowed', 405);
if (empty($_FILES['wallpaper'])) fail('No wallpaper file selected');

$f = $_FILES['wallpaper'];
if ($f['error'] !== UPLOAD_ERR_OK) fail('Upload error code: '.$f['error']);
if ($f['size'] > 8 * 1024 * 1024) fail('Wallpaper is too large. Max 8MB.');

$mime = mime_content_type($f['tmp_name']);
$allowed = array('image/jpeg','image/png','image/gif','image/webp');
if (!in_array($mime, $allowed)) fail('Only JPG, PNG, GIF, or WEBP wallpapers are allowed.');

$ext = strtolower(pathinfo($f['name'], PATHINFO_EXTENSION));
$ext = preg_replace('/[^a-z0-9]/', '', $ext);
if ($ext === '') {
    $map = array('image/jpeg'=>'jpg','image/png'=>'png','image/gif'=>'gif','image/webp'=>'webp');
    $ext = isset($map[$mime]) ? $map[$mime] : 'jpg';
}

$dir = UP_DIR . 'wallpapers/';
if (!is_dir($dir)) mkdir($dir, 0777, true);
$name = preg_replace('/[^a-zA-Z0-9_-]/', '_', $me) . '_' . bin2hex(random_bytes(8)) . '.' . $ext;
if (!move_uploaded_file($f['tmp_name'], $dir . $name)) fail('Could not save wallpaper');

$url = UP_URL . 'wallpapers/' . $name;
db()->prepare("UPDATE users SET chat_wallpaper=? WHERE username=?")->execute(array($url, $me));
ok(array('wallpaper' => $url));
