<?php

error_reporting(E_ALL);
ini_set('display_errors', 0);

set_exception_handler(function($e) {
    http_response_code(500);
    header('Content-Type: application/json');
    echo json_encode(['error' => $e->getMessage(), 'line' => $e->getLine()]);
    exit;
});

set_error_handler(function($errno, $errstr, $errfile, $errline) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
});

header('Content-Type: application/json');
require_once __DIR__ . '/../includes/cors.php';

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'])) {
    jsonError('No file in request. upload_max_filesize=' . ini_get('upload_max_filesize') . ' post_max_size=' . ini_get('post_max_size'));
}
if ($_FILES['avatar']['error'] !== UPLOAD_ERR_OK) {
    $errors = [1 => 'File exceeds server limit', 2 => 'File exceeds form limit', 3 => 'Partial upload', 4 => 'No file sent', 6 => 'No tmp dir', 7 => 'Write failed'];
    jsonError($errors[$_FILES['avatar']['error']] ?? 'Upload error code ' . $_FILES['avatar']['error']);
}

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

$mime = mime_content_type($file['tmp_name']);
$allowed = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];

if (!in_array($mime, $allowed)) {
    jsonError('Invalid file type: ' . $mime . '. 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;
$fileContents = file_get_contents($file['tmp_name']);

if ($fileContents === false) {
    jsonError('Failed to read uploaded file');
}

$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,
    'apikey: ' . SUPABASE_SERVICE_KEY,
    'Content-Type: ' . $mime,
    'x-upsert: true'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fileContents);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);

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

if ($curlError) {
    jsonError('Storage connection failed: ' . $curlError, 500);
}

if ($httpCode >= 400) {
    $decoded = json_decode($response, true);
    jsonError('Storage error (' . $httpCode . '): ' . ($decoded['message'] ?? $decoded['error'] ?? $response), 500);
}

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

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

if (isset($result['error'])) {
    jsonError('Profile update failed: ' . $result['error']);
}

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