<?php

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

namespace Apps\Tips\Helper;

use Core\Utility\Format\Format;
use Core\Utility\Date\Date;

use Apps\Tips\Entity\TipsTips;
use Apps\Tips\Entity\TipsUser;
use Apps\Tips\Widget\TipsForm\TipsForm;

class TipsHelper{
    
    /***
     * Récupére un tips
     */
    public static function Get($core, $code){
        $tips = new TipsTips($core);
        return $tips->GetByCode($code);
    }
    
    /***
     * Obtient le derniers Tips a afficher pour l'utilisateur connecté
     */
    public static function GetLastFoUser($core, $userId = ""){
        
        if($userId == ""){
            $userId = $core->User->IdEntite;
        }

        $request ="select t.Id as TipsId from TipsTips as t 
                       where t.id not in(select TipsId from TipsUser where UserId = ". $userId . ") and t.Status != 99 ORDER BY t.Id";
        $result = $core->Db->GetArray($request);
        
        foreach($result as $tip){
            
            $tips = new TipsTips($core);
            $tips->GetById($tip["TipsId"]);
            
           return $tips;
        }
        
        return null;
    }
    
    /***
     * Le tips concerne t'il l'utilisateur
     */
    public static function HaveTips($core){
        
        $tips = self::GetLastFoUser($core);
       
        if($tips == null){
            return false;
        }
        
       return true;
    }
    
    /***
     * Sauvegarde du tips pour l'utilisateur
     */
    public static function SetShowForUser($core, $tipsId, $userId =""){
     
        if($userId == ""){
            $userId = $core->User->IdEntite;
        }
        
        $tipsUser = new TipsUser($core);
        $tipsUser->UserId->Value = $userId;
        $tipsUser->TipsId->Value = $tipsId;
        $tipsUser->Save();
    }

    /*
     * Sauvegarde le tips
     */
    public static function SaveTips($core, $data)
    { 
      $TipsForm = new TipsForm($core, $data);

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

          $TipsTips = new TipsTips($core);
          
          if($data["Id"] != ""){
            $TipsTips->GetById($data["Id"]);
          } else{
            $TipsTips->Code->Value = Format::ReplaceForUrl($data["Name"]);
            $TipsTips->DateCreated->Value = Date::Now();
            $TipsTips->Status->Value = 1;
        }
          
          $TipsForm->Populate($TipsTips);
          $TipsTips->Save();

          return $TipsForm->Success(array("Id" => $core->Db->GetInsertedId()));
      } else{
        return $TipsForm->Error();
      }
    }

    /**
     * Delete a tips
     */
    public static function DeleteTips($core, $tipsId){
        $TipsTips = new TipsTips($core);
        $TipsTips->GetById( $tipsId);
        $TipsTips->Status->Value = 99;
        $TipsTips->Save();
    }
}
