<?php

namespace App\Http\Controllers;

use App\Models\Vehicle;
use App\Models\Province;
use App\Models\Enroll;
use App\Models\VehicleBooking;
use Illuminate\Http\Request;
use \App\Http\Requests\StoreVehicleRequest;
use \App\Http\Requests\UpdateVehicleRequest;
use Illuminate\Support\Facades\Gate;

class VehicleController 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()
    {

        // $sTime = "09:00:01";
        // $eTime = "11:59:59";
        // $date = "2020-10-25";
        // $booking = VehicleBooking::select('vehicle_id')
        //                             ->where('date', '=', $date)
        //                             ->where('drive','=','ขับ')
        //                             ->where(function($query) use ($sTime, $eTime){
        //                                 $query->whereBetween('starttime', [$sTime, $eTime])->orWhereBetween('endtime', [$sTime, $eTime]);
        //                             })
        //                             ->get();
        // $cars = Vehicle::where('gear', '=', 'ออโต้')->whereNotIn('id', $booking)->orderBy('id')->get();

        if (Gate::allows('isSuperadmin')) {
            $vehicles = Vehicle::where('is_active', '=', '1')->orderBy('type', 'desc')->orderBy('number','asc')->get();
        } else {
            $branch = auth()->user()->branch_id;
            $vehicles = Vehicle::where('is_active', '=', '1')->where('branch_id', '=', $branch)->orWhereNull('branch_id')->orderBy('type', 'desc')->orderBy('number','asc')->get();
        }

        return view('vehicle.index')->with([
            'page_title' => 'การจัดการยานพาหนะ',
            'vehicles' => $vehicles,
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $carNo = Vehicle::select('number')->where('type', '=', 'รถยนต์')->orderBy('number','desc')->first();
        $motobikeNo = Vehicle::select('number')->where('type', '=', 'รถจักรยานยนต์')->orderBy('number','desc')->first();
        if($carNo) {
            $carNo = $carNo->number;
            $carNo = $carNo + 1;
        } else {
            $carNo = '1';
        }
        if($motobikeNo) {
            $motobikeNo = $motobikeNo->number;
            $motobikeNo = $motobikeNo + 1;
        } else {
            $motobikeNo = '1';
        }

        $provinces = Province::orderBy('name')->get();
        return view('vehicle.create')->with([
            'page_title' => 'เพิ่มยานพาหนะ',
            'provinces' => $provinces,
            'car_no' => $carNo,
            'motobike_no' => $motobikeNo
        ]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(StoreVehicleRequest $request)
    {
        $vehicle = new Vehicle;
        $vehicle->number = $request->vehicleNo;
        $vehicle->type = $request->type;
        $vehicle->gear = $request->gear;
        $vehicle->brand = strip_tags($request->brand);
        $vehicle->model = strip_tags($request->model);
        $vehicle->body_serial = strip_tags($request->bodySerial);
        $vehicle->engine_serial = strip_tags($request->engineSerial);
        $vehicle->registration_class = strip_tags($request->registrationClass);
        $vehicle->registration_number = strip_tags($request->registrationNum);
        $vehicle->province = $request->province;
        $vehicle->characteristic = strip_tags($request->characteristic);
        $vehicle->tax_expire = formatDateToDB(strip_tags($request->taxExpire));

        $vehicle->save();

        // Log
        $description = "เพิ่มยานพาหนะ: ". strip_tags($request->brand)." ".strip_tags($request->model). ", ทะเบียน: ". strip_tags($request->registrationClass)." ".strip_tags($request->registrationNum);
        $this->LogController->log('การจัดการยานพาหนะ', 'เพิ่มข้อมูล', $description);

        return redirect()->route('vehicle.index')->with('feedback','เพิ่มยานพาหนะเรียบร้อย');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Vehicle  $vehicle
     * @return \Illuminate\Http\Response
     */
    public function show(Vehicle $vehicle)
    {
        $vehicle = Vehicle::where('id', '=', $vehicle->id)->first();
        return view('vehicle.show')->with([
            'page_title' => 'ข้อมูลยานพาหนะ',
            'vehicle' => $vehicle,
        ]);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Vehicle  $vehicle
     * @return \Illuminate\Http\Response
     */
    public function edit(Vehicle $vehicle)
    {
        $provinces = Province::orderBy('name')->get();
        return view('vehicle.edit', [
            'page_title' => 'แก้ไขยานพาหนะ',
            'vehicle' => $vehicle,
            'provinces' => $provinces
        ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Vehicle  $vehicle
     * @return \Illuminate\Http\Response
     */
    public function update(UpdateVehicleRequest $request, Vehicle $vehicle)
    {
        $vehicle->type = $request->type;
        $vehicle->gear = $request->gear;
        $vehicle->brand = strip_tags($request->brand);
        $vehicle->model = strip_tags($request->model);
        $vehicle->body_serial = strip_tags($request->bodySerial);
        $vehicle->engine_serial = strip_tags($request->engineSerial);
        $vehicle->registration_class = strip_tags($request->registrationClass);
        $vehicle->registration_number = strip_tags($request->registrationNum);
        $vehicle->province = $request->province;
        $vehicle->characteristic = strip_tags($request->characteristic);
        $vehicle->tax_expire = formatDateToDB(strip_tags($request->taxExpire));

        $vehicle->save();

        // Log
        $description = "แก้ไขยานพาหนะ: ". strip_tags($request->brand)." ".strip_tags($request->model). ", ทะเบียน: ". strip_tags($request->registrationClass)." ".strip_tags($request->registrationNum);
        $this->LogController->log('การจัดการยานพาหนะ', 'แก้ไขข้อมูล', $description);

        return redirect()->route('vehicle.index')->with('feedback','แก้ไขยานพาหนะเรียบร้อย');
    }

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

        // Log
        $description = "ลบยานพาหนะ: ". strip_tags($vehicle->brand)." ".strip_tags($vehicle->model). ", ทะเบียน: ". strip_tags($vehicle->registrationClass)." ".strip_tags($vehicle->registrationNum);
        $this->LogController->log('การจัดการยานพาหนะ', 'ลบข้อมูล', $description);

        return redirect()->route('vehicle.index')->with('feedback','ลบข้อมูลยานพาหนะเรียบร้อย');
    }

    public function checkVehicleAvailable($type, $gear, $date, $starttime, $endtime, $drive, $purpose, $category)
    {
        $sTime = $starttime . ":00:01";
        $eTime = explode(":", $endtime);
        $eTime = ($eTime[0]-1) . ":59:59";
        // $category ==> 0 = create, if >0 = edit
        //if($category == '0') {   // For create student booking
        $booking = VehicleBooking::select('vehicle_id')
            ->where('date', '=', $date)
            ->where('drive','=', $drive)
            ->whereRaw("(('$sTime' BETWEEN starttime AND endtime) or ('$eTime' BETWEEN starttime AND endtime))")
            ->groupBy('vehicle_id')
            ->pluck('vehicle_id')->toArray();
        // } else { // for edit student booking
        //     $booking = VehicleBooking::select('vehicle_id')
        //                             ->where('date', '=', $date)
        //                             ->where('drive','=', $drive)
        //                             ->whereRaw("(('$sTime' BETWEEN starttime AND endtime) or ('$eTime' BETWEEN starttime AND endtime))")
        //                             ->where('id', '!=', $category)
        //                             ->get()->toArray();
        // }
        $booking = array_unique($booking);

        // if(($purpose == 'เรียนและสอบ' || $purpose == 'เก็บชั่วโมงเพื่อสอบ') && $drive == 'ไม่ขับ') {
        if($drive == 'ไม่ขับ') {
            $tmp = VehicleBooking::selectRaw('vehicle_id, count(*) as amount')
                                    ->where('date', '=', $date)
                                    ->where('drive', '=', $drive)
                                    ->where('starttime', '=', $starttime.":00:00")
                                    ->where('endtime', '=', $endtime.":00")
                                    ->groupBy('vehicle_id')->get();
            for($i=0; $i<count($tmp); $i++){

                if($tmp[$i]['amount'] < 5) {
                    $pos = array_search($tmp[$i]['vehicle_id'], $booking);
                    unset($booking[$pos]);
                }
            }
        }

            // $input = array_map('intval', $booking); // map value in array to int
            // $output = array();
            // foreach(array_count_values($input) as $value => $count){
            //     if($count > 4) // เรียน module 1 (เรียนและสอบ) ได้ 5 คนในเวลาเดียวกัน
            //     {
            //         $output[] = $value;
            //     }
            // }
            // $booking = $output;
        // } else {
        //     $tmp = array();
        //     for($i=0; $i<count($booking); $i++) {
        //         array_push($tmp, $booking[$i]['vehicle_id']);
        //     }
        //     $booking = $tmp;
        // }

        $br_id = auth()->user()->branch_id;
        $vehicles = Vehicle::where('gear', '=', $gear)
                            ->where('type', '=', $type)
                            ->whereRaw("(branch_id = '$br_id' or branch_id is null)")
                            ->whereNotIn('id', $booking)->orderBy('id')->get();

        $vehicleData['data'] = $vehicles;
        echo json_encode($vehicleData);
        exit;
    }

}
