<?php

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); echo json_encode(['error' => 'Method not allowed']); exit; }

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/supabase.php';

$token = requireAuth();
$userId = getUserId($token);
if (!$userId) jsonError('Invalid user', 401);

if (!isset($_FILES['avatar']) || $_FILES['avatar']['error'] !== UPLOAD_ERR_OK) {
    jsonError('No file uploaded');
}

$file = $_FILES['avatar'];
$maxSize = 5 * 1024 * 1024;
if ($file['size'] > $maxSize) {
    jsonError('File too large (max 5MB)');
}

$allowed = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $file['tmp_name']);
finfo_close($finfo);

if (!in_array($mime, $allowed)) {
    jsonError('Invalid file type. Allowed: JPEG, PNG, WebP, GIF');
}

$ext = match($mime) {
    'image/jpeg' => 'jpg',
    'image/png' => 'png',
    'image/webp' => 'webp',
    'image/gif' => 'gif',
    default => 'jpg'
};

$filename = $userId . '_' . time() . '.' . $ext;
$storagePath = 'avatars/' . $filename;
$bucket = 'profile-images';

$storageUrl = SUPABASE_STORAGE . '/object/' . $bucket . '/' . $storagePath;

$ch = curl_init($storageUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . SUPABASE_SERVICE_KEY,
    'Content-Type: ' . $mime,
    'x-upsert: true'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($file['tmp_name']));
curl_setopt($ch, CURLOPT_TIMEOUT, 30);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode >= 400) {
    $decoded = json_decode($response, true);
    jsonError($decoded['message'] ?? 'Upload failed', 500);
}

$publicUrl = SUPABASE_STORAGE . '/object/public/' . $bucket . '/' . $storagePath;

$db = supabaseService();
$result = $db->update('profiles', ['avatar_url' => $publicUrl], ['id' => 'eq.' . $userId]);

if (isset($result['error'])) {
    jsonError('Failed to update profile');
}

jsonResponse(['avatar_url' => $publicUrl]);
