<?php

namespace App\Http\Controllers\Api;

use App\Models\Answer;
use App\Models\Unit;
use App\User;
use Exception;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;


use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class UnitController extends BaseController
{

    // 创建
    public function createUnit(Request $request) {

            $data = Unit::create([
                'name' => $request->input('name'),
                'title' => $request->input('title'),
                'subject_id' => $request->input('subject_id'),
                'module_id' => $request->input('module_id'),
                'order' => $request->input('order')
            ]);
            return $this->response($data);
    }

    // 修改
    public function updateUnit(Request $request) {
        $Unit = Unit::findOrFail($request->input('id'));
        $data = $Unit->update([
            'name' => $request->input('name'),
            'title' => $request->input('title'),
            'order' => $request->input('order')
        ]);
        return $this->response($data);
    }

    // 删除
    public function deleteUnit(Request $request) {
        $model = Unit::findOrFail($request->input('id'));
        if(!empty($model->courses->count())) return $this->safeException('该模块下有相关课程，请移除课程后重试');
        $model->delete();
        return $this->response($model);
    }

    // 详情
    public function getUnit(Request $request) {
        $model = Unit::with('children')->findOrFail($request->input('id'));
        return $this->response($model);
    }
}

