<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Withdraw;
use App\Models\Teacher;
use App\Models\VehicleBooking;
use App\Http\Requests\WithdrawRequest;
use App\Models\Branch;
use Illuminate\Support\Facades\Gate;

class WithdrawController extends Controller
{
    protected $LogController;
    public function __construct(LogController $LogController)
    {
        $this->middleware('auth');
        $this->LogController = $LogController;
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $withdraws = Withdraw::select('teachers.*', 'teachers.title as ttitle', 'withdraws.*', 'withdraws.title as wtitle', 'branchs.name')
                                ->leftJoin('teachers', 'teachers.id', '=', 'withdraws.teacher_id')
                                ->leftJoin('branchs', 'branchs.id', '=', 'withdraws.branch_id')
                                ->whereMonth('date', '=', date('m'))
                                ->whereYear('date', '=', date('Y'))
                                ->get();
        $teachers = Teacher::where('is_active', '=', '1')->get();
        $branchs = Branch::where('is_active', '=', '1')->get();

        return view('withdraw.index')->with([
            'page_title' => 'รายการเบิกเงิน',
            'withdraws' => $withdraws,
            'date' => date('m/Y'),
            'teachers' => $teachers,
            'branchs' => $branchs,
        ]);
    }

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

        $tmp = explode('/', $request->date);
        $month = $tmp[0];
        $year = $tmp[1];
        $withdraws = Withdraw::select('teachers.*', 'teachers.title as ttitle', 'withdraws.*', 'withdraws.title as wtitle', 'branchs.name')
                                ->leftJoin('teachers', 'teachers.id', '=', 'withdraws.teacher_id')
                                ->leftJoin('branchs', 'branchs.id', '=', 'withdraws.branch_id')
                                ->whereMonth('date', '=', $month)
                                ->whereYear('date', '=', $year)
                                ->get();
        // $withdraws = Withdraw::where('date', '=', formatDateToDB($request->date))->get();
        $teachers = Teacher::where('is_active', '=', '1')->get();
        $branchs = Branch::where('is_active', '=', '1')->get();

        return view('withdraw.index')->with([
            'page_title' => 'รายการเบิกเงิน',
            'withdraws' => $withdraws,
            'date' => $month.'/'.$year,
            'teachers' => $teachers,
            'branchs' => $branchs,
        ]);
    }
    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Withdraw $withdraw)
    {
        $withdraw->delete();

        // Log
        $description = "ลบรายการเบิก: ". $withdraw->title. ' , จำนวน:'. $withdraw->amount .' บาท ของวันที่  '.formatDateFromDB($withdraw->date). ' เวลา '.$withdraw->time ;
        $this->LogController->log('รายการเบิก', 'ลบข้อมูล', $description);

        return redirect()->route('withdraw.index')->with('feedback','ลบข้อมูลรายการเบิกเรียบร้อย');
    }

    public function withdraw(WithdrawRequest $request)
    {
        if($request->wtype=="อื่นๆ") {
            $title = $request->wname;
            $teacher = $request->teacher;
        }
        if($request->wtype=="ค่าสอน"){
            $title = $request->wtype;
            $teacher = $request->teacher;
        }
        if($request->wtype=="ค่าน้ำมัน") {
            $title = $request->wtype;
            $teacher = $request->teacherOil;
        }
        $withdraw = new Withdraw;
        $withdraw->teacher_id = $teacher;
        $withdraw->title = $title;
        $withdraw->amount = $request->amount;
        $withdraw->method = $request->method;
        $withdraw->date = formatDateToDB($request->payDate);
        $withdraw->time = $request->payTime;
        $withdraw->branch_id = $request->branch;

        if($request->teachDate!="") {
            $date = explode('-', $request->teachDate);
            $tmp = $date[1].'-'.$date[0].'-01';
            $date = date("Y-m-t", strtotime($tmp));
            $withdraw->teach_date = $date;
        }
        $withdraw->save();

        $description = "เพิ่มรายการเบิก:". $request->wtype. ", จำนวน:". $request->amount. ", เวลา:".$request->payDate." ".$request->payTime;
        $this->LogController->log('รายการเบิกเงิน', 'เพิ่มข้อมูล', $description);

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

    public function checkTeacher($date)
    {
        $tmp = explode('-', $date);
        $month = $tmp[0];
        $year = $tmp[1];

        $withdraw = Withdraw::select('teacher_id')->whereMonth('teach_date', '=', $month)->whereYear('teach_date', '=', $year)->where('title', '=', 'ค่าสอน')->get();
        $teachers = VehicleBooking::leftJoin('teachers', 'teachers.id', '=', 'vehicle_bookings.teacher_id')
                                    ->whereMonth('date', '=', $month)
                                    ->whereYear('date', '=', $year)
                                    ->where('is_active', '=', '1')
                                    ->whereNotIn('teachers.id', $withdraw)
                                    ->groupBy('teachers.id')
                                    ->get();
        $moduleData['data'] = $teachers;
        echo json_encode($moduleData);
        exit;

        // $teachers = VehicleBooking::leftJoin('teachers', 'teachers.id', '=', 'vehicle_bookings.teacher_id')->where('date', '=', $date)->where('is_active', '=', '1')->groupBy('teachers.id')->get();
        // $moduleData['data'] = $teachers;
        // echo json_encode($moduleData);
        // exit;
    }

    public function checkTeacherEarn($teacherID, $date)
    {
        $tmp = explode('-', $date);
        $month = $tmp[0];
        $year = $tmp[1];

        $amount = VehicleBooking::selectRaw('sum(teacher_earn) as total')
                                    ->where('teacher_id', '=', $teacherID)
                                    ->whereMonth('date', '=', $month)
                                    ->whereYear('date', '=', $year)
                                    ->groupBy('teacher_id')
                                    ->first();
        $moduleData['data'] = $amount;
        echo json_encode($moduleData);
        exit;
    }
}
