<?php
namespace TourOperatorProFrontend\app\models;
defined('_TOUROPERATOR_EXEC') or die;

use TourOperatorPro\Factory as FactoryAlias;
use TourOperatorPro\Mvc\Model\ModelForm;
use TourOperatorPro\Form\Form;
use TourOperatorPro\Mvc\Model\ModelList;
use TourOperatorPro\Registry\Registry;
use TourOperatorProFrontend\app\helpers\FrontendHelper;
use TourOperatorPro\Mvc\Model\Model;
use TourOperatorPro\Router\Route;


class ToursModel extends ModelList
{
    /**
     * @var string
     */
    public $context = "tours";
    /**
     * @var string
     */
    public $table_name = "tour";
    public function getListQuery()
    {
        $input=FactoryAlias::getInput();
        $data=$input->getData();
        $destination_id=$input->getInt('destination',0);
        $activity_id=$input->getInt('activity_id',0);
        $price_search=$input->getString('price_search',"");
        $rate = $input->getString('rate','');
        // list($from, $to) = explode(';', $rate);

        if($price_search!==""){
            $price_search=(array)json_decode($price_search);
        }
        $tour_type=[];
        
        if(array_key_exists('tour_type',(array)$data)) {
            $tour_type=$data['tour_type'];
            if(!empty($tour_type)){
                $tour_type=(array)$tour_type;
            }
        }
        $query=$this->db->getQuery(true);
        $query->select("a.*")
            ->from($this->getTableName("tour").' AS a')
            ->where('a.published=1')
        ;
        $query->order($this->getState('list.ordering', 'a.ordering') . ' ' . $this->getState('list.direction', 'ASC'));
        if($destination_id!=0){
            $query
                ->leftJoin($this->getTableName("tourproperty").' AS tourproperty1 ON tourproperty1.tour_id=a.id')
                ->where('tourproperty1.object_id='.(int)$destination_id)
                ->where('tourproperty1.type='.$query->quote(FrontendHelper::getTourDestinationKey()))
            ;
        }
        if($activity_id!=0){
            $query
                ->leftJoin($this->getTableName("tourproperty").' AS tourproperty3 ON tourproperty3.tour_id=a.id')
                ->where('tourproperty3.object_id='.(int)$activity_id)
                ->where('tourproperty3.type='.$query->quote(FrontendHelper::getTourActivityKey()))
            ;
        }

        // if($from!= '' && trim($from) != '' && $to!= '' && trim($to) != '') {
        //     $query->leftJoin($this->getTableName('tourproperty').' AS tourproperty4 ON tourproperty4.tour_id=a.id')
        //         ->leftJoin($this->getTableName('rate').' AS rate ON rate.id=tourproperty4.object_id')
        //         ->where('tourproperty4.type ='.$query->quote(FrontendHelper::getTourRateKey()))
        //         ->where('rate.from >='.$query->quote($from))
        //         ->where('rate.to <='.$query->quote($to))
        //     ;

        // }


        if(is_array($price_search) && !empty($price_search)){
            $min=reset($price_search);
            $max=end($price_search);

            $query->where('a.price>='.(float)$min);
            $query->where('a.price<='.(float)$max);
        }
        
        if(is_array($tour_type) && !empty($tour_type)){

            $query
                ->leftJoin($this->getTableName("tourproperty").' AS tourproperty2 ON tourproperty2.tour_id=a.id')
                ->where('tourproperty2.object_id IN ('.implode($tour_type,",").')')
                ->where('tourproperty2.type='.$query->quote(FrontendHelper::getTourTypeKey()))
            ;
        }
        $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 getMaxPrice(){
        $db=FactoryAlias::getDBO();
        $query=$this->db->getQuery(true);
        $query->select("a.*")
            ->from($this->getTableName("tour").' AS a')
            ->where('a.published=1')
        ;
        $list_tour = $db->setQuery($query)->loadObjectList();
        $price = [];
        foreach($list_tour as $tour){
            $price[]=$tour->price;
        }
        $max_price = 1000;
        if(!empty($price)){
            $max_price=max($price);
        }
        return $max_price;
    }
    public function getTotalRecord(){
        $db=FactoryAlias::getDBO();
        $query=$this->getListQuery();
        $list_tour=$db->setQuery($query)->loadObjectList();
        $TotalRecord = count($list_tour);
        return $TotalRecord;
    }
    public function getList()
    {
        $input=FactoryAlias::getInput();
        $uri = FactoryAlias::getUri();
        $data=$input->getData();
        $start=0;
        if ($_SERVER['REQUEST_METHOD'] === 'GET') {
            $start=0;
        }elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if(isset($data['start']) && $data['start'] !== ''){
                $start = (int)$data['start'];
            }
        }
        $limit=6;
        if(isset($data['limit']) && $data['limit'] !== ''){
            $limit = (int)$data['limit'];
        }
        if(isset($data['total_item']) && $data['total_item'] !== ''){
            if( !empty($data['page']) > 1 ) {
                if( intval($data['total_item']) < $limit ) {
                    $limit = intval($data['total_item']);
                }
            }
        }
        $db=FactoryAlias::getDBO();
        $query=$this->getListQuery();
        $list_tour = $db->setQuery($query,$start,$limit)->loadObjectList();

        foreach ($list_tour as &$tour){
            $query->clear()
                ->select('DISTINCT tourtype.*')
                ->from($this->getTableName('tourproperty').' AS tourproperty')
                ->leftJoin($this->getTableName('tourtype').' AS tourtype ON tourtype.id=tourproperty.object_id')
                ->where('tour_id='.(int)$tour->id)
                ->where('type='.$query->quote(FrontendHelper::getTourTypeKey()))
            ;
            $list_tour_type= $this->_db->setQuery($query)->loadObjectList();
            $tour->list_tour_type=$list_tour_type;

            $query->clear()
                ->select('DISTINCT location.*')
                ->from($this->getTableName('tourproperty').' AS tourproperty')
                ->leftJoin($this->getTableName('location').' AS location ON location.id=tourproperty.object_id')
                ->where('tour_id='.(int)$tour->id)
                ->where('type='.$query->quote(FrontendHelper::getTourDestinationKey()))
            ;
            $list_destination= $this->_db->setQuery($query)->loadObjectList();
            $tour->list_destination=$list_destination;


            $query->clear()
                ->select('DISTINCT discount.*')
                ->from($this->getTableName('tourproperty').' AS tourproperty')
                ->leftJoin($this->getTableName('discount').' AS discount ON discount.id=tourproperty.object_id')
                ->where('tour_id='.(int)$tour->id)
                ->where('type='.$query->quote(FrontendHelper::getTourDiscountKey()))
            ;
            $list_discount= $this->_db->setQuery($query)->loadObjectList();
            $tour->discount= reset($list_discount);

            $query->clear()
                ->select('wishlist.user_id')
                ->from($this->getTableName('wishlist').' AS wishlist')
                ->where('tour_id='.(int)$tour->id)
            ;
            $tour->user_wishlist = $this->_db->setQuery($query)->loadColumn();
        }
        return $list_tour;
    }
    public function get_list_tour_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_tour=$db->setQuery($query)->loadObjectList();
        foreach ($list_tour as &$tour){
            $query->clear()
                ->select('DISTINCT tourtype.*')
                ->from($this->getTableName('tourproperty').' AS tourproperty')
                ->leftJoin($this->getTableName('tourtype').' AS tourtype ON tourtype.id=tourproperty.object_id')
                ->where('tour_id='.(int)$tour->id)
                ->where('type='.$query->quote(FrontendHelper::getTourTypeKey()))
            ;
            $list_tour_type= $this->_db->setQuery($query)->loadObjectList();
            $tour->list_tour_type=$list_tour_type;

            $query->clear()
                ->select('DISTINCT location.*')
                ->from($this->getTableName('tourproperty').' AS tourproperty')
                ->leftJoin($this->getTableName('location').' AS location ON location.id=tourproperty.object_id')
                ->where('tour_id='.(int)$tour->id)
                ->where('type='.$query->quote(FrontendHelper::getTourDestinationKey()))
            ;
            $list_destination= $this->_db->setQuery($query)->loadObjectList();
            $tour->list_destination=$list_destination;


            $query->clear()
                ->select('DISTINCT discount.*')
                ->from($this->getTableName('tourproperty').' AS tourproperty')
                ->leftJoin($this->getTableName('discount').' AS discount ON discount.id=tourproperty.object_id')
                ->where('tour_id='.(int)$tour->id)
                ->where('type='.$query->quote(FrontendHelper::getTourDiscountKey()))
            ;
            $list_discount= $this->_db->setQuery($query)->loadObjectList();
            $tour->discount= reset($list_discount);

            $query->clear()
                ->select('wishlist.user_id')
                ->from($this->getTableName('wishlist').' AS wishlist')
                ->where('tour_id='.(int)$tour->id)
            ;
            $tour->user_wishlist = $this->_db->setQuery($query)->loadColumn();

            $tour->lang = reset($list_destination)->lang;
            $tour->lat = reset($list_destination)->lat;
        }

        return $list_tour;
    }

    public function getList_destination(){
        $db= FactoryAlias::getDBO();
        $query=$db->getQuery(true);
        $query->select('DISTINCT country.countryname, country.id')
            ->from($this->getTableName('country').' AS country ')
            ->leftJoin($this->getTableName('state').' AS state ON state.country_id=country.id')
            ->where('country.id=state.country_id')
            ->group('country.id')
        ;

        $list_country=$db->setQuery($query)->loadObjectList();

        foreach ($list_country as &$country) {
            $query->clear()
                ->select('location.name AS location_name, location.id AS location_id')
                ->from($this->getTableName('location').' AS location')
                ->leftJoin($this->getTableName('state'). ' AS state ON state.id=location.state_id')
                ->where('state.country_id='.(int)$country->id)
            ;
            $list_location = $db->setQuery($query)->loadObjectList();
            $country->list_location = $list_location;
        }

        return $list_country;
    }
    public function getList_tourtype(){
        $db= FactoryAlias::getDBO();
        $query=$db->getQuery(true);
        $query->select('tourtype.*')
            ->from($this->getTableName('tourtype').' AS tourtype ')
        ;

        $list_tourtype=$db->setQuery($query)->loadObjectList();
        return $list_tourtype;
    }    
    public function getListToursAjax() {
        $input = FactoryAlias::getInput();
        $data = $input->getData();
        $page_tour_detail = isset($data['page_tour_detail']) ? $data['page_tour_detail']:'';
        $modelTours = Model::getInstance('tours');
        $list_tours = $modelTours->getList();
        return $this->htmlViewListTours($list_tours,$page_tour_detail);
    }

    public function htmlViewListTours($list_tours,$page_tour_detail) {
        $input = FactoryAlias::getInput();
        $template1 = $this->template1($list_tours,$page_tour_detail);
        $template2 = $this->template2($list_tours,$page_tour_detail);
        $dataModel = array();
        $dataModel['template1'] = $template1;
        $dataModel['template2'] = $template2;
        $dataModel['total'] = $this->getTotalRecord();
        $dataModel['layout'] = $input->getString('layout', "sidebar");
        $dataModel['tab'] = $input->getString('tab', "grid");
        $total_show = $input->getInt('total_show',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_tours,$page_tour_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');
        $curent_user_id = $input->getInt('curent_user_id','');
        ob_start();
        if( !empty($list_tours) ) {
            foreach ( $list_tours as $tour) {
                $new_price = $tour ->price;
                if($tour->discount) {
                    if($tour->discount->amount > 0) {
                        $new_price = $tour->price - $tour->discount->amount;
                    } else if ($tour->discount->percent > 0) {
                        $new_price= $tour->price - ($tour->price * $tour->discount->percent) / 100 ;
                    }
                }
            ?>
            <?php if($layout =="sidebar"){ ?>
            <div class="col-sm-12 col-md-6 tour-render-item">
            <?php } elseif ($layout =="fullwidth"){ ?>
            <div class="col-sm-12 col-md-6 col-lg-4 tour-render-item">
            <?php } ?>
                <div class="block-tour-item wishlist-hover" data-tour_id=<?php echo esc_attr($tour->id) ?> data-user_id=<?php echo esc_attr($curent_user_id) ?>>
                    <div class="content-top">
                        <div class="block-img">
                            <div class="lazy" style="background-image: url(<?php echo esc_url(FactoryAlias::getRootUrlPlugin()); ?><?php echo esc_attr($tour->image); ?>)">
                                <a href="<?php echo Route::_($page_tour_detail.'?tour_id='.$tour->id); ?>"> 
                                    <div class="search-icon"></div>
                                </a>
                            </div>
                            <div class="category-name-heart">
                                <span class="heart <?php echo esc_attr(in_array($curent_user_id,$tour->user_wishlist))?'active':'' ?>">
                                    <span class="icon-heart"></span>
                                </span>
                            </div>
                        </div>
                        <?php if ($tour->discount) { ?>
                            <?php if ($tour->discount->amount > 0) { ?>>
                            <div class="box-sale"><span><?php echo esc_html($tour->discount->percent); ?>%</span><span><?php echo esc_attr__("Off", "torhub") ?></span></div>
                        <?php }
                            if ($tour->discount->percent > 0) { ?>
                            <div class="box-sale"><span><?php echo esc_html($tour->discount->percent); ?>%</span><span><?php echo esc_attr__("Off", "torhub") ?></span></div>
                        <?php } ?>
                        <?php } ?>
                    </div>
                    <div class="content-bottom">
                        <div class="duration-place-tour">
                            <p class="duration">
                                <?php
                                if (isset($tour->duration)) {
                                    echo esc_html($tour->duration) . esc_attr__( ' Days ', 'torhub' ) . esc_html((int) $tour->duration - 1) . esc_attr__( ' Nights', 'torhub' );
                                }
                                ?>
                            </p>
                            <i class="icon-fafa-map-marker-alt"></i>
                            <p class="place-tour">
                                <?php
                                if (isset(end($tour->list_destination)->name)) {
                                    echo esc_html(end($tour->list_destination)->name);
                                }
                                ?>
                            </p>
                        </div>

                        <h4 class="name-tour">
                            <a href="<?php echo Route::_($page_tour_detail.'?tour_id='.$tour->id); ?>">
                                <?php echo esc_html($tour->name); ?>
                            </a>
                        </h4>
                        <h4 class="description-tour">
                            <?php echo esc_html( wp_trim_words($tour->description, 10, '') ); ?>
                        </h4>
                        <div class="block-trip-price">
                            <?php if ($tour->discount) { ?>
                                <span class="price">Start from <?php echo esc_html((FrontendHelper::format_currency(number_format((float) $tour->price, 0)))); ?></span>
                            <?php } else { ?>
                                <span class="price">Start from <?php echo esc_html(FrontendHelper::format_currency(number_format((float) $new_price, 0))); ?></span>
                            <?php } ?>
                        </div>
                        <div class="take-this-tour">
                            <a class="nb-secondary-button" href="<?php echo Route::_($page_tour_detail.'?tour_id='.$tour->id); ?>">
                                <?php esc_html_e('Take This Tour', 'torhub'); ?>
                            </a>
                        </div>
                    </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 tours','torhub')?></span>
                        </div>
                    </div>
                </div>
            </div>
        <?php }
        return $content = ob_get_clean();
    }
    public function template2($list_tours,$page_tour_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');
        $curent_user_id = $input->getInt('curent_user_id','');
        ob_start();
        if( !empty($list_tours) ) {
            foreach ( $list_tours as $tour) {
                $new_price = $tour ->price;
                if($tour->discount) {
                    if($tour->discount->amount > 0) {
                        $new_price = $tour->price - $tour->discount->amount;
                    } else if ($tour->discount->percent > 0) {
                        $new_price= $tour->price - ($tour->price * $tour->discount->percent) / 100 ;
                    }
                }    
            ?>
            <div class="col-sm-12">
                <div class="block-tour-item block-tour-item-display-list wishlist-hover" data-tour_id=<?php echo esc_attr($tour->id) ?> data-user_id=<?php echo esc_attr($curent_user_id) ?>>
                    <div class="content-top">
                        <div class="block-img">
                            <div class="lazy" style="background-image: url(<?php echo esc_url(FactoryAlias::getRootUrlPlugin()); ?><?php echo esc_attr($tour->image); ?>);">
                                <a href="<?php echo Route::_($page_tour_detail.'?tour_id='.$tour->id); ?>"> 
                                    <div class="search-icon"></div>
                                </a>
                            </div>
                            <?php if ($tour->discount) { ?>
                                <?php if ($tour->discount->amount > 0) { ?>>
                                    <div class="box-sale"><span><?php echo esc_html($tour->discount->percent); ?>%</span><span><?php echo esc_attr__("Off", "torhub") ?></span></div>
                                <?php }
                                if ($tour->discount->percent > 0) { ?>
                                    <div class="box-sale"><span><?php echo esc_html($tour->discount->percent); ?>%</span><span><?php echo esc_attr__("Off", "torhub") ?></span></div>
                                <?php } ?>
                            <?php } ?>
                            <div class="category-name-heart">
                                <span class="heart <?php echo esc_attr(in_array($curent_user_id,$tour->user_wishlist))?'active':'' ?>">
                                    <span class="icon-heart"></span>
                                </span>
                            </div>
                        </div>            
                    </div>
                    <div class="content-bottom">
                        <div class="duration-place-tour">
                            <div class="duration-place-tour">
                                <p class="duration">
                                    <?php
                                    if (isset($tour->duration)) {
                                        echo esc_html($tour->duration) . esc_attr__( ' Days ', 'torhub' ) . esc_html((int) $tour->duration - 1) . esc_attr__( ' Nights', 'torhub' );
                                    }
                                    ?>
                                </p>
                                <i class="icon-fafa-map-marker-alt"></i>
                                <p class="place-tour">
                                    <?php
                                    if (isset(end($tour->list_destination)->name)) {
                                        echo esc_html(end($tour->list_destination)->name);
                                    }
                                    ?>
                                </p>
                            </div>
                        </div>

                        <h4 class="name-tour">
                            <a href="<?php echo Route::_($page_tour_detail.'?tour_id='.$tour->id); ?>">
                                <?php echo esc_html($tour->name); ?>
                            </a>
                        </h4>
                        <h4 class="description-tour">
                            <?php echo esc_html( wp_trim_words($tour->description, 10, '') ); ?>
                        </h4>
                        <div class="block-trip-price">
                            <?php if ($tour->discount) { ?>
                                <span class="price">Start from <?php echo esc_html((FrontendHelper::format_currency(number_format((float) $tour->price, 0)))); ?></span>
                            <?php } else { ?>
                                <span class="price">Start from <?php echo esc_html(FrontendHelper::format_currency(number_format((float) $new_price, 0))); ?></span>
                            <?php } ?>
                        </div>
                        <div class="take-this-tour">
                            <a class="nb-secondary-button" href="<?php echo Route::_($page_tour_detail.'?tour_id='.$tour->id); ?>">
                                <?php esc_html_e('Take This Tour', 'torhub'); ?>
                            </a>
                        </div>
                    </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 tours','torhub')?></span>
                        </div>
                    </div>
                </div>
            </div>
        <?php }
        return $content = ob_get_clean();
    }
}
