<?php

namespace App\Validators;

use App\Exceptions\BadRequest as BadRequestException;
use App\Library\Validators\Common as CommonValidator;
use App\Repos\CourseUser as CourseUserRepo;

class CourseUser extends Validator
{

    public function checkRelation($id)
    {
        $courseUserRepo = new CourseUserRepo();

        $courseUser = $courseUserRepo->findById($id);

        if (!$courseUser) {
            throw new BadRequestException('course_user.not_found');
        }

        return $courseUser;
    }

    public function checkCourseUser($courseId, $userId)
    {
        $repo = new CourseUserRepo();

        $courseUser = $repo->findCourseUser($courseId, $userId);

        if (!$courseUser) {
            throw new BadRequestException('course_user.not_found');
        }

        return $courseUser;
    }

    public function checkCourse($id)
    {
        $validator = new Course();

        return $validator->checkCourse($id);
    }

    public function checkUser($id)
    {
        $validator = new User();

        return $validator->checkUser($id);
    }

    public function checkExpiryTime($expiryTime)
    {
        $value = $this->filter->sanitize($expiryTime, ['trim', 'string']);

        if (!CommonValidator::date($value, 'Y-m-d H:i:s')) {
            throw new BadRequestException('course_user.invalid_expiry_time');
        }

        return strtotime($value);
    }

    public function checkIfJoined($courseId, $userId)
    {
        $repo = new CourseUserRepo();

        $courseUser = $repo->findCourseStudent($courseId, $userId);

        if ($courseUser) {
            throw new BadRequestException('course_user.has_joined');
        }
    }

    public function checkIfReviewed($courseId, $userId)
    {
        $repo = new CourseUserRepo();

        $courseUser = $repo->findCourseUser($courseId, $userId);

        if ($courseUser && $courseUser->reviewed) {
            throw new BadRequestException('course_user.has_reviewed');
        }
    }

}
