<?php

namespace App\Presentation\Profile;

use App\Model\ProfileManager;
use App\Presentation\BasePresenter;
use Nette\Utils\ImageType;

class ProfilePresenter extends BasePresenter
{
    private ProfileManager $profileManager;

    public function __construct(ProfileManager $profileManager)
    {
        parent::__construct();
        $this->profileManager = $profileManager;
    }

    public function actionUploadprofileimg(): void
    {
        if (!$this->getUser()->isLoggedIn()) {
            $this->error("User is not logged in", 403);
        }

        $files = $this->getUploadedFilesAndCheckRequest();

        if (count($files) != 1) {
            $this->error('There must be only 1 profile image file', 400);
        }

        $result = false;
        foreach ($this->getHttpRequest()->getFiles() as $file) {
            $result = $this->profileManager->changeProfileImage($this->getUser()->getId(), $file);
        }
        if (!$result) {
            $this->error("Invalid image", 400);
        }
        $this->sendJson(["success" => $result]);
    }

    public function renderGetprofileimg($userId): void
    {
        if ($userId == null) {
            $this->error("Invalid user id", 400);
        }

        $image = $this->profileManager->getProfileImage($userId);
        if ($image == null) {
            $this->error("Profile image is not set.", 404);
        }

        try {
            $image->send();
        } catch (\Exception) {
            $this->error("Error while loading profile image.", 500);
        }
    }

    public function actionUpdateusersettings()
    {
        if (!$this->getUser()->isLoggedIn())
        {
            $this->error("User is not logged in", 403);
        }

        $payload = $this->getPayloadJsonAndCheckRequest(['email', 'bio']);
        $this->profileManager->updateUserSettings($this->getUser()->getId(), $payload);
        $this->sendJson(['success' => true]);
    }
}