<?php

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

namespace Apps\Seo\Helper;

use Apps\Seo\Entity\SeoPage;
use Core\Entity\Entity\Argument;
use Apps\Seo\Widget\PageSeoForm\PageSeoForm;
use Core\Utility\Format\Format;

class PageHelper {

    /**
     * Sauvegarde une page grâce au pageForm
     */
    public static function SavePageSeoForm($core, $data) {

        $pageForm = new PageSeoForm($core, $data);

        //On valide le formulaire
        if ($pageForm->Validate()) {

            $page = new SeoPage($core);

            if (isset($data["Id"]) && $data["Id"] != "") {
                $id = $data["Id"];
                $page->GetById($data["Id"]);
            } else {
                //Catégorie 1 pour commencer car les autres ne sont pas afficher pour l'instant
                //$page->CmsId->Value = 1;
            }
            
            $pageForm->Populate($page);

            //On sauvegarde
            $page->Save();

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

            return $pageForm->Success(array("Id" => $id, "pages" => self::GetAll($core)));
        } else {
            return $pageForm->Error();
        }
    }
    
    /***
     * Obtient toutes les pages au format json
     */
    public static function GetAll($core, $jsonFormat = true){
        
         $page = new SeoPage($core);
         $pages = $page->GetAll();
         $jsonPage = array();
         
         foreach($pages as $page){
             $jsonPage[] = $page->ToArray();
         }
         
         return json_encode($jsonPage);
    }
    
    /***
     * Supprime une page 
     */
    public static function DeletePage($core, $pageId){
         $page = new SeoPage($core);
         $page->GetById($pageId);
         $page->Delete();
         
         return json_encode(array("pages" => self::GetAll($core)));
    }
}
