<?php

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

namespace Apps\Shop;

use Core\Core\Core;
use Core\Core\Request;
use Core\Core\Response;
use Apps\Base\Base;
use Apps\Shop\Helper\ShopHelper;
use Apps\Shop\Helper\CategoryHelper;
use Apps\Shop\Helper\CaracteristiqueHelper;
use Apps\Shop\Helper\ProductHelper;
use Apps\Shop\Module\Admin\AdminController;
use Apps\Shop\Module\Front\FrontController;
use Apps\Shop\Module\Cart\CartController;
use Apps\Shop\Module\Member\MemberController;
use Apps\Shop\Module\Paiement\PaiementController;
use Apps\Shop\Module\Download\DownloadController;

use Apps\Shop\Widget\CardWidget\CardWidget;
use Apps\Shop\Widget\LastProductWidget\LastProductWidget;
use Apps\Shop\Widget\OneProductWidget\OneProductWidget;

use Apps\Shop\Helper\CartHelper;
use Apps\Shop\Helper\CommandHelper;

use Apps\Shop\Widget\AdminDashBoard\AdminDashBoard;



class Shop extends Base {

    /**
     * Auteur et version
     * */
    public $Author = 'Webemyos';
    public $Version = '1.0.1.0';

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

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

    /***
     * Run member Controller
     */
    function RunMember(){
        $memberController = new MemberController($this->Core);
        return $memberController->Index();
    }

    /**
     * Définie les routes publiques
     */
    function GetRoute($routes = "") {
        parent::GetRoute(array("Category", "Product", "Cart", "AddToCart", "GetCart", "RemoveToCart", "ValidationPay",
                                "Download", "SaveContactAndDownload" , "DownLoadFree"
    ));
        return $this->Route;
    }

    
       /*     * *
     * Execute action after install
     */

    function PostInstall() {
        \Apps\EeApp\Helper\AppHelper::UpdateAppParams($this->Core,
                "Shop",
                $this->Version,
                "Application E-Commerce",
                1,
                1
        );

        \Apps\EeApp\Helper\AppHelper::CreateDataDir("Shop");
    }

    
    /***
     * Home page Shop
     */
    function Index(){
        $this->Core->MasterView->Set("Title", $this->Core->GetCode("Shop.HomePageTitle"));
        $frontController = new FrontController($this->Core);
        return $frontController->Index();
    }
    
    /***
     * Category page Shop
     */
    function Category($params){
        $frontController = new FrontController($this->Core);
        return $frontController->Category($params);
    }
    
    /***
     * Product page Shop
     */
    function Product($params){
        $frontController = new FrontController($this->Core);
        return $frontController->Product($params);
    }
    
    /***
     * Card page Shop
     */
    function Cart($params){
        $frontController = new FrontController($this->Core);
        return $frontController->Cart($params);
    }
    
    /***
     * Téléchargement d'un produit
     */
    function Download($params){

       $this->Core->MasterView->Set("Title", $this->Core->GetCode("Shop.Download"));

       $downloadController = new DownloadController($this->Core);
       return $downloadController->DownLoad($params);
    }

    function DownLoadFree($params){

        $this->Core->MasterView->Set("Title", $this->Core->GetCode("Shop.Download"));
 
        $downloadController = new DownloadController($this->Core);
        return $downloadController->DownLoadFree($params);
     }

    /*
    * Save contact And Download
    */
    function SaveContactAndDownload(){
        $downloadController = new DownloadController($this->Core);
        $result =  $downloadController->SaveContactAndDownload(Request::GetPosts());

        if($result){
            return Response::Success(["token" => Request::GetPost("Token") ]);
        }
    }

    /*     * *
     * Sauvegarde la boutique pour l'utilisateur connecté
     */

    function SaveShop() {
        return ShopHelper::SaveShop($this->Core, Request::GetPosts());
    }

    /*     * *
     * Sauvegarde la catégorie
     */

    function SaveCategory() {
        if (CategoryHelper::SaveCategory($this->Core, Request::GetPosts())) {
            $adminController = new AdminController($this->Core);
            return Response::Success($adminController->GetTabCategory());
        } else {
            return Response::Error();
        }
    }

    /*     * *
     * Supprime une catégorie
     */

    function DeleteCategory() {
        if (CategoryHelper::DeleteCategory($this->Core, Request::GetPost("categoryId"))) {

            $adminController = new AdminController($this->Core);
            return Response::Success($adminController->GetTabCategory());
        } else {
            return Response::Error();
        }
    }

    /**
     * Sauvegarde la caractéristique
     */
    function SaveCaracteristique() {
        if (CaracteristiqueHelper::SaveCaracteristique($this->Core, Request::GetPosts())) {
            $adminController = new AdminController($this->Core);
            return Response::Success($adminController->GetTabCaracteristique());
        } else {
            return Response::Error();
        }
    }

    /*     * *
     * Supprime une caracteristiques
     */

    function DeleteCaracteristique() {
        if (CaracteristiqueHelper::DeleteCaracteristique($this->Core, Request::GetPost("caracteristiqueId"))) {

            $adminController = new AdminController($this->Core);
            return Response::Success($adminController->GetTabCaracteristique());
        } else {
            return Response::Error();
        }
    }
    
    /*     * *
     * Supprime un item d'une caractétistique
     */

    function RemoveCaracteristiqueItem() {
        return CaracteristiqueHelper::RemoveCaracteristiqueItem($this->Core, Request::GetPost("itemId"));
    }

    /**
     * Sauvegarde un produit
     */
    function SaveProduct() {
        if (ProductHelper::SaveProduct($this->Core, Request::GetPosts())) {
            $adminController = new AdminController($this->Core);
            return $adminController->GetTabProduct();
        }
    }

    /*     * *
     * Ajoute une catgégorie à un produit
     */

    function AddCategoryProduct() {
        return json_encode(ProductHelper::AddCategoryProduct($this->Core, Request::GetPosts()));
    }

    /*
     * Supprime une catégorie de produit
     */

    function RemoveCategorieProduct() {
        return ProductHelper::RemoveCategorieProduct($this->Core, Request::GetPost("Id"));
    }

    /*     * *
     * Get the items of  a caracteristiques
     */

    function GetCaracteristiqueItem() {
        return json_encode(CaracteristiqueHelper::GetItemByCaracteristique($this->Core, Request::GetPost("CaracteristiqueId")));
    }

    /***
     * Add a cracteristique to a product
     */
    function AddCaracteristiqueProduct(){
        return json_encode(ProductHelper::AddCaracteristiqueProduct($this->Core, Request::GetPosts()));
    }

    /***
     * Delete a caracteristique product
     */
    function RemoveCaracteristiqueProduct() {
        return ProductHelper::RemoveCaracteristiqueProduct($this->Core, Request::GetPost("Id"));
    }
    
    /****
     * Generate the bills for one command
     */
    function GenerateBill(){
        
        $adminController = new AdminController($this->Core);

        $result = $adminController->GenerateBill(Request::GetPost("CommandId"));

        if($result === true){
            return Response::Success(array("bills", $result));
        } 
        else {
            return Response::Error(array("Code", ""));
        }
    }


      /***
     * Transfert les fichiers dans le Tmp
     */
    function DoUploadFile($idElement, $tmpFileName, $fileName, $action){

        $directory = "Data/Tmp";

        if($action == "SaveDocumentProduct" ){

            move_uploaded_file($tmpFileName, $directory."/".$fileName);

            echo Response::Success(array("type:" => "DOCUMENT",
                                         "file" => $directory."/".$fileName,
                                         "Message" => "OK"));
      
        } 
        else if($action == "SaveImageProduct"){
            move_uploaded_file($tmpFileName, $directory."/".$idElement.".jpg");

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

        /*     * *
     * Obtient les widget
     */

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

        switch ($type) {
            case "AdminDashboard" :
                $widget = new AdminDashBoard($this->Core);
                break;
            case "AddToCard" :
                $widget = new CardWidget($this->Core);
                return $widget->RenderAddToCard($params);
                break;
            case "CardIcon" :
                $widget = new CardWidget($this->Core);
                return $widget->RenderCardIcon($params);
                break;   
            case "LastProduct" :
                $widget = new LastProductWidget($this->Core);
                break;  
            case "OneProduct" :
                    $widget = new OneProductWidget($this->Core);
                    break;           
        }

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

    /***
     * Widget can be Added in the Cms App
     */
    function GetListWidget(){
        return array(array("Name" =>"CardIcon",
                           'Description' => $this->Core->GetCode("Shop.DescriptionCardIcon"),
                        ),
                        array("Name" => "LastProduct", 
                        $this->Core->GetCode("Shop.DescriptionLastProduct"),
                    ),
                    array("Name" => "OneProduct", 
                        $this->Core->GetCode("Shop.DescriptionOneProduct"),
                         "Parameters"  => $this->GetListProduct()
                        )
        );
    }

    /***
     * List of ressource
     */
    public function GetListProduct(){
        $list = new \Core\Control\EntityListBox\EntityListBox("Data", $this->Core);
        $list->Entity = "\Apps\Shop\Entity\ShopProduct"; 
        $list->AddField("Name");
        return $list->Render();
    }

    /*     * *
     * Retourn le panier
     */

     function GetCart() {
        
        $cartController = new CartController($this->Core);
        return $cartController->Show();
    }

    /***
     * Retourne qu eles informations du panier
     */
    function GetInfoCart()
    {
        return CartHelper::GetCart();
    }
    
    /***
     * Récupére un panier sauvegardé
     */
    function GetSavedCart($cartId){
         return CartHelper::GetSavedCart($this->Core, $cartId);
    }
    
    /*     * *
     * Ajoute un produit au panier ou augmen,te la quantité
     * Si déjà ajouté
     */

    function AddToCart($product) {
        return CartHelper::AddToCart($this->Core, Request::GetPost("entityId"));
    }
    
    /***
     * Supprime un produit du panier
     */
    function RemoveToCart() {
       return CartHelper::RemoveToCart($this->Core, Request::GetPost("IdEntite"));
    }

    /***
     * Create a new Command 
     */
    function CreateCommand(){
        return CommandHelper::CreateCommand($this->Core, Request::GetPosts());
    }

    /***
     * Update a command
     */
    function UpdateCommand(){
        return CommandHelper::UpdateCommand($this->Core, Request::GetPosts());
    }

    /***
     * Get list of category
     */
    function GetCategory(){
        return Response::Success(CategoryHelper::GetAll($this->Core, true));
    }

    /***
     * Get product of a category
     */
    function GetProductCategory(){
        return Response::Success(ProductHelper::GetByCategorie($this->Core, Request::GetPost("categoryId"), true));
    }

    /***
     * Get a product
     */
    function GetProduct(){
        return Response::Success(ProductHelper::GetProduct($this->Core, Request::GetPost("productId"), true));
    }

    /**
     * Get list a product
     * @return type
     */
    function GetProducts(){
        return Response::Success(ProductHelper::GetProducts($this->Core, Request::GetPost("productIds"), true));
    }
    
    /****
     * Get Validation configuration
     * For adress and Paid module
     */
    function GetValidationConfiguration(){
        return Response::Success(array("delivery" => true , "pay"=> false));
    }
    

    function SendCommand($params, $userId){
        return Response::Success(CommandHelper::CreateCommandApi($this->Core, Request::GetPosts(""), $userId));
    }
    
    /***
     * Get Teh command user 
     */ 
    function GetCommands($params, $userId){
        return Response::Success(CommandHelper::GetCommandWithProduct($this->Core, $userId));
    }
    
    /**
     * Validation du paiement
     */
    function ValidationPay($commandToken){
     
        $this->Core->MasterView->Set("Title", $this->Core->GetCode("PayValidated"));
    
        if(!$this->Core->IsConnected()){
            
            $frontController = new FrontController($this->Core);
            return $frontController->NotConnected();
            
        } else {
            $paiementController = new PaiementController($this->Core);
            return $paiementController->ValidationPay($commandToken);
        }
    }
    
}

?>
