<?php

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

namespace Apps\Annonce\Helper;

use Apps\Annonce\Entity\AnnonceAnnonce;
use Apps\Annonce\Entity\AnnonceResponse;
use Core\Utility\Format\Format;

class AnnonceHelper {
    /*     * *
     * Get Annonce in Status 2 for a category
     */

    public static function GetPublishedByCategory($core, $categoryId) {

        $annonce = new AnnonceAnnonce($core);
        return $annonce->Find("CategoryId= " . $categoryId . " and Status = 2");
    }

    /*     * *
     * Get Annonce of a user
     */

    public static function GetByUser($core, $userId) {
        $annonce = new AnnonceAnnonce($core);
        return $annonce->Find("UserId= " . $userId . " and Status <> 99 order by id desc");
    }

    /*     * *
     * Get All Response af annonce
     */

    public static function GetResponses($core, $annonceId) {

        $response = new AnnonceResponse($core);
        return $response->Find("AnnonceId=" . $annonceId);
    }

    /*     * *
     * Search Annonce
     */

    public static function Search($core, $filters) {

        $annonce = new AnnonceAnnonce($core);
        $filtType = [];

        foreach ($filters as $key => $filter) {

            if (is_int($key) && $filter != "") {
                $request = "select * from Caracteristic where CategoryId= $key and Id = $filter;";
                $result = $core->Db->GetArray($request);

                if (count($result) > 0) {
                    $filtType[] = $filter;
                }
            }
        }

        if(count($filtType) > 0 ){
        $Request = "
            
        SELECT ce.EntityId as id
        FROM CaracteristicEntity ce
        WHERE ce.CaracteristicId IN (" . implode(",", $filtType) . ")
        GROUP BY ce.EntityId
        HAVING COUNT(DISTINCT ce.Id) = " . count($filtType);

        $result = $core->Db->GetArray($Request);
        $annoceId = [];

        if (count($result) == 0) {
            return false;
        }

        foreach ($result as $r) {
            $annoceId[] = $r["id"];
        }
      
        $annonces = $annonce->Find("id in (" . implode(",", $annoceId) . ")");

        } 
        else {
                $annonces = $annonce->Find("1 = 1");
        }
       
        $annonceArray = $annonce->ToAllArray($annonces);

        foreach ($annonceArray as &$annonce) {
            $annonce["UrlPath"] = $core->GetPath("/Annonce/Annonce/" . $annonce["Code"]);
            $annonce["ShortDescription"] = Format::Tronquer($annonce["Description"], 400);
        }

        return $annonceArray;
    }
}
