<?php
/**
 * Klasa UserProfile - rozszerzone dane użytkownika
 */

class UserProfile
{
    private Database $db;
    
    public function __construct()
    {
        $this->db = Database::getInstance();
    }
    
    /**
     * Pobierz profil użytkownika
     */
    public function getByUserId(int $userId): ?array
    {
        $profile = $this->db->fetchOne(
            "SELECT * FROM user_profiles WHERE user_id = :user_id",
            ['user_id' => $userId]
        );
        
        if (!$profile) {
            // Utwórz domyślny profil
            $this->create($userId);
            return $this->getByUserId($userId);
        }
        
        return $profile;
    }
    
    /**
     * Utwórz profil
     */
    public function create(int $userId, array $data = []): int
    {
        return $this->db->insert(
            "INSERT OR IGNORE INTO user_profiles (user_id, full_name, email, phone, company, timezone, language, theme, created_at, updated_at)
             VALUES (:user_id, :full_name, :email, :phone, :company, :timezone, :language, :theme, datetime('now'), datetime('now'))",
            [
                'user_id' => $userId,
                'full_name' => $data['full_name'] ?? '',
                'email' => $data['email'] ?? '',
                'phone' => $data['phone'] ?? '',
                'company' => $data['company'] ?? '',
                'timezone' => $data['timezone'] ?? 'Europe/Warsaw',
                'language' => $data['language'] ?? 'pl',
                'theme' => $data['theme'] ?? 'dark'
            ]
        );
    }
    
    /**
     * Aktualizuj profil
     */
    public function update(int $userId, array $data): bool
    {
        $allowedFields = [
            'full_name', 'email', 'phone', 'company', 'address',
            'timezone', 'language', 'theme',
            'notifications_email', 'notifications_browser'
        ];
        
        $updates = [];
        $params = ['user_id' => $userId];
        
        foreach ($data as $key => $value) {
            if (in_array($key, $allowedFields)) {
                $updates[] = "{$key} = :{$key}";
                $params[$key] = $value;
            }
        }
        
        if (empty($updates)) {
            return false;
        }
        
        $updates[] = "updated_at = datetime('now')";
        
        $this->db->execute(
            "UPDATE user_profiles SET " . implode(', ', $updates) . " WHERE user_id = :user_id",
            $params
        );
        
        return $this->db->getLastStatement()->rowCount() > 0;
    }
    
    /**
     * Aktualizuj avatar
     */
    public function updateAvatar(int $userId, string $avatarPath): bool
    {
        $this->db->execute(
            "UPDATE user_profiles SET avatar = :avatar, updated_at = datetime('now') WHERE user_id = :user_id",
            ['avatar' => $avatarPath, 'user_id' => $userId]
        );
        
        return $this->db->getLastStatement()->rowCount() > 0;
    }
    
    /**
     * Usuń avatar
     */
    public function removeAvatar(int $userId): bool
    {
        $profile = $this->getByUserId($userId);
        
        if ($profile && $profile['avatar']) {
            $avatarPath = __DIR__ . '/../../uploads/avatars/' . $profile['avatar'];
            if (file_exists($avatarPath)) {
                unlink($avatarPath);
            }
        }
        
        $this->db->execute(
            "UPDATE user_profiles SET avatar = NULL, updated_at = datetime('now') WHERE user_id = :user_id",
            ['user_id' => $userId]
        );
        
        return true;
    }
    
    /**
     * Przetwórz upload avatara
     */
    public function processAvatarUpload(int $userId, array $file): array
    {
        if ($file['error'] !== UPLOAD_ERR_OK) {
            return ['success' => false, 'error' => 'Błąd podczas uploadu pliku.'];
        }
        
        if ($file['size'] > 2 * 1024 * 1024) {
            return ['success' => false, 'error' => 'Plik jest za duży. Maksymalny rozmiar to 2MB.'];
        }
        
        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mimeType = finfo_file($finfo, $file['tmp_name']);
        finfo_close($finfo);
        
        if (!in_array($mimeType, $allowedTypes)) {
            return ['success' => false, 'error' => 'Niedozwolony typ pliku. Dozwolone: JPG, PNG, GIF, WEBP.'];
        }
        
        $uploadDir = __DIR__ . '/../../uploads/avatars/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }
        
        $this->removeAvatar($userId);
        
        $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
        $filename = 'avatar_' . $userId . '_' . time() . '.' . $extension;
        $filepath = $uploadDir . $filename;
        
        if (!move_uploaded_file($file['tmp_name'], $filepath)) {
            return ['success' => false, 'error' => 'Nie udało się zapisać pliku.'];
        }
        
        $this->resizeImage($filepath, 200, 200);
        $this->updateAvatar($userId, $filename);
        
        return ['success' => true, 'filename' => $filename];
    }
    
    /**
     * Zmień rozmiar obrazu
     */
    private function resizeImage(string $filepath, int $maxWidth, int $maxHeight): bool
    {
        $info = @getimagesize($filepath);
        if (!$info) return false;
        
        list($width, $height, $type) = $info;
        
        if ($width <= $maxWidth && $height <= $maxHeight) {
            return true;
        }
        
        $ratio = min($maxWidth / $width, $maxHeight / $height);
        $newWidth = (int)($width * $ratio);
        $newHeight = (int)($height * $ratio);
        
        switch ($type) {
            case IMAGETYPE_JPEG: $src = @imagecreatefromjpeg($filepath); break;
            case IMAGETYPE_PNG: $src = @imagecreatefrompng($filepath); break;
            case IMAGETYPE_GIF: $src = @imagecreatefromgif($filepath); break;
            case IMAGETYPE_WEBP: $src = @imagecreatefromwebp($filepath); break;
            default: return false;
        }
        
        if (!$src) return false;
        
        $dst = imagecreatetruecolor($newWidth, $newHeight);
        
        if ($type == IMAGETYPE_PNG || $type == IMAGETYPE_GIF) {
            imagealphablending($dst, false);
            imagesavealpha($dst, true);
        }
        
        imagecopyresampled($dst, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
        
        switch ($type) {
            case IMAGETYPE_JPEG: imagejpeg($dst, $filepath, 90); break;
            case IMAGETYPE_PNG: imagepng($dst, $filepath, 9); break;
            case IMAGETYPE_GIF: imagegif($dst, $filepath); break;
            case IMAGETYPE_WEBP: imagewebp($dst, $filepath, 90); break;
        }
        
        imagedestroy($src);
        imagedestroy($dst);
        
        return true;
    }
    
    /**
     * Pobierz URL avatara
     */
    public function getAvatarUrl(int $userId): string
    {
        $profile = $this->getByUserId($userId);
        
        if ($profile && $profile['avatar']) {
            return '/uploads/avatars/' . $profile['avatar'];
        }
        
        return '';
    }
}
