<?php

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


namespace Apps\Shop\Helper;

use Core\Utility\Format\Format;
use Core\Utility\File\File;
use Apps\Shop\Entity\ShopProduct;
use Apps\Shop\Entity\ShopProductCategory;
use Apps\Shop\Entity\ShopProductCaracteristique;
use Apps\Shop\Widget\ProductForm\ProductForm;
use Apps\Shop\Helper\ShopHelper;

class ProductHelper
{
    /**
     * Sauvegarde un produit
     */
    public static function SaveProduct($core, $data){

        $productForm = new ProductForm($core, $data);

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

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

            $productForm->Populate($shop);
            $product->Save();
            
            if(!isset($id)){
              $id = $core->Db->GetInsertedId();  
            }

            //Base Directory
            File::CreateDirectory("Data/Apps/Shop");
            File::CreateDirectory("Data/Apps/Shop/Product/");
            File::CreateDirectory("Data/Apps/Shop/ProductDocument/");
            

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

            File::CreateDirectory($directory);

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

                $source = str_replace($core->GetPath("/"), "", $image);
                $filename = explode("/", $source);

                rename($source, $directory . $filename[count($filename) - 1]);
            }
            

            //Sauvegare des documents
            $directory = $product->DirectoryDocument . $id . "/";

            File::CreateDirectory($directory);

            foreach (explode(",", $data["dvUpload-UploadDocumentfileToUpload"]) as $document) {

                $source = str_replace($core->GetPath("/"), "", $document);
                $filename = explode("/", $source);

                rename($source, $directory . $filename[count($filename) - 1]);
            }
           

            return $productForm->Success(array());
        
        }  else {
              return $productForm->Error();
        }
    } 

    /***
     * Le produit a déjà la catégorie
     */
    public static function HaveCategory($core, $productId, $categoryId){
        $productCategory = new ShopProductCategory($core);
        $category = $productCategory->Find("ProductId= " .$productId. " And CategoryId=".$categoryId );

        return (count($category) > 0 );
    }

    /**
     * Ajoute une catégorie à un produit
     */
    public static function AddCategoryProduct($core, $data){

        if(!self::HaveCategory($core, $data["productId"], $data["categoryId"])){
        
            $productCategory = new ShopProductCategory($core);
            $productCategory->ProductId->Value = $data["productId"];
            $productCategory->CategoryId->Value = $data["categoryId"];
            $productCategory->Save();
        }

        return self::GetCategoryByProduct($core, $data["productId"]);
    }

    /***
     * Obtient les catégories d'un produit
     */
    public static function GetCategoryByProduct($core, $productId){
       
       $productCategory = new ShopProductCategory($core);
       $productCategory->Select("category.Name", "CategoryName");
       $productCategory->Join("ShopCategory", "category", "left", "category.Id = ShopProductCategory.CategoryId");
       
       $categories = $productCategory->Find("ProductId= " . $productId);
       $categoriesArray = array();

       foreach($categories as $category){
            $categoryArray = $category->ToArray();
            $categoryArray["CategorieName"] = $category->CategoryName->Value;
            $categoriesArray[] = $categoryArray;
       }

       return $categoriesArray;
    }

    /**
     * Supprime une catégorie de produit
     */
    public static function RemoveCategorieProduct($core, $productId){
        $productCategory = new ShopProductCategory($core);
        $productCategory->GetById($productId);
        $productCategory->Delete();
    }

    /***
     * Obtient les caracteristique d'un produit
     */
    public static function GetCaracteristiqueByProduct($core, $productId, $returnType = "array"){

        $productCaracteristique = new ShopProductCaracteristique($core);
        $productCaracteristique->Select("caracteristique.Name", "CaracteristiqueName");
        $productCaracteristique->Select("caracteristiqueItem.Label", "CaracteristiqueItemName");
        
        $productCaracteristique->Join("ShopCaracteristique", "caracteristique", "left", "caracteristique.Id = ShopProductCaracteristique.CaracteristiqueId");
        $productCaracteristique->Join("ShopCaracteristiqueItem", "caracteristiqueItem", "left", "caracteristiqueItem.Id = ShopProductCaracteristique.ItemId");
        
        $caracteristiques = $productCaracteristique->Find("ProductId= " . $productId);

        if($returnType != "array"){
            return $caracteristiques;
        }

        $caracteristiquesArray = array();
 
        foreach($caracteristiques as $caracteristique){
             $caracteristiqueArray = $caracteristique->ToArray();
             $caracteristiqueArray["CaracteristiqueName"] = $caracteristique->CaracteristiqueName->Value;
             $caracteristiqueArray["CaracteristiqueItemName"] = $caracteristique->CaracteristiqueItemName->Value;
             $caracteristiquesArray[] = $caracteristiqueArray;
        }
 
        return $caracteristiquesArray;
    }

    /***
     * Add Caracteristique to a product
     */
    public static function AddCaracteristiqueProduct($core, $data){

        $productCaracteristique = new ShopProductCaracteristique($core);
        $productCaracteristique->ProductId->Value = $data["productId"];
        $productCaracteristique->CaracteristiqueId->Value = $data["caracteristiqueId"];
        $productCaracteristique->ItemId->Value = $data["itemId"];
        $productCaracteristique->Save();

        return self::GetCaracteristiqueByProduct($core, $data["productId"]);
    }

    /***
     * Remove a caracteristique for à product
     */
    public static function RemoveCaracteristiqueProduct($core, $productId){
        $productCaracteristique = new ShopProductCaracteristique($core);
        $productCaracteristique->GetById($productId);
        $productCaracteristique->Delete();
    }
    
    /***
     * Get The Product of a category
     */
    public static function GetByCategorie($core, $categoryId, $returnArray = false){
       
        $product = new ShopProduct($core);
        $product->Join("ShopProductCategory", "productCategory", "left", "productCategory.ProductId = ShopProduct.Id");
        
        $products = $product->Find("productCategory.CategoryId=" . $categoryId);

        if($returnArray){
            return $product->ToAllArray($products);
        }

        return $products;
    }

    /***
     * Get Last added Product
     */
    public static function GetLast($core){
        $product = new ShopProduct($core);
        return $product->Find("id > 0 order by Id desc limit 0,5");
    }

    /***
     * Get detail of a product
     */
    public static function GetProduct($core, $productId){
        $product = new ShopProduct($core);
        $product->GetById($productId);

        return $product->ToArray();
    }

    /***
     * Get detail of products
     */
    public static function GetProducts($core, $productIds){
        $product = new ShopProduct($core);
        $products = $product->Find("id in(".$productIds.")");
        return $product->ToAllArray($products);
    }

    /**
     * Get the Child Product
     */
    public static function GetChilds($core, $productId){
        $product = new ShopProduct($core);
        $products = $product->Find("ParentId =".$productId."");
        return $products;
    }
}