<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Middleware\AuthMiddleware;
use App\Utils\Env;
use App\Config\Database;

class UploadController extends Controller {
    
    public function avatar() {
        $userId = AuthMiddleware::authenticate();
        
        if (!isset($_FILES['avatar'])) {
            $this->json(['error' => 'No file uploaded'], 400);
        }
        
        $file = $_FILES['avatar'];
        
        if ($file['error'] !== UPLOAD_ERR_OK) {
            $this->json(['error' => 'Upload failed with error code ' . $file['error']], 500);
        }
        
        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
        if (!in_array($file['type'], $allowedTypes)) {
            $this->json(['error' => 'Invalid file type'], 400);
        }
        
        if ($file['size'] > 5 * 1024 * 1024) { // 5MB
             $this->json(['error' => 'File too large (max 5MB)'], 400);
        }
        
        $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
        $filename = 'avatar_' . $userId . '_' . time() . '.' . $ext;
        $uploadDir = __DIR__ . '/../../public/uploads/avatars/';
        
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }
        
        $targetPath = $uploadDir . $filename;
        
        if (move_uploaded_file($file['tmp_name'], $targetPath)) {
            $baseUrl = Env::get('APP_URL', 'http://s3rv.messrypt.com/backend-php/public');
            $avatarUrl = $baseUrl . '/uploads/avatars/' . $filename;
            
            // Update user's avatar_url in database
            $db = Database::getInstance()->getConnection();
            $stmt = $db->prepare("UPDATE users SET avatar_url = ? WHERE id = ?");
            $stmt->execute([$avatarUrl, $userId]);
            
            $this->json(['url' => $avatarUrl]);
        } else {
            $this->json(['error' => 'Failed to move uploaded file'], 500);
        }
    }
}
