<?php

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


namespace Apps\Shop\Helper;

use Core\Utility\Format\Format;
use Apps\Shop\Helper\ShopHelper;
use Apps\Shop\Entity\ShopCategory;
use Apps\Shop\Widget\CategoryForm\CategoryForm;
use Apps\Shop\Entity\ShopProductCategory;

use Core\Entity\Entity\Argument;

class CategoryHelper
{

    /***
     * Get All category of the current Shop
     */
    public static function GetAll($core, $json = false){

        $shop = ShopHelper::GetDefault($core);

        if($shop){
            $category = new ShopCategory($core);
            $categories = $category->Find("ShopId=" . $shop->IdEntite);
        
            if($json){
                return $category->ToAllArray($categories);
            }
            return $categories;
        
        }

        return [];
    }

    /***
     * Sauvegarde une catégorie
     */
    public static function SaveCategory($core, $data){

        $categoryForm = new CategoryForm($core, $data);

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

            $category = new ShopCategory($core);
            
            if($data["Id"] != "" ){
                $category->GetById($data["Id"]);
            } else {
                $shop = ShopHelper::GetShop($core);
                $category->ShopId->Value = $shop[0]->IdEntite;
            }

            $category->Code->Value = Format::ReplaceForUrl($data["Name"]);
         
            $categoryForm->Populate($category);
            $category->Save();

            if($data["Id"] == ""){
                $category->IdEntite = $core->Db->GetInsertedId();
            }
            
            $category->SaveImage($data["dvUpload-UploadfileToUpload"], true);
            
            return true;
        }

        return false;
    }
    
    /***
     * Supprime une catégorie
     */
    public static function DeleteCategory($core, $categoryId){

        //Suppression dans les produit
        $productCategory = new ShopProductCategory($core);
        $productCategory->AddArgument(new Argument("Apps\Shop\Entity\ShopProductCategory" , "CategoryId", EQUAL, $categoryId));
        $productCategory->DeleteByArg();
        
        $category = new ShopCategory($core);
        $category->GetById($categoryId);
        $category->Delete();
        
        return true;
    }
}