<?php
namespace WpBookingHotelBlock\block_popular_hotel;
use WpBookingHotel\Factory as FactoryAlias;
use WpBookingHotel\Factory;
use WpBookingHotel\Mvc\Model\ModelList;
use WpBookingHotel\Registry\Registry;
use WpBookingHotel\Utilities\Utility as UtilityAlias;
use WpBookingHotelFrontend\app\helpers\FrontendHelper;

class block_popular_hotel_helper {
    public static function getListPopularHotel($limit){
        $db=Factory::getDBO();
        $query=$db->getQuery(true);
        $query->select('hotel.*')
            ->from(UtilityAlias::getTableName('hotel').' AS hotel')
            ->where('hotel.published=1')
            ->where('hotel.is_popular_hotel=1')
            ;
        
        $list = $db->setQuery($query,0,$limit)->loadObjectList();

        foreach ($list as &$item) {
            $query->clear()
                ->select('DISTINCT location.*')
                ->from(UtilityAlias::getTableName('location').' AS location')
                ->leftJoin(UtilityAlias::getTableName('hotelproperty').' AS hotelproperty ON hotelproperty.object_id=location.id')
                ->where('hotelproperty.hotel_id='.(int)$item->id)
                ->where('hotelproperty.type='.$query->quote(FrontendHelper::getWpBookingDestinationKey()))
            ;
            $destination= $db->setQuery($query, 0, 6)->loadObject();
            $item->destination=$destination;

            $query->clear()
                ->select('DISTINCT review.*')
                ->from(UtilityAlias::getTableName('review').' AS review')
                ->leftJoin(UtilityAlias::getTableName('hotelproperty').' AS hotelproperty ON hotelproperty.object_id=review.id')
                ->where('hotelproperty.hotel_id='.(int)$item->id)
                ->where('hotelproperty.type='.$query->quote(FrontendHelper::getWpBookingReviewKey()))
            ;
            $list_review = $db->setQuery($query)->loadObjectList();
            $query->clear()
            ->select('wishlist.user_id')
            ->from(UtilityAlias::getTableName('wishlist').' AS wishlist')
            ->where('wishlist.hotel_id='.(int)$item->id);
            $item->user_wishlist = $db->setQuery($query)->loadColumn();

            $rating_sum = 0;
            foreach ($list_review as $review) {
                if(isset($review->rating)) {
                    $rating_sum += $review->rating;
                }
            }
            $item->list_review = $list_review;
            $item->rating_avg = !empty($list_review)?($rating_sum/count($list_review)):0;

            $register = new Registry();
            $register->loadString($item->params);
            $item->params = $register;
        }

        return $list;
    }
}