<?php
require_once __DIR__ . '/auth.php';
require_login();
header('Content-Type: application/json; charset=utf-8');

$raw = file_get_contents('php://input');
if (!$raw) { echo json_encode(['success'=>false,'message'=>'Nenhum conteúdo recebido']); exit; }
$data = json_decode($raw, true);
if (!$data || !isset($data['image'])) { echo json_encode(['success'=>false,'message'=>'Formato inválido']); exit; }

$img = $data['image'];
if (preg_match('/^data:image\/(\w+);base64,/', $img, $matches)) {
    $ext = $matches[1] === 'jpeg' ? 'jpg' : $matches[1];
    $base64 = substr($img, strpos($img, ',') + 1);
    $decoded = base64_decode($base64);
    if ($decoded === false) { echo json_encode(['success'=>false,'message'=>'Base64 inválido']); exit; }

    $uploadDir = __DIR__ . '/uploads/';
    if (!is_dir($uploadDir)) {
        if (!mkdir($uploadDir, 0755, true)) { echo json_encode(['success'=>false,'message'=>'Não foi possível criar pasta uploads.']); exit; }
    }

    $name = isset($data['name']) ? preg_replace('/[^A-Za-z0-9._-]/','_', $data['name']) : 'banner_' . time() . '.' . $ext;
    $target = $uploadDir . $name;

    if (file_put_contents($target, $decoded) === false) { echo json_encode(['success'=>false,'message'=>'Erro ao salvar imagem']); exit; }

    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'];
    $dir = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
    $url = $protocol . '://' . $host . $dir . '/uploads/' . $name;

    echo json_encode(['success'=>true,'url'=>$url]); exit;
} else {
    echo json_encode(['success'=>false,'message'=>'Conteúdo não está em base64 de imagem']); exit;
}