<?php

/*
 * PuzzleApp
 * Webemyos
 * Jérôme Oliva
 * GNU Licence
 */

namespace Apps\Blog\Helper;

use Core\Utility\Date\Date;
use Core\Utility\Format\Format;
use Core\Entity\Entity\Argument;
use Core\Utility\File\File;
use Core\Utility\ImageHelper\ImageHelper;
use Apps\Blog\Entity\BlogArticle;
use Apps\Blog\Entity\BlogCategory;
use Apps\Blog\Widget\BlogArticleForm\BlogArticleForm;

class ArticleHelper {

    /**
     * Sauvegarde l'article
     * @param type $core
     * @param type $name
     * @param type $keywork
     * @param type $description
     */
    public static function Save($core, $data) {
        $articleForm = new BlogArticleForm($core, $data);

        if ($articleForm->Validate($data)) {

            $article = new BlogArticle($core);

            if ($data["Id"] != "") {
                $article->GetById($data["Id"]);
                $id = $data["Id"];
            } else {
                $blog = BlogHelper::GetFirst($core);
                $article->BlogId->Value = $blog->IdEntite;
                $article->UserId->Value = $core->User->IdEntite;
                $article->Actif->Value = 1;
                $article->DateCreated->Value = Date::Now();
            }

            $article->Code->Value = Format::ReplaceForUrl($data["Name"]);

            $articleForm->Populate($article);
            $article->Save();

            if ($data["dvUpload-UploadfileToUpload"] != "") {

                if (!isset($id)) {
                    $id = $core->Db->GetInsertedId();
                }

                //Base Directory
                File::CreateDirectory("Data/Apps/Blog/Article");

                //Sauveagerde des images
                $directory = $article->DirectoryImage . "/" . $id . "/";

                File::CreateDirectory($directory);
                $numberImage = 0;

                foreach (explode(",", $data["dvUpload-UploadfileToUpload"]) as $image) {

                    $source = str_replace($core->GetPath("/"), "", $image);
                    $filename = explode("/", $source);
                    $destinationFile = $directory . "full.png";

                    rename($source, $destinationFile);

                    if ($numberImage == 0) {
                        $image = new ImageHelper();

                        $directory . $filename[count($filename) - 1];
                        $image->load($destinationFile);
                        $image->fctredimimage(450, 0, $directory . "thumb.png");
                        
                        //On est pas arrivé à faire la miniature
                        if(!file_exists($directory . "thumb.png")){
                            copy($directory . "full.png", $directory . "thumb.png");
                        }
                        
                    }

                    $numberImage++;
                }
            }
            return true;
        }

        return false;
    }

    /*
     * Supprime un article
     */

    public static function DeleteArticle($core, $articleId) {

        //Suppression de l'article
        $article = new BlogArticle($core);
        $article->GetById($articleId);
        $article->Delete();

        return true;
    }

    /*
     * Sauvegarde le contenu de l'article
     */

    public static function SaveContent($core, $articleId, $content) {
      
      $content = str_replace("'", '&acute;', $content);
      $content = str_replace('"', "&quot;", $content);
      
      if($content != ""){
        $request = "Update BlogArticle set content= \"".$content."\" where Id = ".$articleId;
        $core->Db->Execute($request);
      }
    }

    /**
     * Récupere tous les articles d'une catégorie
     * @return type
     */
    public static function GetByCategoryId($core, $categoryId) {
        $article = new BlogArticle($core);
        $article->AddArgument(new Argument("Apps\Blog\Entity\BlogArticle", "CategoryId", EQUAL, $categoryId));

        $article->AddArgument(new Argument("Apps\Blog\Entity\BlogArticle", "Actif", EQUAL, 1));
        $article->AddOrder("Id Desc");

        return $article->GetByArg();
    }

    /**
     * Récupere tous les articles d'une catégorie
     * @return type
     */
    public static function GetByCategoryName($core, $category) {
        //Formattage
        $category = str_replace("_", " ", $category);

        //Recuperation de la catégorie
        $categorie = new BlogCategory($core);
        $categorie->GetByName($category);

        $article = new BlogArticle($core);
        $article->AddArgument(new Argument("Apps\Blog\Entity\BlogArticle", "CategoryId", EQUAL, $categorie->IdEntite));

        $article->AddArgument(new Argument("Apps\Blog\Entity\BlogArticle", "Actif", EQUAL, 1));
        $article->AddOrder("Id");

        return $article->GetByArg();
    }

    /**
     * Retourne les trois dernier articles de la mème categorie
     */
    public static function GetSimilare($core, $article) {
        $articles = new BlogArticle($core);
        $articles->AddArgument(new Argument("Apps\Blog\Entity\BlogArticle", "Actif", EQUAL, 1));
        $articles->AddArgument(new Argument("Apps\Blog\Entity\BlogArticle", "CategoryId", EQUAL, $article->CategoryId->Value));

        $articles->AddArgument(new Argument("Apps\Blog\Entity\BlogArticle", "Id", NOTEQUAL, $article->IdEntite));
        $articles->AddArgument(new Argument("Apps\Blog\Entity\BlogArticle", "Id", LESS, $article->IdEntite));

        $articles->AddOrder("Id");
        $articles->SetLimit(1, 3);
        return $articles->GetByArg();
    }
    
    /***
     * Return mast Article
     */
    public static function GetLast($core){
      
       $article = new BlogArticle($core);
       $lastArticle = $article->Find("id > 0 ORDER BY Id DESC");
       
       if(count($lastArticle)> 0){           
        return $lastArticle[0];
       } 
       
       return null;
    }
}
