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

use WpBookingPro\Factory;
use WpBookingPro\Mvc\Model\ModelForm;
use WpBookingPro\Form\Form;
use WpBookingPro\Mvc\Model\ModelList;
use WpBookingPro\Registry\Registry;
class ReviewsModel extends ModelList
{
    /**
     * @var string
     */
    public $context = "reviews";
    /**
     * @var string
     */
    public $table_name = "review";

    public function getListQuery()
    {
        $input = Factory::getInput();
        $user_id  = $input->getInt('user_id',0);

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

        ;
        if($user_id > 0) {
            $query1->clear()
                ->select('id')
                ->from($this->getTableName('service'))
                ->where('user_id='.(int)$user_id)
            ;
            $service_id = $this->db->setQuery($query1)->loadResult();
            $query->leftJoin($this->getTableName('vendor_review').' AS vendor_review ON vendor_review.review_id=a.id')
                ->leftJoin($this->getTableName('service_review').' AS service_review ON service_review.review_id=a.id')
                ->where('vendor_review.user_id='.(int)$user_id)
                ->orWhere('service_review.service_id='.(int)$service_id)
            ;
        }
        $query->order($this->getState('list.ordering', 'a.ordering') . ' ' . $this->getState('list.direction', 'ASC'));

        return $query;
    }


    public function getList()
    {
        $input = Factory::getInput();
        $user_id  = $input->getInt('user_id',0);
        $db=Factory::getDBO();
        $query=$this->getListQuery();
        $list =  $db->setQuery($query)->loadObjectList();
        foreach ($list as &$item) {
            $query->clear()
                ->select('service_id')
                ->from($this->getTableName('service_review'))
                ->where('review_id='.(int)$item->id)
            ;

            $item->service_id = $db->setQuery($query)->loadResult();
            $query->clear()
                ->select('user_id')
                ->from($this->getTableName('vendor_review'))
                ->where('review_id='.(int)$item->id)
            ;
            $item->user_id = $db->setQuery($query)->loadResult();
            $rating_ambience = isset($item->rating_ambience)?$item->rating_ambience:0;
            $rating_cleanliness = isset($item->rating_cleanliness)?$item->rating_cleanliness:0;
            $rating_staff = isset($item->rating_staff)?$item->rating_staff:0;
            $rating_value = isset($item->rating_value)?$item->rating_value:0;
            $item->avg_rating = ($rating_ambience + $rating_cleanliness + $rating_staff + $rating_value) / 4;
        }
        return $list;
    }
}
