<?php

namespace App\Model;

use Nette\Http\FileUpload;
use Nette\Utils\Image;
use Nette\Utils\ImageType;

class ProfileManager extends BaseManager
{
    public const PROFILE_IMAGE_PATH = './files/profile_images/';

    public function getProfileImagePath(): string
    {
        return self::PROFILE_IMAGE_PATH;
    }

    public function changeProfileImage($userId, FileUpload $file): bool
    {
        if (!$file->isImage())
            return false;

        if ($file->getSize() >= 5000000)
            return false;

        $table = $this->database->table('users');
        $selection = $table
            ->where('id', $userId);

        try {
            $image = Image::fromFile($file->getTemporaryFile());
            $fileName = $userId . ".jpg";
        } catch (\Exception) {
            return false;
        }

        if ($selection->fetch()->profile_image != null) {

            unlink(self::PROFILE_IMAGE_PATH . $table->get($userId)['profile_image']);
        }

        $image->save(self::PROFILE_IMAGE_PATH . $fileName, 80, ImageType::JPEG);
        $selection->update([
            'profile_image' => $fileName
        ]);
        return true;
    }

    public function getProfileImage($userId): ?Image
    {
        $row = $this->database->table('users')
                ->get($userId);

        if ($row == null)
            return null;

        try {
            return Image::fromFile(self::PROFILE_IMAGE_PATH . $row['profile_image']);
        } catch (\Exception) {
            return null;
        }
    }

    public function updateUserSettings($userId, $data)
    {
        $this->database->table('users')
            ->where('id', $userId)
            ->update([
                'email' => $data['email'],
                'bio' => $data['bio'],
            ]);
    }
}