<?php
namespace WpBookingProBlock\block_top_service;
use WpBookingPro\Factory as FactoryAlias;
use WpBookingPro\Utilities\Utility as UtilityAlias;

class block_top_service_helper{
    public static function getList_service(){
        $db= FactoryAlias::getDBO();
        $query=$db->getQuery(true);
        $query->select('service.*')
            ->from(UtilityAlias::getTableName('service').' AS service ')
            ->where('service.published=1')
        ;
        $list=$db->setQuery($query)->loadObjectList();
        foreach ($list as &$item){
            $query->clear()
                ->select('review.*')
                ->from(UtilityAlias::getTableName('review').' AS review')
                ->leftJoin(UtilityAlias::getTableName('service_review').' AS service_review ON service_review.review_id=review.id')
                ->where('service_review.service_id='.(int)$item->id)
            ;
            $list_review = $db->setQuery($query)->loadObjectList();
            $arr_rating_avg = array();
            foreach ($list_review as $review) {
                $rating_ambience = isset($review->rating_ambience)?$review->rating_ambience:0;
                $rating_cleanliness = isset($review->rating_cleanliness)?$review->rating_cleanliness:0;
                $rating_staff = isset($review->rating_staff)?$review->rating_staff:0;
                $rating_value = isset($review->rating_value)?$review->rating_value:0;
                $review->avg_rating = ($rating_ambience + $rating_cleanliness + $rating_staff + $rating_value) / 4;
                array_push($arr_rating_avg,$review->avg_rating);
            }
            $item->list_review = $list_review;
            $item->rating_avg = array_sum($arr_rating_avg) / count($arr_rating_avg);
        }
       return $list;
    }
}