<?php
namespace WpBookingProFrontend\app\models;
defined('_WPBOOKINGPRO_EXEC') or die;

use Exception;
use WpBookingPro\Factory;
use WpBookingPro\Language\Text;
use WpBookingPro\Mvc\Model\ModelForm;
use WpBookingPro\Filesystem\File as FileAlias;
use WpBookingPro\Mvc\Model\Model;
use WpBookingPro\Form\Form;
use WpBookingPro\Mvc\Model\ModelList;
use WpBookingPro\Registry\Registry;
use WpBookingPro\Router\Route;
use WpBookingPro\Utilities\Utility;
use WpBookingProAdmin\app\helpers\AdminHelper;
use WpBookingProFrontend\app\helpers\FrontendHelper;
use WpBookingProFrontend\app\Html\HtmlFrontend;

class CategoryModel extends ModelForm
{
    /**
     * @var string
     */
    public $context = "category";
    /**
     * @var string
     */
    public $table_name = "category";

    public function queryFilterServiceAjax() {
        $input = Factory::getInput();
        $category_id = $input->getInt('category_id',  0);
        $price_search = $input->getString('price_search', '');
        $keyword = $input->getString('keyword', '');
        $sort = $input->getString('sort','service.ordering');
        $direction = $input->getString('direction','');
        if($price_search!== ''){
            $price_search=(array)json_decode($price_search);
        }
        $db = Factory::getDBO();
        $query = $db->getQuery(true);
        $query->clear()
            ->select('service.*')
            ->from($this->getTableName('service').' AS service')
            ->where('service.category_id='.(int)$category_id)
        ;
        if($price_search !== '' && is_array($price_search) && !empty($price_search)) {
            $query->where('service.price >='.(float)min($price_search))
                ->where('service.price <='.(float)max($price_search));
        }
        if(trim($keyword) != '') {
            $query->where('service.name LIKE '.$query->quote("%$keyword%"))
            ;
        }
        $query->order("$sort $direction");
        return $query;
    }

    public function getServiceByCategoryId() {
        $input = Factory::getInput();
        $limit = $input->getInt('limit',  0);
        $start = $input->getInt('start',  0);
        $total_result = $input->getInt('total_result',  0);
        $db = Factory::getDBO();
        $query = $this->queryFilterServiceAjax();
        $list_service = $db->setQuery($query, $start* $limit, (($total_result - $start * $limit) > $limit)?$limit: ($total_result - $start * $limit))->loadObjectList();
        foreach ($list_service as $key => &$item) {
            $query = $this->db->getQuery(true);
            $query->clear()
                ->select('category.*')
                ->from($this->getTableName('category') . ' AS category')
                ->where('category.id=' . (int)$item->category_id);
            $item->category = $this->db->setQuery($query)->loadObject();
            $query->clear()
                ->select('employee.*')
                ->from($this->getTableName('employee') . ' AS employee')
                ->leftJoin($this->getTableName('service_employee') . ' AS service_employee ON service_employee.employee_id=employee.id')
                ->where('service_employee.service_id=' . (int)$item->id);
            $list_employee = $this->db->setQuery($query)->loadObjectList();
            $list_employee_id = [];
            foreach ($list_employee as $employee) {
                $employee->full_name = $employee->first_name. ' ' .$employee->last_name;
                array_push($list_employee_id, $employee->id);
            }
            $item->list_employee = $list_employee;
            $item->list_employee_id = $list_employee_id;
            $query->clear()
                ->select('location.*')
                ->from($this->getTableName('location') . ' AS location')
                ->where('location.id=' . (int)$item->location_id)
            ;
            $location = $this->db->setQuery($query)->loadObjectList();
            $item->location = reset($location);

            $query->clear()
                ->select('review.*')
                ->from($this->getTableName('review').' AS review')
                ->leftJoin($this->getTableName('service_review').' AS service_review ON service_review.review_id=review.id')
                ->where('service_review.service_id='.(int)$item->id)
            ;
            $list_review = $this->_db->setQuery($query)->loadObjectList();

            $user_id = isset($_SESSION['user_id']) ? sanitize_text_field($_SESSION['user_id']) : '';
            $query->clear()
                ->select('wishlist.id')
                ->from($this->getTableName('wishlist').' AS wishlist')
                ->where('wishlist.service_id='.(int)$item->id)
                ->where('wishlist.user_id='.(int)$user_id)
            ;
            $wishlist = $this->_db->setQuery($query)->loadResult();
            $item->wishlist = $wishlist;


            $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;
            if(!empty($arr_rating_avg)) {
                $item->rating_avg = array_sum($arr_rating_avg) / count($arr_rating_avg);
            }else {
                $item->rating_avg = 0;
            }
            if(!empty($rating)) {
                if($item->rating_avg < min($rating) || $item->rating_avg > max($rating)) {
                    unset($list_service[$key]);
                }
            }



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


        }

        return $list_service;
    }

    public function getTotalServiceNotPagination() {
        $db = Factory::getDBO();
        $query = $this->queryFilterServiceAjax();
        $list_service = $db->setQuery($query)->loadObjectList();
        return count($list_service);
    }

    public function renderServiceHtmlAjax() {
        $result = array();
        if(!function_exists('wp_get_current_user')) {
            include(ABSPATH . "wp-includes/pluggable.php");
        }
        $input = Factory::getInput();
        $category_id = $input->getInt('category_id', 0);
        $page_service_detail = $input->getString('page_service_detail', 0);
        $list_service = $this->getServiceByCategoryId($category_id);
        $user_id_login = isset($_SESSION['user_id']) ? sanitize_text_field($_SESSION['user_id']) : '';
        $check_user_demo = FrontendHelper::checkUserDemo();
        $uploads = wp_upload_dir();

        ob_start();
        if(is_array($list_service) && !empty($list_service)) {
            foreach ($list_service as $service) {
                $rating_avg = $service->rating_avg;
                $list_star_sum = HtmlFrontend::get_rating_star($rating_avg);
                $list_review = isset($service->list_review)?$service->list_review:array();
                $near_me = 0;
                $unit_for_search= '';
                $check_image_size = FrontendHelper::checkImageData($uploads['baseurl'], $service->image);
                ?>
                <div class="col-sm-6 col-md-4 col-lg-3">
                    <div class="block-service-item" data-service_id="<?php echo (esc_attr(isset($service->id)?$service->id:''))?>">
                        <div class="content-top">
                            <a href="<?php echo (esc_url(Route::_($page_service_detail.'?service_id='.$service->id)))?>">
                                <div class="block-img">
                                    <div>
                                        <?php if($check_user_demo['is_demo']) {?>
                                            <?php if ($check_image_size) {?>
                                                <img src="<?php echo (esc_url(isset($service->image)? $uploads['baseurl'].'/'.$service->image:Factory::getRootUrlPlugin().'frontend/app/assets/images/no-image.jpg')) ?>" alt="service-image">
                                            <?php } else {?>
                                                <img src="<?php echo (esc_url(isset($service->image)? Factory::getRootUrlPlugin().$service->image:Factory::getRootUrlPlugin().'frontend/app/assets/images/no-image.jpg')) ?>" alt="service-image">
                                            <?php } ?>
                                        <?php } else {?>
                                            <img src="<?php echo (esc_url(isset($service->image)?Factory::getRootUrlPlugin().$service->image:Factory::getRootUrlPlugin().'frontend/app/assets/images/no-image.jpg')) ?>" alt="service-image">
                                        <?php } ?>
                                    </div>
                                </div>
                            </a>
                            <div class="block-feature">
                                <div class="label-feature <?php echo (esc_attr(isset($service->is_feature) && $service->is_feature==1 ? 'visible':''));?>">
                                    <span><?php esc_attr_e('Featured','wpbookingpro');?></span>
                                </div>
                                <?php if($user_id_login!='') {?>
                                    <i class="fas fa-heart <?php echo (esc_attr(isset($service->wishlist)? 'active':'')) ?>"></i>
                                <?php }?>
                            </div>
                        </div>
                        <div class="content-bottom">
                            <p class="place-service" title="<?php echo (isset($service->location->address)?$service->location->address:'')?>">
                                <i class="icon-nb-pin"></i>
                                <?php echo (isset($service->location->address)?$service->location->address:'')?>
                            </p>
                            <a href="<?php echo (esc_url(Route::_($page_service_detail.'?service_id='.$service->id)))?>">
                                <h4 class="name-service" title="<?php echo (esc_html(isset($service->name)?$service->name:''))?>">
                                    <?php echo (esc_html(isset($service->name)?$service->name:''))?>
                                </h4>
                            </a>
                            <div class="block-rating">
                                <ul class="list-rating-star">
                                    <?php if($rating_avg > 0) {?>
                                        <?php for ($i=0; $i < $list_star_sum[0]; $i++) {?>
                                            <li class="item-star"><i class="fas fa-star"></i></li>
                                        <?php }?>
                                        <?php for ($i=0; $i <$list_star_sum[1]; $i++) {?>
                                            <li class="item-star"><i class="fas fa-star-half-alt"></i></li>
                                        <?php }?>
                                        <?php for ($i=0; $i <$list_star_sum[2]; $i++) {?>
                                            <li class="item-star"><i class="far fa-star"></i></li>
                                        <?php }?>
                                    <?php } else {?>
                                        <?php for ($i=0; $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)))?> <?php esc_attr_e('Reviews','wpbookingpro');?></span>
                                </div>
                            </div>
                            <div class="block-trip-price">
                                <div class="time-trip">
                                    <i class="icon-nb-clock"></i>
                                    <span><?php echo (esc_html(isset($service->duration)?$service->duration:0))?> <?php esc_attr_e('hours','wpbookingpro');?></span>
                                </div>
                                <div class="price-service">
                                    <span><i class="fas fa-bolt"></i><span><?php esc_attr_e('From','wpbookingpro');?></span></span>
                                    <span class="price"><?php echo (esc_html(HtmlFrontend::render_price(isset($service->price)?$service->price:0)))?></span>
                                </div>
                            </div>
                            <?php if($near_me == 1) {?>
                                <div class="distance-between-your-location">
                                    <i class="fas fa-map-pin"></i>
                                    <span>
                                        <?php echo (esc_html(isset($service->distance)?$service->distance:0))?>
                                        <?php
                                        if($unit_for_search == 'Km') {
                                            echo (esc_html('Km'));
                                        } elseif ($unit_for_search='Mi') {
                                            echo (esc_html('Mile'));
                                        }
                                        ?>
                                    </span>
                                </div>
                            <?php }?>
                        </div>
                    </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 services','wpbookingpro')?></span>
                    </div>
                </div>
            </div>
            <?php
        }

        $content = ob_get_clean();
        $result['total_service'] = $this->getTotalServiceNotPagination();
        $result['html'] = $content;
        return $result;
    }

    public function save($data = array())
    {

        $item= parent::save($data); // TODO: Change the autogenerated stub
        $image=Factory::getInput()->files->get('image','','raw');
        $check_user_demo = FrontendHelper::checkUserDemo();
        if(!empty($image['name'])) {
            $name = str_replace(' ', '_',Utility::gen_random_string()) . $image['name'];
            if($check_user_demo['is_demo']) {
                $short_path_image = "category/images/cover/$name";
                $new_file_image_activity_path = WP_CONTENT_DIR . '/uploads/sites/' . $check_user_demo['blog_id'].DS.$short_path_image;

            } else {
                $short_path_image = "upload/category/images/cover/$name";
                $new_file_image_activity_path = WPBOOKINGPRO_PATH_ROOT . DS . $short_path_image;

            }
            if (!FileAlias::write($new_file_image_activity_path, FileAlias::read($image['tmp_name']))) {
                throw new Exception(Text::_("can not upload image cover"));
            }
            $item->image = $short_path_image;
            $data = (array)$item;
            $item = parent::save($data);
        }
        return $item;
    }



}
