<?php

namespace App\Http\Controllers\Teacher;

use App\Models\CheckCard;
use App\Models\StudentCourseTeacher;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class CheckCardController extends Controller
{
    protected $redirect_index = '/teacher/CheckCard/index';

    protected $view_path = 'teacher.check-cards.';

    protected $pre_uri = '/teacher/CheckCard/';

    protected $model_name = '打卡';

    protected $model;

    public function __construct()
    {
        parent::__construct();
        $this->model = new CheckCard();
    }

    public function index(Request $request)
    {
        $teacher = Auth::guard('teacher')->user();
        $ids = StudentCourseTeacher::where('teacher_id', $teacher->id)->orWhere('teacher_id', 0)->pluck('student_course_id');
        $list = $this->model->whereIn('student_course_id', $ids)->orderBy('created_at', 'desc')->get();

        if(!empty($request->input('keyword')) && !empty(trim($request->input('keyword')))) {
            $keyword = trim($request->input('keyword'));

            $list = $list->filter(function ($value) use($keyword) {
                if(!empty($value->student) && !(strpos($value->student->name, $keyword) === false)) {
                    return true;
                }
                if(!empty($value->course) && !(strpos($value->course->name, $keyword) === false)) {
                    return true;
                }
                return false;
            });
        }

        if(!empty($request->input('begin_date'))) {
            $begin_date_time = Carbon::createFromTimestamp(strtotime($request->input('begin_date')))->toDateTimeString();
        } else {
            $begin_date_time = Carbon::now()->subYears(10)->toDateTimeString();
        }

        if(!empty($request->input('end_date'))) {
            $end_date_time = Carbon::createFromTimestamp(strtotime($request->input('end_date')))->addDay()->toDateTimeString();
        } else {
            $end_date_time = Carbon::now()->addYears(10)->toDateTimeString();
        }

        if(!empty($begin_date_time) || !empty($end_date_time)) {
            $list = $list->filter(function ($value) use($begin_date_time, $end_date_time) {
                return $value->begin_date_time >= $begin_date_time && $value->end_date_time < $end_date_time;
            });
        }

        $list = $this->paginate($list);

        foreach($list as $item) {
            $item->duration = $item->getDuration();
        }

        list($pre_uri, $model_name) = array($this->pre_uri, $this->model_name);
        return view($this->view_path . 'index', compact('list', 'pre_uri', 'model_name'));
    }
}
