<?php

namespace App\Http\Controllers;

use App\Models\Teacher;
use App\Models\TeacherBooking;
use App\Models\VehicleBooking;
use App\Models\Withdraw;
use Illuminate\Http\Request;

class TeacherController 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()
    {
        $teachers = Teacher::where('is_active', '=', '1')->orderBy('id')->get();

        return view('teacher.index')->with([
            'page_title' => 'การจัดการผู้สอน',
            'teachers' => $teachers,
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('teacher.create')->with([
            'page_title' => 'เพิ่มผู้สอน'
        ]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required',
            'firstname' => 'required',
            'lastname' => 'required',
            'idCard' => 'required',
            'phone1' => 'required|numeric',
            'birthdate' => 'required|date_format:d/m/Y',
            'teacherType' => 'required'
        ],[
            'title.required' => 'กรุณาเลือกคำนำหน้าชื่อ',
            'firstname.required' => 'กรุณากรอกชื่อ',
            'lastname.required' => 'กรุณากรอกนามสกุล',
            'phone1.required' => 'กรุณากรอกหมายเลขโทรศัพท์',
            'phone1.numeric' => 'กรุณากรอกเป็นตัวเลข',
            'birthdate.required' => 'กรุณากรอกวันเกิด',
            'birthdate.date_format:m/d/Y' => 'กรุณากรอกรูปแบบวันที่ให้ถูกต้อง',
            'teacherType.required' => 'กรุณาเลือกประเภทผู้สอน'
        ]);

        $teacher = new Teacher;
        $teacher->type = $request->teacherType;
        $teacher->gender = getGender($request->title);
        $teacher->title = $request->title;
        $teacher->firstname = $request->firstname;
        $teacher->lastname = $request->lastname;
        $teacher->nickname = $request->nickname;
        $teacher->idcard = $request->idCard;
        $teacher->birthdate = formatDateToDB($request->birthdate);
        $teacher->address = $request->address;
        $teacher->district = $request->district;
        $teacher->amphoe = $request->amphoe;
        $teacher->province = $request->province;
        $teacher->phone_1 = $request->phone1;
        $teacher->phone_2 = $request->phone2;
        $teacher->save();

        // Log
        $description = "เพิ่มผู้สอน: ". $request->title.$request->firstname." ".$request->lastname;
        $this->LogController->log('การจัดการผู้สอน', 'เพิ่มข้อมูล', $description);

        return redirect()->route('teacher.index')->with('feedback','เพิ่มผู้สอนเรียบร้อย');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Teacher  $teacher
     * @return \Illuminate\Http\Response
     */
    public function show(Teacher $teacher)
    {
        if(isset($_GET['monthYear'])) {
            $tmp = explode('/', $_GET['monthYear']);
            $month = $tmp[0];
            $year = $tmp[1];
        } else {
            $month = date('m');
            $year = date('Y');
        }

        $monthYear = $month.'/'.$year;

        // $income = VehicleBooking::select('vehicle_bookings.*', 'vehicle_bookings.date as vdate', 'withdraws.method', 'withdraws.date as wdate')
        //                             ->selectRaw('sum(teacher_earn) as total, sum(starttime) as start, sum(endtime) as end')
        //                             ->leftJoin('withdraws', 'withdraws.teach_date', '=', 'vehicle_bookings.date')
        //                             ->where('vehicle_bookings.teacher_id', '=', $teacher->id)
        //                             ->whereMonth('vehicle_bookings.date', '=', $month)
        //                             ->whereYear('vehicle_bookings.date', '=', $year)
        //                             ->whereNotNull('vehicle_bookings.teacher_earn')
        //                             ->groupBy('vehicle_bookings.date')
        //                             ->get();

        $income = VehicleBooking::select('vehicle_bookings.*', 'vehicle_bookings.date as vdate')
                                    ->selectRaw('sum(teacher_earn) as total, sum(starttime) as start, sum(endtime) as end')
                                    ->where('vehicle_bookings.teacher_id', '=', $teacher->id)
                                    ->whereMonth('vehicle_bookings.date', '=', $month)
                                    ->whereYear('vehicle_bookings.date', '=', $year)
                                    ->whereNotNull('vehicle_bookings.teacher_earn')
                                    ->groupBy('vehicle_bookings.date')
                                    ->get();

        $total = 0;
        for($i=0; $i<count($income); $i++) {
            $total = $total + $income[$i]->total;
        }
        // $arrIncome = array();
        // for($i=0; $i<count($income); $i++) {
        //     $date = $income[$i]->vdate;
        //     $wdate = Withdraw::where('teacher_id', '=', $teacher->id)->where('teach_date', '=', $date)->first();
        //     $hour = ($income[$i]->end - $income[$i]->start)/10000;
        //     if($wdate!='') {    //  เบิกแล้ว
        //         $arrIncome[$i] = array('date'=>$date, 'hour'=>$hour, 'total'=>$income[$i]->total, 'wdate'=>$wdate->date, 'method'=>$wdate->method);
        //     } else {            // ยังไม่ได้เบิก
        //         $arrIncome[$i] = array('date'=>$date, 'hour'=>$hour, 'total'=>$income[$i]->total, 'wdate'=>NULL, 'method'=>NULL);
        //     }
        // }

        return view('teacher.show', [
            'page_title'=>'รายละเอียดผู้สอน',
            'teacher'=>$teacher,
            'month_year' => $monthYear,
            'incomes' => $income,
            'total' => $total
        ]);
    }

    // public function show_month_selected(Teacher $teacher)
    // {


    //     $income = TeacherBooking::leftJoin('vehicle_bookings', 'teacher_bookings.vehicle_booking_id', '=', 'vehicle_bookings.id')
    //                                 ->where('teacher_bookings.teacher_id', '=', $teacher->id)
    //                                 ->whereMonth('date', '=', date('m'))
    //                                 ->whereYear('date', '=', date('Y'))
    //                                 ->get();

    //     return view('teacher.show', [
    //         'page_title'=>'รายละเอียดผู้สอน',
    //         'teacher'=>$teacher,
    //         'month_year' => $monthYear,
    //         'incomes' => $income,
    //     ]);
    // }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Teacher  $teacher
     * @return \Illuminate\Http\Response
     */
    public function edit(Teacher $teacher)
    {
        return view('teacher.edit', [
            'page_title' => 'แก้ไขผู้สอน',
            'teacher' => $teacher
        ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Teacher  $teacher
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Teacher $teacher)
    {
        $request->validate([
            'title' => 'required',
            'firstname' => 'required',
            'lastname' => 'required',
            'idCard' => 'required',
            'phone1' => 'required|numeric',
            'birthdate' => 'required|date_format:d/m/Y',
            'teacherType' => 'required'
        ],[
            'title.required' => 'กรุณาเลือกคำนำหน้าชื่อ',
            'firstname.required' => 'กรุณากรอกชื่อ',
            'lastname.required' => 'กรุณากรอกนามสกุล',
            'phone1.required' => 'กรุณากรอกหมายเลขโทรศัพท์',
            'phone1.numeric' => 'กรุณากรอกเป็นตัวเลข',
            'birthdate.required' => 'กรุณากรอกวันเกิด',
            'birthdate.date_format:m/d/Y' => 'กรุณากรอกรูปแบบวันที่ให้ถูกต้อง',
            'teacherType.required' => 'กรุณาเลือกประเภทผู้สอน'
        ]);

        $teacher->gender = getGender($request->title);
        $teacher->type = $request->teacherType;
        $teacher->title = $request->title;
        $teacher->firstname = $request->firstname;
        $teacher->lastname = $request->lastname;
        $teacher->nickname = $request->nickname;
        $teacher->idcard = $request->idCard;
        $teacher->birthdate = formatDateToDB($request->birthdate);
        $teacher->address = $request->address;
        $teacher->district = $request->district;
        $teacher->amphoe = $request->amphoe;
        $teacher->province = $request->province;
        $teacher->phone_1 = $request->phone1;
        $teacher->phone_2 = $request->phone2;

        $teacher->save();

        // Log
        $description = "แก้ไขผู้สอน: ". $request->title.$request->firstname." ".$request->lastname;
        $this->LogController->log('การจัดการผู้สอน', 'แก้ไขข้อมูล', $description);

        return redirect()->route('teacher.index')->with('feedback','แก้ไขผู้สอนเรียบร้อย');
    }

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

        // Log
        $description = "ลบผู้สอน: ". $teacher->title.$teacher->fitsrname. " ".$teacher->lastname;
        $this->LogController->log('การจัดการผู้สอน', 'ลบข้อมูล', $description);

        return redirect()->route('teacher.index')->with('feedback','ลบข้อมูลผู้สอนเรียบร้อย');
    }

    public function withdraw(Request $request)
    {
        $request->validate([
            'method' => 'required',
            'payDate' => 'required|date_format:d/m/Y',
            'payTime' => 'required|date_format:H:i:s'
        ],[
            'method.required' => 'กรุณาเลือกวิธีจ่ายเงิน',
            'payDate.required' => 'กรุณากรอกวันที่จ่ายเงิน',
            'payDate.date_format:m/d/Y' => 'กรุณากรอกรูปแบบวันที่ให้ถูกต้อง',
            'payTime.required' => 'กรุณากรอกเวลาที่จ่ายเงิน',
            'payTime.date_format:H:i:s' => 'กรุณากรอกรูปแบบเวลาให้ถูกต้อง',
        ]);

        $withdraw = new Withdraw;
        $withdraw->teacher_id = $request->teacher;
        $withdraw->title = "ค่าสอน";
        $withdraw->amount = $request->amount;
        $withdraw->method = $request->method;
        $withdraw->date = formatDateToDB($request->payDate);
        $withdraw->time = $request->payTime;
        $withdraw->teach_date = $request->teachDate;
        $withdraw->save();

        // Log
        $description = "เพิ่มการเบิกเงินผู้สอน: ". $request->teacherName. ", จำนวน: ".$request->amount." บาท";
        $this->LogController->log('การจัดการผู้สอน', 'เพิ่มข้อมูล', $description);

        return redirect()->back()->with('feedback','บันทึกการเบิกเงินเรียบร้อย');
    }

    public function scan_index()
    {
        $scan_teacher_amount = Teacher::where('type', '=', 's')->orWhere('type', '=', 'a')->count();
        $dataArr = array();
        $teachers = array();
        for($t=7; $t<20; $t++) {
            $time = $t.':00:01';
            $scan_teacher = VehicleBooking::select('teacher_scan_id')->whereDate('date', '=', date('Y-m-d'))->whereRaw("('$time' BETWEEN starttime AND endtime)")->whereNotNull('teacher_scan_id')->get()->toArray();
            $amount = $scan_teacher_amount - count($scan_teacher);
            $time_txt = $t. ':00 - '. ($t+1) .':00 น.';
            $dataArr[] = ['time'=> $time_txt, 'amount'=>$amount];
            $teachers[] = Teacher::select('title', 'firstname', 'lastname', 'id')->where('type', '=', 's')->orWhere('type', '=', 'a')->whereNotIn('id', $scan_teacher)->orderBy('firstname')->get()->toArray();
        }
        return view('teacher.scan.index')->with([
            'page_title' => 'ครูสแกนว่าง',
            'data' => $dataArr,
            'teachers' => $teachers,
        ]);
    }

    public function checkout(Request $request)
    {
        $tmp = VehicleBooking::find($request->vbid);
        $tmp->checkout = '1';
        $tmp->save();

        return back()->with('feedback','สแกนครูผู้สอนเรียบร้อย');
    }
}
