<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class StudentCourse extends Model
{
    protected $table = 'student_courses';

    protected $guarded = [];

    public function course()
    {
        return $this->hasOne('App\Models\Course', 'id', 'course_id');
    }

    public function getTeacherNames()
    {
        if($this['assign_teacher'] == 1) {
            return '全部';
        }

        $ids = $this['studentCourseTeachers']->pluck('teacher_id');
        return (new Teacher())->whereIn('id', $ids)->get()->implode('name', ',');
    }

    public function getTeacherFullNames()
    {
        if($this['assign_teacher'] == 1) {
            return '全部';
        }

        $ids = $this['studentCourseTeachers']->pluck('teacher_id');
        return (new Teacher())->whereIn('id', $ids)->get()->implode('name', '/');
    }

    public function studentCourseTeachers()
    {
        return $this->hasMany('App\Models\StudentCourseTeacher');
    }

    public function getTeacherIds()
    {
        if($this['assign_teacher'] == 1) {
            return collect();
        }
        return $this['studentCourseTeachers']->pluck('teacher_id');
    }

    public function updateStudentCourseTeachers($teachers, $assign_teacher)
    {
        StudentCourseTeacher::where('student_course_id', $this['id'])->delete();
        if($assign_teacher == 2) {
            if(!empty($teachers) && is_array($teachers)) {
                foreach($teachers as $teacher) {
                    StudentCourseTeacher::create([
                        'student_course_id' => $this['id'],
                        'teacher_id' => $teacher,
                        'student_id' => $this['student_id']
                    ]);
                }
            }
        } else {
            StudentCourseTeacher::create([
                'student_course_id' => $this['id'],
                'teacher_id' => 0,
                'student_id' => $this['student_id']
            ]);
        }
    }
}
