<?php

namespace App\Http\Controllers;

use App\Models\Vehicle;
use App\Models\VehicleBooking;
use App\Models\Teacher;
use App\Models\TeacherBooking;
use App\Models\Payment;
use App\Models\Student;
use App\Models\Enroll;
use App\Models\Module;
use Illuminate\Http\Request;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Collection;
use Illuminate\Pagination\LengthAwarePaginator;

class CalendarController extends Controller
{
    protected $LogController;
    public function __construct(LogController $LogController)
    {
        $this->LogController = $LogController;
    }

    public function print(Request $request)
    {
        return $request->date;
    }

    public function genCalendar($from, $type)
    {

        $teachers = Teacher::orderBy('firstname')->get();
        if($type=='index') {
            $vehicles =  Vehicle::orderBy('id')->paginate(4);
        } else {
            $vehicles =  Vehicle::orderBy('id')->paginate(4)->appends(request()->query());
        }
        $students = Student::where('is_active', '=', '1')->orderBy('firstname')->get();


        $firstday = date("Y-m-d", strtotime('monday this week', strtotime($from)));
        $date = strtotime($firstday);
        $lastday = strtotime("+6 day", $date);
        $lastday = date('Y-m-d', $lastday);
        $week = getDateBetween2Date($firstday, $lastday);

        // init array data
        for($d=0; $d<28; $d++) {
            $arrData[$d] = '0';
            $arrSpan[$d] = '1';
            $arrGear[$d] = '0';
        }

        $arrStartBlock = ['7'=>'1', '8'=>'3', '9'=>'5', '10'=>'7', '11'=>'9', '12'=>'11', '13'=>'13', '14'=>'15', '15'=>'17', '16'=>'19', '17'=>'21', '18'=>'23', '19'=>'25', '20'=>'27'];
        //$arrEndBlock = ['7'=>'0', '8'=>'2', '9'=>'4', '10'=>'6', '11'=>'8', '12'=>'10', '13'=>'12', '14'=>'14', '15'=>'16', '16'=>'18', '17'=>'20', '18'=>'22', '19'=>'24', '20'=>'26'];
        // end init
        $arrVehicles = array();
        $arr1 = array();
        $arrSpan1 = array();
        $arr2 = array();
        $arrSpan2 = array();
        $arrGear2 = array();
        $arr3 = array();
        $arrSpan3 = array();

        $data1 = VehicleBooking::select('vehicle_bookings.id as vbid', 'vehicle_bookings.date as vdate', 'vehicle_bookings.*', 'enrolls.*', 'students.*', 'course_modules.module as module', 'course_modules.module_hour as hour')
                                            ->leftJoin('enrolls', 'vehicle_bookings.enroll_id', '=', 'enrolls.id')
                                            ->leftJoin('students', 'students.id', '=', 'enrolls.student_id')
                                            ->leftJoin('course_modules', 'course_modules.id', '=', 'vehicle_bookings.course_module')
                                            ->whereRaw('vehicle_bookings.date between "'.$firstday.'" and "'.$lastday.'"')
                                            ->where('enrolls.purpose', '=', 'เพิ่มประสบการณ์')
                                            ->orderBy('starttime')
                                            ->get();

        $data2 = VehicleBooking::select('vehicle_bookings.id as vbid', 'vehicle_bookings.gear as vgear', 'vehicle_bookings.date as vdate', 'vehicle_bookings.*', 'students.*', 'enrolls.*', 'course_modules.module as module', 'course_modules.module_hour as hour')
                                            ->leftJoin('enrolls', 'vehicle_bookings.enroll_id', '=', 'enrolls.id')
                                            ->leftJoin('students', 'students.id', '=', 'enrolls.student_id')
                                            ->leftJoin('course_modules', 'course_modules.id', '=', 'vehicle_bookings.course_module')
                                            ->whereRaw('vehicle_bookings.date between "'.$firstday.'" and "'.$lastday.'"')
                                            ->where('enrolls.purpose', '=', 'เรียนและสอบ')
                                            ->orderBy('vehicle_bookings.date')
                                            ->orderBy('starttime')
                                            ->get();

        $data3 = VehicleBooking::select('vehicle_bookings.id as vbid', 'vehicle_bookings.date as vdate','vehicle_bookings.*', 'enrolls.*', 'students.*', 'course_modules.module as module', 'course_modules.module_hour as hour')
                                            ->leftJoin('enrolls', 'vehicle_bookings.enroll_id', '=', 'enrolls.id')
                                            ->leftJoin('students', 'students.id', '=', 'enrolls.student_id')
                                            ->leftJoin('course_modules', 'course_modules.id', '=', 'vehicle_bookings.course_module')
                                            ->whereRaw('vehicle_bookings.date between "'.$firstday.'" and "'.$lastday.'"')
                                            ->where('enrolls.purpose', '=', 'เก็บชั่วโมงเพื่อสอบ')
                                            ->orderBy('starttime')
                                            ->get();

        for($w=0; $w<count($week); $w++) {

            $date = $week[$w];

            for($i=0; $i<count($vehicles); $i++) {
                $id = $vehicles[$i]->id;

                $arrVehicles[$i] = $id;

                $arrTime1[$w][$id] = array();
                $arrHour1[$w][$id] = array();
                $arrName1[$w][$id] = array();
                $arrBook1[$w][$id] = array();
                $arrT1[$w][$id] = array();
                $arrM1[$w][$id] = array();
                $arrDriveTime1[$w][$id] = array();

                $arrTime2[$w][$id] = array();
                $arrHour2[$w][$id] = array();
                $arrName2[$w][$id] = array();
                $arrBook2[$w][$id] = array();
                $arrT2[$w][$id] = array();
                $arrM2[$w][$id] = array();
                $arrDriveTime2[$w][$id] = array();
                $arrG2[$w][$id] = array();

                $arrTime3[$w][$id] = array();
                $arrHour3[$w][$id] = array();
                $arrName3[$w][$id] = array();
                $arrBook3[$w][$id] = array();
                $arrT3[$w][$id] = array();
                $arrM3[$w][$id] = array();
                $arrDriveTime3[$w][$id] = array();
            }

            for($a=0; $a<count($arrVehicles); $a++) {
                $vid = $arrVehicles[$a];

                $arr1[$w][$vid] = $arrData;
                $arrSpan1[$w][$vid] = $arrSpan;
                $arrValue1[$w][$vid] = array();
                $arrBooking1[$w][$vid] = array();
                $arrSchedule1[$w][$vid] = array();
                $arrTeacher1[$w][$vid] = array();
                $arrModule1[$w][$vid] = array();

                $arr2[$w][$vid] = $arrData;
                $arrSpan2[$w][$vid] = $arrSpan;
                $arrGear2[$w][$vid] = $arrGear;
                $arrValue2[$w][$vid] = array();
                $arrBooking2[$w][$vid] = array();
                $arrSchedule2[$w][$vid] = array();
                $arrTeacher2[$w][$vid] = array();
                $arrModule2[$w][$vid] = array();

                $arr3[$w][$vid] = $arrData;
                $arrSpan3[$w][$vid] = $arrSpan;
                $arrValue3[$w][$vid] = array();
                $arrBooking3[$w][$vid] = array();
                $arrSchedule3[$w][$vid] = array();
                $arrTeacher3[$w][$vid] = array();
                $arrModule3[$w][$vid] = array();

                // เพิ่มประสบการณ์
                $k=0;
                for($i=0; $i<count($data1); $i++) {
                    if( ($data1[$i]->vdate==$date) && ($data1[$i]->vehicle_id==$vid) ) {
                        $arrTime1[$w][$vid][$k] = getHourDigit($data1[$i]->starttime);
                        $arrHour1[$w][$vid][$k] = calHour($data1[$i]->starttime, $data1[$i]->endtime);
                        $arrName1[$w][$vid][$k] = $data1[$i]->firstname." ".$data1[$i]->lastname;
                        $arrBook1[$w][$vid][$k] = $data1[$i]->vbid;
                        $arrT1[$w][$vid][$k] = $data1[$i]->teacher_id;
                        $arrM1[$w][$vid][$k] = $data1[$i]->module;
                        $arrDriveTime1[$w][$vid][$k] = $data1[$i]->starttime . " - ". $data1[$i]->endtime;
                        $k++;
                    } else {
                        continue;
                    }
                }
                for($t=0; $t<count($arrTime1[$w][$vid]); $t++) {
                    $x = (string)((int)$arrTime1[$w][$vid][$t]);
                    $hour = $arrHour1[$w][$vid][$t] * 2;
                    $block = $arrStartBlock[$x];
                    $arr1[$w][$vid][$block] = '1';
                    $arrSpan1[$w][$vid][$block] = $hour;
                    for($j=1; $j<$hour; $j++){
                        $z = $block + $j;
                        $arr1[$w][$vid][$z] = '-1';
                    }
                    if($t!=0) {
                        if(array_key_exists($block, $arrValue1[$w][$vid])) {
                            $arrValue1[$w][$vid][$block] .= ','. $arrName1[$w][$vid][$t];
                            $arrBooking1[$w][$vid][$block] .= ','. $arrBook1[$w][$vid][$t];
                        } else {
                            $arrValue1[$w][$vid][$block] = $arrName1[$w][$vid][$t];
                            $arrBooking1[$w][$vid][$block] = $arrBook1[$w][$vid][$t];
                        }
                    } else {
                        $arrValue1[$w][$vid][$block] = $arrName1[$w][$vid][$t];
                        $arrBooking1[$w][$vid][$block] = $arrBook1[$w][$vid][$t];
                    }
                    $arrSchedule1[$w][$vid][$block] = $arrDriveTime1[$w][$vid][$t];
                    $arrTeacher1[$w][$vid][$block] = $arrT1[$w][$vid][$t];
                    $arrModule1[$w][$vid][$block] = $arrM1[$w][$vid][$t];
                }

                // เรียนและสอบ
                $k=0;
                for($i=0; $i<count($data2); $i++) {
                    if( ($data2[$i]->vdate==$date) && ($data2[$i]->vehicle_id==$vid) ) {
                        $arrTime2[$w][$vid][$k] = getHourDigit($data2[$i]->starttime);
                        $arrHour2[$w][$vid][$k] = calHour($data2[$i]->starttime, $data2[$i]->endtime);
                        $arrName2[$w][$vid][$k] = $data2[$i]->firstname." ".$data2[$i]->lastname;
                        $arrBook2[$w][$vid][$k] = $data2[$i]->vbid;
                        $arrT2[$w][$vid][$k] = $data2[$i]->teacher_id;
                        $arrM2[$w][$vid][$k] = $data2[$i]->module;
                        $arrG2[$w][$vid][$k] = getGearAbbr($data2[$i]->vgear);
                        $arrDriveTime2[$w][$vid][$k] = $data2[$i]->starttime . " - ". $data2[$i]->endtime;
                        $k++;
                    } else {
                        continue;
                    }
                }
                for($t=0; $t<count($arrTime2[$w][$vid]); $t++) {
                    $x = (string)((int)$arrTime2[$w][$vid][$t]);
                    $hour = $arrHour2[$w][$vid][$t] * 2;
                    $block = $arrStartBlock[$x];
                    $arr2[$w][$vid][$block] = '1';
                    $arrSpan2[$w][$vid][$block] = $hour;
                    $arrGear2[$w][$vid][$block] = $arrG2[$w][$vid][$t];
                    for($j=1; $j<$hour; $j++){
                        $z = $block + $j;
                        $arr2[$w][$vid][$z] = '-1';
                    }
                    if($t!=0) {
                        // if($arrValue2[$w][$vid][$block]!='') {
                        if(array_key_exists($block, $arrValue2[$w][$vid])) {
                            $arrValue2[$w][$vid][$block] .= ','. $arrName2[$w][$vid][$t];
                            $arrBooking2[$w][$vid][$block] .= ','. $arrBook2[$w][$vid][$t];
                        } else {
                            $arrValue2[$w][$vid][$block] = $arrName2[$w][$vid][$t];
                            $arrBooking2[$w][$vid][$block] = $arrBook2[$w][$vid][$t];
                        }
                    } else {
                        $arrValue2[$w][$vid][$block] = $arrName2[$w][$vid][$t];
                        $arrBooking2[$w][$vid][$block] = $arrBook2[$w][$vid][$t];
                    }
                    $arrSchedule2[$w][$vid][$block] = $arrDriveTime2[$w][$vid][$t];
                    $arrTeacher2[$w][$vid][$block] = $arrT2[$w][$vid][$t];
                    $arrModule2[$w][$vid][$block] = $arrM2[$w][$vid][$t];
                }

                // เก็บชั่วโมงเพื่อสอบ
                $k=0;
                for($i=0; $i<count($data3); $i++) {
                    if( ($data3[$i]->vdate==$date) && ($data3[$i]->vehicle_id==$vid) ) {
                        $arrTime3[$w][$vid][$k] = getHourDigit($data3[$i]->starttime);
                        $arrHour3[$w][$vid][$k] = calHour($data3[$i]->starttime, $data3[$i]->endtime);
                        $arrName3[$w][$vid][$k] = $data3[$i]->firstname." ".$data3[$i]->lastname;
                        $arrBook3[$w][$vid][$k] = $data3[$i]->vbid;
                        $arrT3[$w][$vid][$k] = $data3[$i]->teacher_id;
                        $arrM3[$w][$vid][$k] = $data3[$i]->module;
                        $arrDriveTime3[$w][$vid][$k] = $data3[$i]->starttime . " - ". $data3[$i]->endtime;
                        $k++;
                    } else {
                        continue;
                    }
                }
                for($t=0; $t<count($arrTime3[$w][$vid]); $t++) {
                    $x = (string)((int)$arrTime3[$w][$vid][$t]);
                    $hour = $arrHour3[$w][$vid][$t] * 2;
                    $block = $arrStartBlock[$x];
                    $arr3[$w][$vid][$block] = '1';
                    $arrSpan3[$w][$vid][$block] = $hour;
                    for($j=1; $j<$hour; $j++){
                        $z = $block + $j;
                        $arr3[$w][$vid][$z] = '-1';
                    }
                    if($t!=0) {
                        if(array_key_exists($block, $arrValue3[$w][$vid])) {
                            $arrValue3[$w][$vid][$block] .= ','. $arrName3[$w][$vid][$t];
                            $arrBooking3[$w][$vid][$block] .= ','. $arrBook3[$w][$vid][$t];
                        } else {
                            $arrValue3[$w][$vid][$block] = $arrName3[$w][$vid][$t];
                            $arrBooking3[$w][$vid][$block] = $arrBook3[$w][$vid][$t];
                        }
                    } else {
                        $arrValue3[$w][$vid][$block] = $arrName3[$w][$vid][$t];
                        $arrBooking3[$w][$vid][$block] = $arrBook3[$w][$vid][$t];
                    }
                    $arrSchedule3[$w][$vid][$block] = $arrDriveTime3[$w][$vid][$t];
                    $arrTeacher3[$w][$vid][$block] = $arrT3[$w][$vid][$t];
                    $arrModule3[$w][$vid][$block] = $arrM3[$w][$vid][$t];
                }
            }
        }
        return view('calendar.index')->with([
            'page_title' => 'ตารางเรียน',
            'date' => formatDateFromDB($firstday),
            'vehicles' => $vehicles,
            'teachers' => $teachers,
            'teachersArr' => $teachers->toArray(),
            'students' => $students,
            'week' => $week,
            'arr1' => $arr1,
            'arrSpan1' => $arrSpan1,
            'arrValue1' => $arrValue1,
            'arrBooking1' => $arrBooking1,
            'arrSchedule1' => $arrSchedule1,
            'arrTeacher1' => $arrTeacher1,
            'arrModule1' => $arrModule1,
            'arr2' => $arr2,
            'arrSpan2' => $arrSpan2,
            'arrGear2' => $arrGear2,
            'arrValue2' => $arrValue2,
            'arrBooking2' => $arrBooking2,
            'arrSchedule2' => $arrSchedule2,
            'arrTeacher2' => $arrTeacher2,
            'arrModule2' => $arrModule2,
            'arr3' => $arr3,
            'arrSpan3' => $arrSpan3,
            'arrValue3' => $arrValue3,
            'arrBooking3' => $arrBooking3,
            'arrSchedule3' => $arrSchedule3,
            'arrTeacher3' => $arrTeacher3,
            'arrModule3' => $arrModule3,
        ]);
    }

    public function index()
    {
        return $this->genCalendar(date('Y-m-d'), 'index');
    }

    public function submit(Request $request)
    {
        $request->validate([
            'date' => 'required|date_format:d/m/Y',
        ],[
            'date.required' => 'กรุณากรอกวันที่',
            'date.date_format:m/d/Y' => 'กรุณากรอกรูปแบบวันที่ให้ถูกต้อง',
        ]);
        return $this->genCalendar(formatDateToDB($request->date), 'submit');
    }

    public function cancelBooking(Request $request)
    {
        $booking = VehicleBooking::where('id', '=', $request->vehicleBookingID)->first();
        $booking->delete();
        return redirect()->back();
    }

    public function paginate($items, $perPage = 4, $page = null, $options = [])
    {
        $page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
        $items = $items instanceof Collection ? $items : Collection::make($items);
        return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
    }

    public function booking($vbid, $teacher, $teacherEarn)
    {
        $vehicle = VehicleBooking::leftJoin('vehicles', 'vehicle_bookings.vehicle_id', '=', 'vehicles.id')->where('vehicle_bookings.id', '=', $vbid)->first();
        $type = $vehicle->type;
        $gear = $vehicle->gear;
        $drive = $vehicle->drive;
        $hour = calHour($vehicle->starttime, $vehicle->endtime);

        if($drive=='ขับ') {
            $earn = Payment::where('drive', '=', 'ขับ')->where('type', '=', $type)->where('gear', '=', $gear)->first();
        } else {
            $earn = Payment::where('drive', '=', 'ไม่ขับ')->first();
        }
        $earn = ($earn->cost * $hour);

        $vehicle = VehicleBooking::find($vbid);
        $vehicle->teacher_id = $teacher;
        if($teacherEarn) $vehicle->teacher_earn = $earn;
        $vehicle->save();
    }

    public function teacherBooking(Request $request)
    {
        $request->validate([
            'teacher' => 'required',
        ],[
            'teacher.required' => 'กรุณาเลือกผู้สอน'
        ]);

        if(numberOfStudent($request->vehicleBookingID) > 1) {   // นักเรียนมากกว่า 1 คน ต่อครู 1 คน
            for($i=0; $i<numberOfStudent($request->vehicleBookingID); $i++) {
                $vid = getVehicleBookingAtN($request->vehicleBookingID, $i);
                if($i==0) {
                    $earn = true;   // คิดรายได้ผู้สอนจากนักเรียนคนเดียว
                } else {
                    $earn = false;
                }
                $this->booking($vid, $request->teacher, $earn);
            }
        } else {    //นักเรียน 1 คนต่อครู 1 คน
            $this->booking($request->vehicleBookingID, $request->teacher, true);
        }

        return redirect()->back();
    }

    public function vehicleBooking(Request $request)
    {
        $request->validate([
            'purposeBooking' => 'required',
            'studentBooking' => 'required',
            'moduleBooking' => 'required'
        ],[
            'purposeBooking.required' => 'กรุณาเลือกรูปแบบการเรียน',
            'studentBooking.required' => 'กรุณาเลือกนักเรียนเรียน',
            'moduleBooking.required' => 'กรุณาเลือกรายวิชา',
        ]);

        // if($request->purpose=='เก็บชั่วโมงเพื่อสอบ') {
        //     $drive = 'ไม่ขับ';
        // } else {
        //     $drive = 'ขับ';
        // }

        $tmp = explode('-', $request->moduleBooking);
        $enroll_id = $tmp[0];
        $module_id = $tmp[1];
        $hour = $tmp[2];

        $drive = Module::find($module_id);
        $drive = $drive->drive;

        $booking = new VehicleBooking();
        $booking->enroll_id = $enroll_id;
        $booking->vehicle_id = $request->vehicle;
        $booking->drive = $drive;
        $booking->date = $request->vdate;
        $booking->starttime = $request->time.":00:00";
        $booking->endtime = ($request->time + $hour) . ":00:00";
        $booking->course_module = $module_id;
        $booking->save();

        // Log
        $description = "เพิ่มตารางเรียน วันที่:". formatDateFromDB($request->vdate). " เวลา:".$request->time.":00:00 รถ id:". $request->vehicle;
        $this->LogController->log('ตารางเรียน', 'เพิ่มข้อมูล', $description);

        return redirect()->back();
    }

}
