<?php

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

namespace Apps\Annonce;

use Core\Core\Core;
use Core\Core\Request;
use Core\Core\Response;
use Apps\Base\Base;

use Apps\Annonce\Helper\SitemapHelper;
use Apps\Annonce\Module\Admin\AdminController;
use Apps\Annonce\Module\Front\FrontController;
use Apps\Annonce\Module\Member\MemberController;
use Apps\Annonce\Module\Api\ApiController;
use Apps\Annonce\Helper\AnnonceHelper;
use Apps\Annonce\Helper\ApiHelper;
use Apps\Annonce\Helper\NotifyHelper;


class Annonce extends Base {

    /**
     * Author and version
     * */
    public $Author = 'Webemyos';
    public $Version = '1.0.6.0';

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

    /**
     * Set public route
     */
    function GetRoute($routes = "") {
        $this->Route->SetPublic(array("Search", "ShowActionUser",
                                      "annonces/category/" => "Category",
                                      "annonces/" => "Annonce",
                    ));

        return $this->Route;        
    }

    /*     * *
     * Execute action after install
     */

    function PostInstall() {
        \Apps\EeApp\Helper\AppHelper::UpdateAppParams($this->Core,
                "Annonce",
                $this->Version,
                "Classified ads platform ", // Add Description of the app
                1, // Set 1 if the App have a AdminWidgetDashBoard
                1  // Set 1 if the App have a Member Module
        );

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

    /**
     * Start Admin
     */
    function Run() {
        echo parent::RunApp($this->Core, "Annonce", "Annonce");
    }

    /**
     * Save a catégorie
     */
    function SaveCategory() {
        $adminController = new AdminController($this->Core);

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

    /*     * *
     * Delete a category
     */

    function DeleteCategory() {
        $adminController = new AdminController($this->Core);

        if ($adminController->DeleteCategory(Request::GetPost("categoryId"))) {
            return Response::Success($adminController->GetTabCategory());
        } else {
            return Response::Error();
        }
    }

    /*     * *
     * Annoncein admin 
     */

    function SaveAdminAnnonce() {
        $adminController = new AdminController($this->Core);

        if ($adminController->SaveAdminAnnonce(Request::GetPosts())) {
            return Response::Success($adminController->GetTabAnnonce());
        } else {
            return Response::Error();
        }
    }

    /*     * *
     * Delete Annonce 
     */

    function DeleteAnnonce() {
        $adminController = new AdminController($this->Core);

        if ($adminController->DeleteAnnonce(Request::GetPost("annonceId"))) {
            return Response::Success($adminController->GetTabAnnonce());
        } else {
            return Response::Error();
        }
    }
    
    function RefreshPlugin(){
        $adminController = new AdminController($this->Core);
        return $adminController->GetTabExtension();
    }
    
    /**
     * Save image tmp
     */
    function DoUploadFile($idElement, $tmpFileName, $fileName, $action) {
        $directory = "Data/Tmp";

        move_uploaded_file($tmpFileName, $directory . "/" . $idElement . ".jpg");

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

    //Front page
    function Index() {
        $this->Core->MasterView->Set("Title", "Annonces");

        $frontController = new FrontController($this->Core);
        return $frontController->Index();
    }

    /*     * *
     * Display one category and this annonces
     */

    function Category($codeCategory) {
        $frontController = new FrontController($this->Core);
        return $frontController->Category($codeCategory);
    }

    /*     * *
     * Save the annonce
     */

    function SaveAnnonce() {
        $frontController = new FrontController($this->Core);

        if ($frontController->SaveAnnonce(Request::GetPosts())) {
            return Response::Success(array());
        } else {
            return Response::Error();
        }
    }

    /***
     * Update annonce
     */
    function UpdateAnnonce(){
        $memberController = new MemberController($this->Core);

        if ($memberController->UpdateAnnonce(Request::GetPosts())) {
            return Response::Success(array());
        } else {
            return Response::Error();
        }
    }

    /**
     * Display a annonce
     */
    function Annonce($codeAnnonce) {
        
        if($codeAnnonce == ""){
            
            $frontController = new FrontController($this->Core);
            return $frontController->Index();
            
        } else{
        
            $frontController = new FrontController($this->Core);
            return $frontController->Annonce($codeAnnonce);
        }
    }

    /*     * *
     * Add Response to a annonce
     */

    function AddResponse() {
        $frontController = new FrontController($this->Core);

        if ($frontController->AddResponse(Request::GetPosts())) {
            return Response::Success($this->Core->GetCode("Annonce.YourReponseHasBeenSend"));
        } else {
            return Response::Error();
        }
    }
    
    /*     * *
     * Run member Controller
     * 
     */

    function RunMember($data ="") {
        $memberController = new MemberController($this->Core);
        
        if($data != ""){
           return  $memberController->$data();
        } else{
           return $memberController->Index();
        }
    }

    /**
     * Get The siteMap 
     */
     public function GetSiteMap($returnUrl = false){
        return SitemapHelper::GetSiteMap($this->Core, $returnUrl);
     } 

    /*     * *
     * Get the widget
     */
    public function GetWidget($type = "", $params = "") {

        switch ($type) {
            case "AdminDashboard" :
                $widget = new \Apps\Annonce\Widget\AdminDashBoard\AdminDashBoard($this->Core);
                break;
            case "ListAnnonce" : 
                $widget = new \Apps\Annonce\Widget\ListAnnonce\ListAnnonce($this->Core);
                break;    
        }

        return $widget->Render();
    }

    /*     * *
     * Get Forum Addable widget
     */
     public function GetListWidget(){
      return array(array("Name" => "ListAnnonce",
         "Description" => $this->Core->GetCode("Annonce.DescriptionListAnnonce")),
      );
      } 

      /***
       * Search Annonce with Filter
       */
      public function Search(){

        $annonces =  AnnonceHelper::Search($this->Core, Request::GetPosts());

         //State de recherche
        $stateApp = \Core\Dashboard\DashBoardManager::GetApp("Stat", $this->Core);

        if ($stateApp) {
            $stateApp->AddStat("Annonce.Search", "Front", json_encode(["search" => Request::GetPosts(),
                "result" => $result]));
        }
        
        
        return Response::Success(["Annonces" => $annonces]);
      }

      
    /***
     * Get list of Email can be user ine Newsletter
     */
    public function GetListEmail(){
        return array("NewAnnonce", "NewResponseAnnonce");
    }
    
     /***
     * Get list of Event can be used in WorkFlow
     */
    public function GetListEvent(){

        return array(array("Name" => "NewAnnonce",
          "Description" => $this->Core->GetCode("Annonce.NewAnnonceEventDescription")),
        );
    }

    /***
     * Detail d'une notification
     */
    public function GetDetailNotify($notify){
       return NotifyHelper::GetDetailNotify($this->Core, $notify);
    }
    
    
     /********************* API *************************************/
    
    /***
     * Obtient les catégories et avec leur dérniers messages
     */
    public function GetCategories(){
        $apiController = new ApiController($this->Core);
        return Response::Success($apiController->GetCategories());
    }
    
    /***
     * Obtient la catégorie et tous les messages
     */
    public function GetCategorie(){
        $apiController = new ApiController($this->Core);
        return Response::Success($apiController->GetCategorie(Request::GetPost("categoryId")));
    }
    
    /***
     * Obtient un message et ses réponses
     */
    public function GetAnnonce(){
        $apiController = new ApiController($this->Core);
        return Response::Success($apiController->GetAnnonce(Request::GetPost("annonceId")));
    }
    
    /***
     * List des annonce disponibles avec les filtres
     */
    public function GetListAnnonce(){
        $apiController = new ApiController($this->Core);
        return Response::Success($apiController->GetListAnnonce());
    }

    /***
     * Obtient tles filtres disponibles
     */
    public function GetFilters(){
        $apiController = new ApiController($this->Core);
        return Response::Success($apiController->GetFilters());
    }
    
    /***
     * Créer une alerte
     */
    public function CreateAlert(){
        $apiController = new ApiController($this->Core);
        return Response::Success($apiController->CreateAlert(Request::GetPosts()));
    }
    
    /***
     * De
     */
    public function RemoveAlert(){
        $alert = new \Plugins\AlertPlugin\Entity\AlertPluginAlert($this->Core);
        $alert->GetById(Request::GetPost("alertId"));
        $alert->Delete();
        return Response::Success([]);
    }
  
    
    
    
    /***
     * Formulaire de tracking
     */
    public function GetTrackingForm(){
        $apiController = new ApiController($this->Core);
        return Response::Success($apiController->GetTrackingForm(Request::GetPosts()));
    }
    
    /****
     * Message sur une annonce
     */
    public function SendContactForm(){
        $apiController = new ApiController($this->Core);
        return Response::Success($apiController->SendContactForm(Request::GetPosts()));
    }
    
}
