<?php

use Joomla\CMS\Factory;
use Joomla\CMS\MVC\Model\ListModel;
use Joomla\CMS\Table\Table;

defined('_JEXEC') or die('Restricted access');

class GuruModelGuruReview extends ListModel
{
    protected function populateState($ordering = null, $direction = null)
    {
        parent::populateState($ordering, $direction);

        $input = Factory::getApplication()->input;
        $start = $input->getInt('start', 0);
        $this->setState('list.start', $start);
        $this->setState('list.limit', 5);
    }

    public function getListQuery()
    {
        $db = Factory::getDbo();
        $input = Factory::getApplication()->input;
        $course_id = $input->getInt('course_id', 0);

        $query = $db->getQuery(true);
        $query->select(array('a.*', 'b.firstname', 'b.lastname', 'b.image'))
            ->from('#__guru_review a')
            ->innerJoin('#__guru_customer b ON b.id = a.user_id')
            ->where('a.course_id = ' . $db->q($course_id))
            ->where('a.state = 1')
            ->order('a.review_time DESC');

        $rating = $input->getInt('rating');
        if ($rating) {
            $query->where('rating = ' . $db->q($rating));
        }

        return $query;
    }

    public function getCurrentUserReview()
    {
        $input = Factory::getApplication()->input;
        $course_id = $input->getInt('course_id', 0);
        $user = Factory::getUser();

        require_once JPATH_ROOT . '/components/com_guru/tables/gurureview.php';
        $table = Table::getInstance('Review', 'TableGuru');
        $table->load(array(
            'course_id' => $course_id,
            'user_id' => $user->id,
        ));

        return (object) $table->getProperties();
    }
}
