<?php

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


namespace Apps\Shop\Helper;

use Apps\Shop\Entity\ShopShop;
use Apps\Shop\Widget\ShopForm\ShopForm;
use Core\Utility\Format\Format;

class ShopHelper
{
    /***
     * Obtient la boutique par défault
     */
    public static function GetDefault($core){
        $shop = new ShopShop($core);
        $shops = $shop->Find("id > 0 order by Id Desc");

        return count($shops) > 0 ? $shops[0] : null; 
    }

    /***
     * Vérifie si un utilisateur à une boutique
     */
    public static function HaveShop($core){

        $shop = new ShopShop($core);
        return count($shop->Find("UserId=" . $core->User->IdEntite)) > 0;
    }
    
    /***
     * Obtient la boutique de l'user connecté
     */
    public static function GetShop($core){

        $shop = new ShopShop($core);
        return $shop->Find("UserId=" . $core->User->IdEntite);
    }

    /***
     * Sauvegarde la boutiqur pour l'utilisateur connecté
     */
 
     public static function SaveShop($core, $data){
        
        $shopForm = new ShopForm($core, $data);

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

            $shop = self::GetShop($core);
           
            if(count($shop) == 0){
                $shop = new ShopShop($core);
                $shop->Code->Value = Format::ReplaceForUrl($data["Name"]);
                $shop->UserId->Value = $core->User->IdEntite;
            } else {
                $shop = $shop[0];
            }

            $shopForm->Populate($shop);
            $shop->Save();
        }
    }
}