<?php

namespace common\modules\school\controllers;

use common\components\BaseController;
use common\modules\school\models\LikesCourse;

class LikesCourseController extends BaseController
{
    public static function actionsTitles()
    {
        return [
            'Like-course' => 'Положительная оценка курса пользователем',
            'Unlike-course' => 'Отрицательная оценка курса пользователем',
        ];
    }
    
    
    public function actionLikeCourse()
    {
        if (!\Yii::$app->user->isGuest){
            $courseId = $_POST['courseId'];
            $userId = \Yii::$app->user->id;
            $estimateCourse = LikesCourse::findOne(['user_id' => $userId, 'course_id' => $courseId]);
            if (!$estimateCourse){
                $estimateCourse = new LikesCourse();
                $estimateCourse->estimate = LikesCourse::LIKE;
                $estimateCourse->user_id = $userId;
                $estimateCourse->course_id = $courseId;
                $estimateCourse->save();
            }  
            else{
                if ($estimateCourse->estimate == LikesCourse::UNLIKE){
                    $estimateCourse->estimate = LikesCourse::LIKE;
                    $estimateCourse->save();
                }
            }
            $gradeUser = LikesCourse::LIKE;
            echo $this->renderPartial('block_likes_course',  array(
                'gradeUser' => $gradeUser, 'courseId' => $courseId
            ));
        }
        
    }
    
    public function actionUnlikeCourse()
    {
        if (!\Yii::$app->user->isGuest){
            $courseId = $_POST['courseId'];
            $userId = \Yii::$app->user->id;
            $estimateCourse = LikesCourse::findOne(['user_id' => $userId, 'course_id' => $courseId]);
            if (!$estimateCourse){
                $estimateCourse = new LikesCourse();
                $estimateCourse->estimate = LikesCourse::UNLIKE;
                $estimateCourse->user_id = $userId;
                $estimateCourse->course_id = $courseId;
                $estimateCourse->save();
            }  
            else{
                if ($estimateCourse->estimate == LikesCourse::LIKE){
                    $estimateCourse->estimate = LikesCourse::UNLIKE;
                    $estimateCourse->save();
                }
            }
            $gradeUser = LikesCourse::UNLIKE;
            echo $this->renderPartial('block_likes_course',  array(
                'gradeUser' => $gradeUser, 'courseId' => $courseId
            ));
        }
        
    }
}
