<?php

namespace App\Http\Controllers;

use App\Models\Course;
use App\Models\Module;
use App\Models\Enroll;
use App\Models\Student;
use Illuminate\Http\Request;
use \App\Http\Requests\StoreCourseRequest;
use \App\Http\Requests\UpdateCourseRequest;
use App\Models\VehicleBooking;
use DB;

class CourseController extends Controller
{
    protected $LogController;
    public function __construct(LogController $LogController)
    {
        $this->LogController = $LogController;
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $courses = Course::where('is_active', '=', '1')->get();

        return view('course.index')->with([
            'page_title' => 'การจัดการคอร์สเรียน',
            'courses' => $courses
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('course.create', ['page_title' => 'เพิ่มคอร์สเรียน']);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(StoreCourseRequest $request)
    {
        // Courses::create($request->all());
        $course = new Course;
        $course->type = $request->type;
        $course->gear = $request->gear;
        $course->name = $request->name;
        $course->hour = $request->hour;
        $course->hour_training = $request->hourTraning;
        $course->price = $request->price;
        $course->license_test = $request->test;
        $course->optional = $request->optional;
        $course->optional_price = $request->oPrice;
        $course->save();
        $cid = $course->id;

        for($i=1; $i<=$request->noOfModule; $i++) {
            $m = 'module'.$i;
            $id = $m.'ID';
            $mHour = 'mHour'.$i;
            $mDrive = 'mDrive'.$i;
            $mSig = 'significance'.$i;
            if( $request->$m != '' || $request->$m != null) {
                $module = new Module;
                $module->course_id = $cid;
                $module->module = $request->$m;
                $module->module_hour = $request->$mHour;
                $module->drive = $request->$mDrive;
                $module->significance = ($request->$mSig) ? $request->$mSig : '0' ;
                $module->save();
            }
        }
        // Log
        $description = "เพิ่มคอร์สเรียน: ". $request->name;
        $this->LogController->log('การจัดการคอร์สเรียน', 'เพิ่มข้อมูล', $description);

        return redirect()->route('course.index')->with('feedback','เพิ่มข้อมูลคอร์สเรียบร้อย');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Course  $course
     * @return \Illuminate\Http\Response
     */
    public function show(Course $course)
    {
        $modules = Module::where('course_id', '=', $course->id)->orderBy('id','asc')->get();

        return view('course.show', [
            'page_title'=>'รายละเอียดคอร์ส',
            'course'=>$course,
            'modules' => $modules,
        ]);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Course  $course
     * @return \Illuminate\Http\Response
     */
    public function edit(Course $course)
    {
        $modules = Module::where('course_id', '=', $course->id)->get();
        return view('course.edit', [
            'page_title' => 'แก้ไขคอร์ส',
            'course' => $course,
            'modules' => $modules
        ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Course  $course
     * @return \Illuminate\Http\Response
     */
    public function update(UpdateCourseRequest $request, Course $course)
    {
        $no_of_module = $request->count;

        $course->gear = $request->gear;
        $course->name = $request->name;
        $course->hour = $request->hour;
        $course->hour_training = $request->hourTraning;
        $course->price = $request->price;
        $course->license_test = $request->test;
        $course->optional = $request->optional;
        $course->optional_price = $request->oPrice;
        $course->save();

        for($i=1; $i<=$no_of_module; $i++) {
            $m = 'module'.$i;
            $id = $m.'ID';
            $mHour = 'mHour'.$i;
            $mDrive = 'mDrive'.$i;
            $mSig = 'significance'.$i;
            if( $request->$m != '' || $request->$m != null) {
                $module = Module::find($request->$id);
                $module->module = $request->$m;
                $module->module_hour = $request->$mHour;
                $module->drive = $request->$mDrive;
                $module->significance = ($request->$mSig) ? $request->$mSig : '0' ;
                $module->save();
            }
        }
        // Log
        $description = "แก้ไขคอร์สเรียน: ". $request->name;
        $this->LogController->log('การจัดการคอร์สเรียน', 'แก้ไขข้อมูล', $description);

        return redirect()->route('course.index')->with('feedback','แก้ไขข้อมูลคอร์สเรียบร้อย');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Course  $course
     * @return \Illuminate\Http\Response
     */
    public function destroy(Course $course)
    {
        $course->is_active = '0';
        $course->save();

        // Log
        $description = "ลบคอร์สเรียน: ". $course->name;
        $this->LogController->log('การจัดการคอร์สเรียน', 'ลบข้อมูล', $description);
        //$course->delete();
        return redirect()->route('course.index')->with('feedback','ลบข้อมูลคอร์สเรียบร้อย');
    }

    public function checkCourseModule($course)
    {
        $modules = Module::where('course_id', '=', $course)->get();
        $moduleData['data'] = $modules;
        echo json_encode($moduleData);
        exit;
    }

    public function checkCourseModuleForBooking($eid)
    {
        $enrolls = Enroll::find($eid);
        // หาว่ามี book module ไหนไว้บ้าง
        $tmpArr = array();
        $bookings = VehicleBooking::where('enroll_id', '=', $eid)->pluck('course_module')->toArray();
        $tmpArr = array_merge($tmpArr, $bookings);
        // หา module ที่ยังไม่ได้ลงทะเบียน
        $modules = Module::where('course_id', '=', $enrolls->course_id)->whereNotIn('id', $tmpArr)->get();
        $moduleData['data'] = $modules;
        echo json_encode($moduleData);
        exit;
    }

    public function checkCourseModuleForCalendar($sid, $purpose, $type, $vehicleID, $date, $time)
    {
        // 1.หาว่า enrolls ไว้อะไรบ้าง
        $enrolls = Enroll::select('enrolls.id', 'course_id')->leftJoin('courses', 'enrolls.course_id', '=', 'courses.id')->where('student_id', '=', $sid)->where('type', '=', $type)->where('enrolls.is_active', '=', '1')->get();

        // 2.หาว่ามี book module ไหนไว้บ้าง
        $tmpArr = array();
        foreach($enrolls as $enroll) {
            $bookings = VehicleBooking::where('enroll_id', '=', $enroll->id)->pluck('course_module')->toArray();
            $tmpArr = array_merge($tmpArr, $bookings);
        }
        //  3.หา module ที่ยังไม่ได้ลงทะเบียน
        $modules = Module::select('course_modules.id', 'enrolls.id as eid', 'drive', 'module_hour', 'module')
                            ->leftJoin('enrolls', 'enrolls.course_id', '=', 'course_modules.course_id')
                            ->where('enrolls.student_id', '=', $sid)
                            ->where('enrolls.is_active', '=', '1')
                            ->whereNotIn('course_modules.id', $tmpArr)
                            ->get();
        // 4. check ว่าสามารถจองเวลานี้ได้ไหม
        foreach($modules as $keyIndex => $module) {
            $sTime = $time.":00:01";
            $eTime = ($time + $module->module_hour - 1) . ":59:59";
                if($module->drive == 'ไม่ขับ') {
                    $booked = VehicleBooking::selectRaw('count(*) as amount')
                                            ->where('date', '=', $date)
                                            ->where('vehicle_id', '=', $vehicleID)
                                            ->where('drive', '=', 'ไม่ขับ')
                                            ->whereRaw("(('$sTime' BETWEEN starttime AND endtime) or ('$eTime' BETWEEN starttime AND endtime))")
                                            ->first();

                    if($booked) {
                        if($booked->amount >= 5) {
                            unset($modules[$keyIndex]);
                        }
                    }
                }
                if($module->drive == 'ขับ') {
                    //DB::enableQueryLog();
                    $booked = VehicleBooking::select('vehicle_id')
                                            ->where('date', '=', $date)
                                            ->where('vehicle_id', '=', $vehicleID)
                                            ->where('drive', '=', 'ขับ')
                                            ->whereRaw("(('$sTime' BETWEEN starttime AND endtime) or ('$eTime' BETWEEN starttime AND endtime))")
                                            ->first();
                    //dd(DB::getQueryLog());
                    if($booked) {
                        unset($modules[$keyIndex]);
                    }
                }
        }

        $moduleData['data'] = $modules;
        echo json_encode($moduleData);
        exit;
    }

    public function add_module(Request $request)
    {
        $request->validate([
            'addModuleName' => 'required',
            'addModuleHour' => 'required|numeric',
            'addModuleDrive' => 'required'
        ],[
            'addModuleName.required' => 'กรุณากรอกชื่อรายวิชา',
            'addModuleHour.required' => 'กรุณากรอกจำนวนชั่วโมง',
            'addModuleHour.numeric' => 'กรุณากรอกเป็นตัวเลข',
            'addModuleDrive.required' => 'กรุณาเลือก'
        ]);

        $module = new Module();
        $module->course_id = $request->cid;
        $module->module = strip_tags($request->addModuleName);
        $module->module_hour = strip_tags($request->addModuleHour);
        $module->drive = $request->addModuleDrive;
        $module->significance = ($request->significance) ? $request->significance : '0';
        $module->save();

        // Log
        $this->LogController->log('คอร์สเรียน', 'เพิ่มข้อมูล', 'เพิ่มรายวิชา'.$request->addModuleName. ' ของคอร์ส'.$request->logAddModule);

        return redirect()->back();
    }

    public function delete_module(Request $request)
    {
        $booking = Module::find($request->mid);
        $booking->delete();
        // Log
        $this->LogController->log('คอร์สเรียน', 'ลบข้อมูล', $request->logModule);

        return redirect()->back();
    }
}
