<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Alpr;
use App\Device_Group;

class AlprController extends Controller
{
    //
    public function index(){
//        ->get('No','Plate_Number','Car_Type','Point_A_Enter_DateTime','Speed','Location','Speed_Limit','Prohibited_Vehicles','Violation','Case_Number','Point_A_Image_Path','Point_B_Image_Path','Status');
        $alpr=Alpr::where("Status","待審核")->paginate(10);
        foreach ($alpr as $al) {
            $al->Speed=round($al->Speed,1);
        }
        $Dgs=Device_Group::all('Group_Name');
        return view('plates')->with(["Alprs"=>$alpr,"Dgs"=>$Dgs]);
    }

    public function select(Request $request){
        $alpr=Alpr :: where('Point_A_Enter_DateTime','>=',$request->start_time)->where('Point_A_Enter_DateTime','<=',$request->end_time);
//        $alpr=Alpr :: where('Plate_Number','8503-LX')->get();
        if ($alpr->get()->isEmpty()){
            $meg = "該時段沒有資料";
            return redirect()->route('plates');
        }
        if($request->Plate_Number != null)
            $alpr=$alpr->where("Plate_Number",$request->Plate_Number);
        if($request->Car_Type != null)
            $alpr=$alpr->where("Car_Type",$request->Car_Type);
        if($request->Group_Name != null)
            $alpr=$alpr->where("Location",$request->Group_Name);
        if($request->Violation != null)
            $alpr=$alpr->where("Violation",$request->Violation);
        if($request->Case_Number != null)
            $alpr=$alpr->where("Case_Number",$request->Case_Number);
        if($request->Status != null){
            $alpr=$alpr->where("Status",$request->Status);
        }

        $alpr=$alpr->paginate(10);
        if($alpr->isEmpty()){
            $meg = "查無資料";
            return redirect()->route('plates');
        }
        foreach ($alpr as $al) {
            $al->Speed=round($al->Speed,1);
        }
        $Dgs=Device_Group::all('Group_Name');
        return view('plates')->with(["Alprs"=>$alpr,"Dgs"=>$Dgs]);
    }
    public function update(Request $request){
        $plate=$request->Plate_Number;
        $status=$request->Status;     // 待審核 已告發 已註銷  3種選項
        try{
            $alpr=Alpr ::where("No",$request->No);
            $alpr->update([
                "Plate_Number"=>$plate,
                "Status"=>$status,
            ]);
        }
        catch (Exception $e){
            $erro_meg="修改失敗";
//            $e->getMessage(); 真正錯誤原因
            return back()->withError($erro_meg)->withInput();
        }
        return redirect()->route('plates');
    }
    public function delete(Request $request){
        try{
            $alpr=Alpr ::where("No",$request->No);
            $alpr->update(["Status"=>"已註銷"]);
        }
        catch (Exception $e){
            $erro_meg="註銷失敗";
            //$e->getMessage(); 真正錯誤原因
            return back()->withError($erro_meg)->withInput();
        }
        return redirect()->route('plates');
    }
}
