<?php

namespace App\Model;


use Nette\Database\SqlLiteral;
use Nette\Http\FileUpload;
use Nette\Utils\Random;
use Nette\Utils\Strings;

class EditorManager extends BaseManager
{
    private const MAX_FILE_SIZE = 10_000_000 * 10; // 100 MB
    public const ARTICLE_FILES_PATH = '../files/article_files/';
    private const ALLOWED_MIME_TYPES = [
        'application/pdf',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document', // docx
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',       // xlsx
        'application/vnd.openxmlformats-officedocument.presentationml.presentation', // pptx
        'text/plain',
        'image/png',
        'image/jpeg',
        'image/',
    ];


    public function createArticle($authorId, $data): int
     {
         return $this->database->table('articles')
             ->insert([
                 'title' => $data['title'],
                 'type' => $data['type'],
                 'short_description' => $data['short_description'],
                 'content' => json_encode($data['content']),
                 'time_estimate' => $data['time_estimate'],
                 'difficulty' => $data['difficulty'],
                 'usage_count' => 0,
                 'users_id' => $authorId,
                 'topic_id' => $data['topic_id'],
                 'status' => 'IN_PROGRESS',
                 'created_at' => new SqlLiteral('NOW()'),
                 'updated_at' => new SqlLiteral('NOW()'),
            ])->id;
     }

     public function updateArticle($articleId, $data): void
     {
         $this->database->table('articles')
             ->where('id', $articleId)
             ->update([
             'title' => $data['title'],
             'type' => $data['type'],
             'short_description' => $data['short_description'],
             'content' => $data['content'],
             'time_estimate' => $data['time_estimate'],
             'difficulty' => $data['difficulty'],
             'topic_id' => $data['topic_id'],
             'updated_at' => new SqlLiteral('NOW()'),
         ]);
     }

     public function setArticleStatus($articleId, $newStatus): void
     {
         $this->database->table('articles')
             ->where('id', $articleId)
             ->update([
                 'status' => $newStatus,
                 'created_at' => new SqlLiteral('NOW()'),
                 ]);
     }

     public function uploadFileToArticle($articleId, FileUpload $file): bool
     {
         if (!$file->isOk()) {
             return false;
         }

         if ($file->getSize() > self::MAX_FILE_SIZE) {
             return false;
         }

         $mime = $file->getContentType();
         /*if (!in_array($mime, self::ALLOWED_MIME_TYPES, true)) {
             return false;
         }*/

         $clean = Strings::webalize($file->getSanitizedName(), '.');
         $target = sprintf('%s-%s', Random::generate(20), $clean);

         mkdir($this->getArticleFilesPath() . $articleId);
         $path = $this->getArticleFilesPath() . $articleId . "/" . $target;
         $file->move($path);
         $this->database->table('files')
             ->insert(
                 [
                     'name' => $clean,
                     'path' => $articleId . "/" . $target,
                     'article_id' => $articleId
                 ]
             );
         return true;
     }

    public function getArticleFilesPath(): string
    {
        return self::ARTICLE_FILES_PATH;
    }
}