<?php
namespace WpBookingHotelFrontend\app\models;
defined('_WPBOOKINGHOTEL_EXEC') or die;
use WpBookingHotel\Factory as FactoryAlias;
use WpBookingHotel\Factory;
use WpBookingHotel\Mvc\Model\Model;
use WpBookingHotel\Form\Form;
use WpBookingHotel\Mvc\Model\ModelList;
use WpBookingHotel\Registry\Registry;
use WpBookingHotelFrontend\app\helpers\FrontendHelper;
use WpBookingHotel\Router\Route;
class HotelsModel extends ModelList
{
    /**
     * @var string
     */
    public $context = "hotels";
    /**
     * @var string
     */
    public $table_name = "hotel";

    public function getListQuery()
    {
        $input = Factory::getInput();
        $data = $input->getData();
        $keyword_address = isset($data['keyword_address'])?$data['keyword_address']:'';
        $check_in = isset($data['check_in'])?$data['check_in']:'';
        $check_out = isset($data['check_out'])?$data['check_out']:'';
        $number_adult = isset($data['number_adult'])?$data['number_adult']:0;
        $number_child = isset($data['number_child'])?$data['number_child']:0;
        $rating = isset($data['rating'])?$data['rating']:array();

        if(!empty($rating) && is_array($rating)) {
            if(count($rating)) {
                $rating = array_map(function ($v){
                    return json_decode($v);
                },$rating);
                $rating = call_user_func_array("array_merge",$rating);
            }
        }

        $roomtype_id=[];
        if(array_key_exists('room_type_id',(array)$data)) {
            $roomtype_id=$data['room_type_id'];
            if(!empty($roomtype_id)){
                $roomtype_id=(array)$roomtype_id;
            }
        }
        $country_id = $input->getInt('country_id',0);

        $query=$this->db->getQuery(true);
        $query->select("a.*")
            ->from($this->getTableName().' AS a')
            ->where('a.published=1')

        ;

        if($keyword_address != '' && trim($keyword_address)!='') {
            $query->leftJoin($this->getTableName('hotelproperty').' AS hotelproperty1 ON hotelproperty1.hotel_id=a.id')
                ->leftJoin($this->getTableName('location'). ' AS location ON location.id=hotelproperty1.object_id')
                ->where('hotelproperty1.type='.$query->quote(FrontendHelper::getWpBookingDestinationKey()))
                ->where('location.address LIKE '.$query->quote("%$keyword_address%"))
                ;
        }
        if($number_adult > 0) {
            $query->where('a.max_adult >='.(int)$number_adult);
        }
        if($number_child > 0) {
            $query->where('a.max_child >='.(int)$number_child);
        }
        if(!empty($roomtype_id)) {
            $query->leftJoin($this->getTableName('hotelproperty').' AS hotelproperty4 ON hotelproperty4.hotel_id=a.id')
                ->where('hotelproperty4.type='.$query->quote(FrontendHelper::getWpBookingRoomtypeKey()))
                ->where('hotelproperty4.object_id IN ('.implode(",",$roomtype_id).')')
                ;
        }
        if(!empty($rating)) {
            if( is_array($rating) ) {
                $rating = $rating;
            }elseif(is_string($rating)) {
                $arr = str_replace(']','',$rating);
                $arr = str_replace('[','',$arr);
                $rating = array_values(array_unique(explode(',', $arr)));
            }
            $query->leftJoin($this->getTableName('hotelproperty').' AS hotelproperty5 ON hotelproperty5.hotel_id=a.id')
                ->leftJoin($this->getTableName('review').' AS review ON review.id=hotelproperty5.object_id')
                ->where('hotelproperty5.type='.$query->quote(FrontendHelper::getWpBookingReviewKey()))
                ->where('review.rating >'.(int)min($rating))
                ->where('review.rating <='.(int)max($rating))
            ;
        }


        if($country_id > 0) {
            $query->leftJoin($this->getTableName('hotelproperty').' AS hotelproperty6 ON hotelproperty6.hotel_id=a.id')
                ->leftJoin($this->getTableName('location').' AS location ON location.id=hotelproperty6.object_id')
                ->leftJoin($this->getTableName('state'). ' AS state ON state.id=location.state_id')
                ->leftJoin($this->getTableName('country'). ' AS country ON country.id=state.country_id')
                ->where('hotelproperty6.type='.$query->quote(FrontendHelper::getWpBookingDestinationKey()))
                ->where('country.id='.(int)$country_id)
                ;
        }
        $query->group('a.id');

        $key_sort_by="a.ordering";
        if(isset($data['key_sort']) && trim($data['key_sort'])!==''){
            $key_sort_by=$data['key_sort'];
        }
        $direction="ASC";
        if(isset($data['direction']) && trim($data['direction'])!==''){
            $direction=$data['direction'];
        }
        $query->order("$key_sort_by $direction");

        return $query;
    }

    public function getList()
    {
        $input=Factory::getInput();
        $data=$input->getData();
        $start=0;
        if(isset($data['start']) && $data['start'] !== ''){
            $start = (int)$data['start'];
        }
        $limit=12;
        if(isset($data['limit']) && $data['limit'] !== ''){
            $limit = (int)$data['limit'];
        }
        $db=FactoryAlias::getDBO();        
        $query=$this->getListQuery();
        $list = $db->setQuery($query,$start,$limit)->loadObjectList();

        foreach ($list as &$item) {
            $query->clear()
                ->select('DISTINCT location.*')
                ->from($this->getTableName('location').' AS location')
                ->leftJoin($this->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= $this->_db->setQuery($query)->loadObject();
            $item->destination=$destination;

            $query->clear()
                ->select('DISTINCT review.*')
                ->from($this->getTableName('review').' AS review')
                ->leftJoin($this->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 = $this->_db->setQuery($query)->loadObjectList();
            $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;
            $query->clear()
                ->select('wishlist.user_id')
                ->from($this->getTableName('wishlist').' AS wishlist')
                ->where('wishlist.hotel_id='.(int)$item->id);
            $item->user_wishlist = $db->setQuery($query)->loadColumn();

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

        return $list;
    }

    public function getTotalRecord(){
        $db=FactoryAlias::getDBO();
        $query=$this->getListQuery();
        $list_service=$db->setQuery($query)->loadObjectList();
        return count($list_service);
    }

    public function getFilterFormHotel()
    {
        return self::get_filter_form_hotel();
    }

    public static function get_filter_form_hotel()
    {

        try {
            $form = Form::getInstance(WPBOOKINGHOTEL_PATH_ROOT."/frontend/app/models/forms/filter_form_hotel.xml"); //TODO: refactor late.

        } catch (\Exception $e) {
            echo ($e->getMessage());
            die;
            return false;
        }
        return $form;
    }

    public function get_list_hotel_loc()
    {
        $db=FactoryAlias::getDBO();
        $input=FactoryAlias::getInput();
        $data=$input->getData();
        $user_id = 0;
        if(!empty($data['user_id'])){
            $user_id = intval($data['user_id']);
        }
        $query=$this->getListQuery();
        $list_service=$db->setQuery($query)->loadObjectList();
        foreach ($list_service as &$item) {
            $query = $this->db->getQuery(true);
            $query->clear()
                ->select('DISTINCT location.*')
                ->from($this->getTableName('location').' AS location')
                ->leftJoin($this->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= $this->_db->setQuery($query)->loadObject();
            $item->destination=$destination; 
            $query->clear()
                ->select('wishlist.user_id')
                ->from($this->getTableName('wishlist') . ' AS wishlist')
                ->where('wishlist.hotel_id=' . (int)$item->id)
            ;
            $user_wishlist = $this->db->setQuery($query)->loadColumn();
            $item->user_wishlist = $user_wishlist;
            // $checkWishlist = false;
            // if(in_array($user_id,$item->user_wishlist)){
            //     $checkWishlist = true;
            // }
            $query->clear()
                ->select('DISTINCT review.*')
                ->from($this->getTableName('review').' AS review')
                ->leftJoin($this->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 = $this->_db->setQuery($query)->loadObjectList();
            $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;

            $item->lang = $item->destination->lang;
            $item->lat = $item->destination->lat;
        }

        return $list_service;
    }

    public function getListHotelsAjax() {
        $input = Factory::getInput();
        $data = $input->getData();
        $page_hotel_detail = isset($data['page_hotel_detail']) ? $data['page_hotel_detail'] : "";
        $modelHotels = Model::getInstance('hotels');
        $list_hotels = $modelHotels->getList();
        return $this->htmlViewListHotels($list_hotels,$page_hotel_detail);
    }

    public function htmlViewListHotels($list_hotels,$page_hotel_detail) {
        $input = FactoryAlias::getInput();
        $template1 = $this->template1($list_hotels,$page_hotel_detail);
        $template2 = $this->template2($list_hotels,$page_hotel_detail);
        $dataModel = array();
        $dataModel['template1'] = $template1;
        $dataModel['layoutlist'] = $input->getString('layout', "sidebar");
        $dataModel['template2'] = $template2;
        $dataModel['layout'] = $input->getString('tab', "grid");
        $total_show = $input->getInt('limit1',12);
        if( $total_show <  $this->getTotalRecord()) {
            $dataModel['total_show'] = $total_show;
        }else {
            $dataModel['total_show'] = $this->getTotalRecord();
        }
        $dataModel['total'] = $this->getTotalRecord();

        return $dataModel;
    }

    public function template1($list_hotels,$page_hotel_detail='') {
        $input = FactoryAlias::getInput();
        $layout = $input ->getString('layout', "sidebar");
        $tab = $input->getString('tab', "grid");
        $sort = $input->getString('key_sort', 'a.ordering');
        $direction = $input->getString('direction', 'ASC');
        $tab = $input->getString('tab', 'ASC');
        $user_id = $input->getInt('user_id','');
        ob_start();
        if( !empty($list_hotels) ) {
            foreach ( $list_hotels as $hotel) {?>
                <?php
                $list_review = isset($hotel->list_review)?$hotel->list_review:array();
                if(!empty($list_review)) {
                    $rating_sum = 0;
                    foreach ($list_review as $review) {
                        if(isset($review->rating)) {
                            $rating_sum += $review->rating;
                        }
                    }
                    $max_star = 5;
                    $hotel_rating=$rating_sum / count($list_review);
                    while ($hotel_rating > $max_star) {
                        $hotel_rating = $hotel_rating - $max_star;
                    }
    
                    $star = $hotel_rating % 10;
                    $non_star = ($max_star - $hotel_rating) % 10;
                    $half_star = ceil($max_star-$star-$non_star);
                }?>
                <?php if($layout =="sidebar"){ ?>
                <div class="col-sm-6 col-xl-4 hotel-render-item wishlist-item" data-hotel_id= "<?php echo esc_attr($hotel->id) ?>" data-user_id= "<?php echo esc_attr( $user_id ) ?>" >
                <?php } elseif($layout =="fullwidth") { ?>
                <div class="col-xs-12 col-sm-6 col-md-4 col-lg-3 hotel-render-item wishlist-item" data-hotel_id= "<?php echo esc_attr($hotel->id) ?>" data-user_id= "<?php echo esc_attr( $user_id ) ?>" >
                <?php } ?>
                    <div class="box-hotel row-1 box-1">
                            <div class="img-block">
                                <a href="<?php echo esc_url(Route::_($page_hotel_detail.'?hotel_id='.$hotel->id,0)); ?>" style="display: block">
                                <div class=" wishlist-hover">
                                    <img src="<?php echo(Factory::getRootUrlPlugin())?><?php echo (isset($hotel->image)?$hotel->image:'');?>"
                                        alt="<?php echo (isset($hotel->name)?$hotel->name:'');?>">
                                </div>
                                </a>

                                <div class="category-name-heart">
                                    <span class="heart <?php echo in_array($user_id,$hotel->user_wishlist) ? 'active':'' ?> ">
                                        <i class="fas fa-heart"></i>
                                    </span>
                                </div>
                            </div>
                            <div class="block-content">
                                <div class="block-rating">
                                    <ul class="list-rating-star">
                                        <?php if(!empty($list_review)) {?>
                                            <?php for ($i=0; $i <$star; $i++) {?>
                                                <li class="item-star"><i class="fas fa-star"></i></li>
                                            <?php }?>
                                            <?php for ($i=0; $i <$half_star; $i++) {?>
                                                <li class="item-star"><i class="fas fa-star-half-alt"></i></li>
                                            <?php }?>
                                            <?php for ($i=0; $i <$non_star; $i++) {?>
                                                <li class="item-star"><i class="far fa-star"></i></li>
                                            <?php }?>
                                        <?php } else {?>
                                            <?php for($i = 1; $i <= 5; $i++) {?>
                                                <li class="item-star"><i class="far fa-star"></i></li>
                                            <?php }?>
                                        <?php }?>
                                    </ul>
                                    <div class="rating-review">
                                        <span><?php echo (esc_html(count($list_review)));?></span>
                                        <span><?php esc_html_e('Reviews','wpbookinghotel');?></span>
                                    </div>
                                </div>
                                <div class="name-hotel text-1">
                                    <a href="<?php echo esc_url(Route::_($page_hotel_detail.'?hotel_id='.$hotel->id,0)); ?>" style="display: block">
                                    <h4 title="<?php echo (isset($hotel->name)?$hotel->name:'');?>"><?php echo (isset($hotel->name)?$hotel->name:'');?></h4>
                                    </a>
                                </div>
                                <div class="address-hotel text-1">
                                    <i class="fas fa-map-marker-alt"></i>
                                    <span title="<?php echo (isset($hotel->destination)?$hotel->destination->address:'');?>">
                                        <?php echo (isset($hotel->destination)?$hotel->destination->address:'');?>
                                    </span>
                                </div>
                            </div>
                        <div class="price">
                            <span><?php echo(FrontendHelper::format_currency(isset($hotel->price)?$hotel->price:0))?></span>
                            <span><?php esc_html_e('Night','wpbookinghotel');?></span>
                        </div>
                    </div>
                </div>
            <?php }
        }else {?>
            <div class="container">
                <div class="row">
                    <div class="col-md-12">
                        <div class="alert-block">
                            <span><?php esc_attr_e('Could not found any hotels','hotelier')?></span>
                        </div>
                    </div>
                </div>
            </div>
        <?php }
        
        return $content = ob_get_clean();
    }

    public function template2($list_hotels,$page_hotel_detail='') {
        $input = FactoryAlias::getInput();
        $tab = $input->getString('tab', "grid");
        $sort = $input->getString('key_sort', 'a.ordering');
        $direction = $input->getString('direction', 'ASC');
        $tab = $input->getString('tab', 'ASC');
        $user_id = $input->getInt('user_id','');
        ob_start();
        if(!empty($list_hotels)) {
            foreach ( $list_hotels as $hotel) {?>
                <?php
                $list_review = isset($hotel->list_review)?$hotel->list_review:array();
                if(!empty($list_review)) {
                    $rating_sum = 0;
                    foreach ($list_review as $review) {
                        if(isset($review->rating)) {
                            $rating_sum += $review->rating;
                        }
                    }
                    $max_star = 5;
                    $hotel_rating=$rating_sum / count($list_review);
                    while ($hotel_rating > $max_star) {
                        $hotel_rating = $hotel_rating - $max_star;
                    }
    
                    $star = $hotel_rating % 10;
                    $non_star = ($max_star - $hotel_rating) % 10;
                    $half_star = ceil($max_star-$star-$non_star);
                }?>
                <div class="hotel-render-item hotel-render-item wishlist-item" data-hotel_id= "<?php echo esc_attr($hotel->id) ?>" data-user_id= "<?php echo esc_attr( $user_id ) ?>" >
                    <div class="list-hotel list-1">
                        <a href="<?php echo esc_url(Route::_($page_hotel_detail.'?hotel_id='.$hotel->id,0)); ?>" style="display: block">
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="block-content-left">
                                        <div class="img-block">
                                            <div class="wishlist-hover">
                                                <img src="<?php echo(Factory::getRootUrlPlugin())?><?php echo (isset($hotel->image)?$hotel->image:'');?>"
                                                     alt="<?php echo (isset($hotel->name)?$hotel->name:'');?>">
                                            </div>
                                            <div class="category-name-heart">
                                                <span class="heart <?php echo in_array($user_id,$hotel->user_wishlist) ? 'active':'' ?> ">
                                                    <i class="fas fa-heart"></i>
                                                </span>
                                            </div>
                                        </div>
                                        <div class="price">
                                            <span><?php echo(FrontendHelper::format_currency(isset($hotel->price)?$hotel->price:0))?></span>
                                            <span><?php esc_html_e('Night','wpbookinghotel');?></span>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-8">
                                    <div class="content-description">
                                        <div class="block-rating">
                                            <ul class="list-rating-star">
                                                <?php if(!empty($list_review)) {?>
                                                    <?php for ($i=0; $i <$star; $i++) {?>
                                                        <li class="item-star"><i class="fas fa-star"></i></li>
                                                    <?php }?>
                                                    <?php for ($i=0; $i <$half_star; $i++) {?>
                                                        <li class="item-star"><i class="fas fa-star-half-alt"></i></li>
                                                    <?php }?>
                                                    <?php for ($i=0; $i <$non_star; $i++) {?>
                                                        <li class="item-star"><i class="far fa-star"></i></li>
                                                    <?php }?>
                                                <?php } else {?>
                                                    <?php for($i = 1; $i <= 5; $i++) {?>
                                                        <li class="item-star"><i class="far fa-star"></i></li>
                                                    <?php }?>
                                                <?php }?>
                                            </ul>
                                            <div class="rating-review">
                                                <span><?php esc_html_e(count($list_review));?></span>
                                                <span><?php esc_attr_e('Reviews','wpbookinghotel');?></span>
                                            </div>
                                        </div>
                                        <div class="name-hotel text-1">
                                            <h4><?php echo (isset($hotel->name)?$hotel->name:'');?></h4>
                                        </div>
                                        <div class="address-hotel text-1">
                                            <i class="fas fa-map-marker-alt"></i>
                                            <span title="<?php echo (isset($hotel->destination)?$hotel->destination->address:'');?>">
                                                <?php echo (isset($hotel->destination)?$hotel->destination->address:'');?>
                                            </span>
                                        </div>
                                        <div class="description text-1">
                                            <?php echo wp_strip_all_tags(isset($hotel->description)?$hotel->description:'');?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </a>
                    </div>
                </div>
            <?php }
        } else { ?>
            <div class="row">
                <div class="col-md-12">
                    <div class="alert-block">
                        <span><?php esc_attr_e('Could not found any hotels','hotelier')?></span>
                    </div>
                </div>
            </div>
        <?php }
        
        return $content = ob_get_clean();
    }
}
