<?php

/**
 * Application de gestion des page paramétrables
 * */

namespace Apps\Cms;

use Core\Core\Core;
use Core\Core\Request;
use Core\Core\Response;
use Core\Utility\File\File;
use Core\Utility\ImageHelper\ImageHelper;
use Core\Control\ListBox\ListBox;
use Core\App\Application;
use Apps\Cms\Entity\CmsCms;
use Apps\Cms\Entity\CmsPage;
use Apps\Cms\Helper\CmsHelper;
use Apps\Cms\Helper\PageHelper;
use Apps\Cms\Helper\SitemapHelper;

use Apps\Cms\Module\Admin\AdminController;
use Apps\Cms\Module\Cms\CmsController;
use Apps\Cms\Module\Page\PageController;
use Apps\Cms\Module\Api\ApiController;
use Apps\Cms\Widget\AdminDashBoard\AdminDashBoard;
use Apps\Cms\Widget\BlockContent\BlockContent;
use Apps\Cms\Widget\PageContent\PageContent;
use Apps\Cms\Widget\LoginMenu\LoginMenu;
use Apps\Cms\Helper\BlockHelper;
use Apps\Cms\Widget\ContactForm\ContactForm;

class Cms extends Application {

    /**
     * Auteur et version
     * */
    public $Author = 'Eemmys';
    public $Version = '2.1.5.0';
    public static $Directory = "../Apps/Cms";

    /**
     * Constructeur
     * */
    function __construct() {
        $this->Core = Core::getInstance();
        parent::__construct($this->Core, "Cms");
    }

    /**
     * Execution de l'application
     */
    function Run() {
        echo parent::RunApp($this->Core, "Cms", "Cms");
    }

    /**
     * Set the Public Routes
     */
    public function GetRoute($routes = "") {
        $this->Route->SetPublic(array(""));

        return $this->Route;
    }

    /**
     * Sauvegare les images de presentation
     */
    function DoUploadFile($idElement, $tmpFileName, $fileName, $action) {

        switch ($action) {

            case "SaveImagePage" :

                //Recuperaion de l'page afin d'avoir le dossier du cms
                $page = new CmsPage($this->Core);
                $page->GetById($idElement);
                $folder = $page->CmsId->Value;

                //Sauvegarde
                move_uploaded_file($tmpFileName, $directory . $folder . "/" . $idElement . ".png");

                //Crée un miniature
                $image = new ImageHelper();
                $image->load($directory . $folder . "/" . $idElement . ".png");
                $image->fctredimimage(96, 0, $directory . $folder . "/" . $idElement . "_96.png");
                echo Response::Success(array("type:" => "IMAGE", "Message" => "OK"));

                break;
            default :

                $directory = "Data/Tmp/";

                //Import file
                if ($action == "UploadImport") {

                    $fileTmp = $directory . $folder . "import.csv";

                    move_uploaded_file($tmpFileName, $fileTmp);

                    echo Response::Success(array("type:" => "DOCUMENT", "file" => $fileTmp));
                } else {
                    //Sauvegarde
                    move_uploaded_file($tmpFileName, $directory . $folder . "/" . $idElement . ".jpg");

                    echo Response::Success(array("type:" => "IMAGE", "MESSAGE" => "OK"));
                }
                break;
        }
    }

    /**
     * Affiche une page du cms
     * @param type $cms
     * @param type $page
     */
    function ShowPage($pageName) {

        $page = new CmsPage($this->Core);
        $page = $page->GetByName($pageName);

        $this->Core->MasterView->Set("Title", $page->Title->Value);
        $this->Core->MasterView->Set("Description", $page->Description->Value);

        return $this->GetWidget("PageContent", $pageName);
    }

    /*     * *
     * Obtient les widget
     */

    public function GetWidget($type = "", $params = "") {

        if ($type == "") {
            $type = Request::GetPost("type");
        }

        switch ($type) {
            case "AdminDashboard" :
                $widget = new AdminDashBoard($this->Core);
                break;
            case "BlockContent" :
                $widget = new BlockContent($this->Core);
                break;
            case "PageContent" :
                $widget = new PageContent($this->Core);
                break;
            case "LoginMenu" :
                $widget = new LoginMenu($this->Core);
                break;
            case "ContactForm" :
                $widget = new ContactForm($this->Core);
                break;
        }

        return $widget->Render($params);
    }

     /**
     * Get The siteMap 
     */
    public function GetSiteMap($returnUrl = false) {
        return SitemapHelper::GetSiteMap($this->Core, $returnUrl);
    }
    
    /*     * *
     * Get cms Addable widget
     */

    public function GetListWidget() {
        return array(array("Name" => "LoginMenu",
                "Description" => $this->Core->GetCode("Cms.DescriptionLoginMenu")),
            array("Name" => "ContactForm",
                "Description" => $this->Core->GetCode("Cms.DescriptionContactForm"))
        );
    }

    /*     * **
     * Retourne The Specifique admin Widget
     */

    public function GetAdminWidget($type = "", $params = "") {
        $adminController = new AdminController($this->Core);
        return $adminController->GetWidget($type = "", $params = "");
    }

       public function GetListWidgetBlock() {
        
        //Ajout des widgets de Base
        $Apps = \Apps\EeApp\Helper\AppHelper::GetAll($this->Core);
        $widgetsBlock = new ListBox("Widget");
        $descriptionWidget = "";
        $iWidget = 0;    
  
        foreach ($Apps as $app) {
            $appName = $app->Name->Value;
            $path = "\\Apps\\" . $appName . "\\" . $appName;
            $app = new $path($core);
            $listWidget = $app->GetListWidget();
         
            if (count($listWidget) > 0) {
                foreach ($listWidget as $widget) {

                    if(isset($widget["Name"])){  

                        $name = $widget["Name"];    
                        $widgetsBlock->Add($appName . "-" .$name, $appName . "-" . $name);
                        $style ="";

                        if($iWidget > 0){
                            $style='display:none';
                        }
                        $descriptionWidget .= "<p class='descriptionWidget info' id='descriptionWiget-".$appName . "-" .$name."' style='".$style."'><i class='fa fa-info fa-2x'></i>"  . $widget["Description"] . "</p>";
                        $descriptionWidget .= "<p class='paramsWidget info' id='paramsWidget-".$appName . "-" .$name."' style='".$style."'>"  . $widget["Parameters"] ?? "" . "</p>";
                       
                        $iWidget ++;
                    }
                }
            }
        }
        return "<label>" . $this->Core->GetCode("Cms.WidgetAvialable") . "</label>" .$widgetsBlock->Show().$descriptionWidget;
    }
    
    /***
     * Add HeadScript Container
     */
    function AddHeadScripContainer(){
        $adminController = new AdminController($this->Core);
        return $adminController->AddHeadScripContainer(Request::GetPosts());
        
    }
    
    /**
     * Enregistre une page
     */
    function SavePage() {
        $adminController = new AdminController($this->Core);
        return $adminController->SavePage(Request::GetPosts());
    }

    /*     * *
     * Add Container to a page
     */

    function SaveContainer() {
        $adminController = new AdminController($this->Core);
        return $adminController->SaveContainer(Request::GetPosts());
    }

    /**
     * Delete a container
     */
    function RemoveContainer() {
        $adminController = new AdminController($this->Core);
        return $adminController->RemoveContainer(Request::GetPost("ContainerId"));
    }

    /**
     * Add Image to Library
     */
    function UplodImageToLibrary() {
        $adminController = new AdminController($this->Core);
        return $adminController->UplodImageToLibrary(Request::GetPosts());
    }

    /*     * *
     * Add block à un container
     */

    function SaveBlock() {
        $adminController = new AdminController($this->Core);
        return $adminController->SaveBlock(Request::GetPosts());
    }

    /*     * *
     * Set the content to a block
     */

    function UpdateContentBlock() {
        $adminController = new AdminController($this->Core);
        return $adminController->UpdateContentBlock(Request::GetPosts());
    }

    /*     * *
     * Delete a block 
     */

    function RemoveBlock() {
        $adminController = new AdminController($this->Core);
        return $adminController->RemoveBlock(Request::GetPost("BlockId"));
    }

    /*     * *
     * Add Item to a block
     */

    function SaveBlockItem() {
        $adminController = new AdminController($this->Core);
        return $adminController->SaveBlockItem(Request::GetPosts());
    }

    /*     * *
     * Delete à item to a menu
     */

    function RemoveItemMenu() {
        $adminController = new AdminController($this->Core);
        return $adminController->RemoveItemMenu(Request::GetPost("ItemId"));
    }

    /*     * *
     * Save a image to a block
     */

    function SaveBlockImage() {
        $adminController = new AdminController($this->Core);
        return $adminController->SaveBlockImage(Request::GetPosts());
    }

    /*     * *
     * Sauvegarde le style du css
     */

    function SaveStyle() {
        $adminController = new AdminController($this->Core);
        return $adminController->SaveStyle(Request::GetPost("css"));
    }

    /*     * *
     * Delet a page
     */

    function RemovePage() {
        $adminController = new AdminController($this->Core);
        return $adminController->RemovePage(Request::GetPost("pageId"));
    }

    /*     * *
     * Export All Pages
     */

    function ExportPages() {
        $adminController = new AdminController($this->Core);
        return $adminController->ExportPages();
    }

    /*     * *
     * Import Pages, Container and Block
     */

    public function ImportPages() {
        $adminController = new AdminController($this->Core);
        return Response::Success($adminController->ImportPages($this->Core, Request::GetPosts()));
    }
    
    public function ImportContent($content){
        
       $data = json_decode($content);
      
       //var_dump($data);
       
       $message ="Debut du traitement";
         
       foreach($data as $page){
       
           $message .= "<br>--------------"; 
           $message .= \Apps\Cms\Helper\ImportHelper::ImportPage($this->Core, $page);
       }
    }

    /*     * *
     * Get data and Content of a page
     */

    public function GetPage($name) {
        $apiController = new ApiController($this->Core);
        return Response::Success($apiController->GetPage($name));
    }

    /*     * *
     * Get List of page
     */

    public function GetListPage($name) {
        $apiController = new ApiController($this->Core);
        return Response::Success($apiController->GetListPage($name));
    }

    /***
     * Get List Email of Base App 
     */
    public function GetListEmail(){
        return array("register", "forgetPassword");
    }

    /***
     * Get list of Event can be used in WorkFlow
     */
    public function GetListEvent(){

        return array(array("Name" => "NewUser",
          "Description" => $this->Core->GetCode("Base.NewUserEventDescription")),
        );
    }
}
