<?php

namespace App\Modules\Student\Model;

use App\Models\Crud;
use App\Models\Tenant;
use App\Modules\Staff\Model\Staff;
use App\User;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
use Yajra\DataTables\Facades\DataTables;

class ClassSection extends Crud
{
    protected $fillable = ['class_id', 'section_id', 'staff_id'];
//    protected  $guarded = ['deleted_at'];

    /**
     * @return BelongsTo
     */
    public function studentClass()
    {
        return $this->belongsTo(StudentClass::class, 'class_id')->withDefault();
    }

    /**
     * @return BelongsTo
     */
    public function section()
    {
        return $this->belongsTo(Section::class, 'section_id')->withDefault();
    }

    /**
     * @return BelongsTo
     */
    public function staff()
    {
        return $this->belongsTo(Staff::class, 'staff_id')->withDefault();
    }

    public static function getDatatableClassTeachers()
    {
        $options           = array();
        $options['object'] = true;
        $options['with']   = ['section', 'studentClass', 'staff'];

        $class = new ClassSection();
        $model = $class->find($options);

        return DataTables::eloquent($model)
            ->addColumn('action', function (ClassSection $class) {
                return $class->returnAjaxAction('section', $class, ['edit', 'destroy']);
            })
            ->addColumn('section', function (ClassSection $class) {
                return $class->section->title;
            })
            ->addColumn('class', function (ClassSection $class) {
                return $class->studentClass->title;
            })
            ->addColumn('teacher', function (ClassSection $class) {
                return $class->staff->user->name;
            })
            ->rawColumns(['action', 'sections'])
            ->make(true);
    }

    /**
     * Return class teacher name by grade and division
     *
     * @param $gradeId
     * @param $divisionId
     * @return mixed|string
     */
    public static function getClassTeacherNameByClass($gradeId, $divisionId)
    {
        $option['where'] = ['class_id' => $gradeId, 'section_id' => $divisionId];
        $result          = (new ClassSection())->find($option)->first();

        if (isset($result->staff_id) && !is_null($result->staff_id)) {
            return $result->staff->user->name;
        }

        return '';
    }

}
