<?php

namespace App\Http\Controllers;

use App\Models\Dossier;
use App\Models\Garage;
use App\Models\Location;
use App\Models\Meeting;
use App\Models\MeetingStatus;
use App\Models\Notification;
use App\Models\Observation;
use App\Models\Step;
use App\Models\TypeObservation;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

use function PHPSTORM_META\map;

class MeetingController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index($id)
    {
        $this->authorize('viewAny', Meeting::class);
        $dossier = Dossier::whereId($id)->firstOrFail();
        $this->authorize('view', $dossier);
        $check = Dossier::whereId($id)->whereHas('meeting', function ($query) {
            $query->where('meeting_status_id', 2);
        })->first();
        // if (Auth::user()->role_id == 4) {
        $meetings = Meeting::with(['user', 'dossier', 'meetingstatus', 'garage'])->where('dossier_id', $id)->get();
        // } else {
        //     $meetings = Meeting::with(['user', 'dossier', 'meetingstatus', 'garage'])->where('dossier_id', $id)->where('meeting_status_id', '=', '2')->get();
        // }
        return view('configuration.meeting.index', compact('meetings', 'id', 'check'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create($id)
    {
        $this->authorize('create', Meeting::class);

        $dossier = Dossier::whereId($id)->firstOrFail();

        if ($dossier->update != 0 && Auth::user()->role_id != 4 ||  $dossier->dossier_status_id == 3 && Auth::user()->role_id != 4) {
            return redirect()->route('Dossier.show', $dossier->id)->with('error', 'Dossier est interdit de le modifier Envoyer une demande a Admin ');
        }
        // $step = DB::table('step_dossier')
        //     ->where('dossier_id', $dossier->id)
        //     ->latest()->first();
        // if (Auth::user()->id != $step->user_id) {
        //     return redirect()->route('Dossier.show', $dossier->id)->with('error', 'Vous avez pas le droit de apporter des modification a ce dossier maintenant');
        // }
        $users = User::where('role_id', 5)->get();
        $meetings = Meeting::where('date', Carbon::today())->where('meeting_status_id', 2)->with('user')->get();
        $garages = Garage::all();
        $steps = Step::whereIn('id', [2, 5, 10])->get();
        $markers = Garage::select('libelle', 'lat', 'lng')->get()->toArray();
        $agents = Location::with('user')->get()->toArray();
        // dd($agents);
        return view('configuration.meeting.create', compact('users', 'steps', 'garages', 'markers', 'agents', 'id', 'meetings'));
    }

    public function search($user_id)
    {
        $meetings = Meeting::where('user_id', $user_id)->where('date', '>=', Carbon::today())->with('user', 'dossier', 'garage', 'meetingstatus')->get();
        return response()->json($meetings);
    }

    public function searching($garage_id)
    {
        $garages = Garage::whereId($garage_id)->get();
        // $agents = [
        //     [
        //         "agent" => "walid",
        //         "lat" => 33.45962677614,
        //         "lng" => -7.6016313897823
        //     ],
        //     [
        //         "agent" => "youssef",
        //         "lat" => 33.40962677614,
        //         "lng" => -7.6016313897823
        //     ],

        // ];
        $agents = Location::with('user')->get()->toArray();

        return response()->json(array(
            $garages, $agents
        ));
    }
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->authorize('create', Meeting::class);

        $dossier = Dossier::whereId($request->dossier_id)->firstOrFail();
        if ($dossier->update != 0 && Auth::user()->role_id != 4 ||  $dossier->dossier_status_id == 3 && Auth::user()->role_id != 4) {
            return redirect()->route('Dossier.show', $dossier->id)->with('error', 'Dossier est interdit de le modifier Envoyer une demande a Admin ');
        }
        $meetingcount = Meeting::where('dossier_id',$dossier->id)->where('meeting_status_id',2)->count();
        if($meetingcount > 1){
            return redirect()->route('Dossier.show',$dossier->id)->with('error','Meeting deja encours');
        }

        // $step = DB::table('step_dossier')
        //     ->where('dossier_id', $dossier->id)
        //     ->latest()->first();

        // if (Auth::user()->id != $step->user_id) {
        //     return redirect()->route('Dossier.show', $dossier->id)->with('error', 'Vous avez pas le droit de apporter des modification a ce dossier maintenant');
        // }

        $request->validate([
            'user' => 'required',
            'date' => 'required|date',
            'start' => 'required|date_format:H:i',
            'type' => 'required',
            'adress' => 'required'
        ]);
        $meeting = Meeting::create([
            'dossier_id' => $request->dossier_id,
            'user_id' => $request->user,
            'garage_id' => $request->garage_id,
            'start' => $request->start,
            'lat' => $request->lat,
            'lng' => $request->lng,
            'type' => $request->type,
            'assure' => $request->assure,
            'meeting_status_id' => 2,
            'date' => $request->date,
            'adress' => $request->adress
        ]);
        if (!empty($request->observation)) {
            Observation::create([
                'observation' => $request->observation,
                'user_id' => Auth::user()->id,
                'dossier_id' => $request->dossier_id,
            ]);
        }
        $j = 0;
        if ($request->type == 2) {
            $j = 2;
        }
        if ($request->type == 5) {
            $j = 6;
        }
        if ($request->type == 10) {
            $j = 7;
        }
        $step = Step::whereId($j)->firstOrFail();
        $dossier->step_id = $step->id;
        $dossier->update();


        $dossier->step()->attach($step, ['user_id' => $meeting->user_id]);
        \App\Services\SidebarCache::clear();
        return redirect()->route('Meeting.index', ['id' => $dossier->id]);
    }
    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Meeting  $meeting
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $this->authorize('view', Meeting::class);

        $meeting = Meeting::whereId($id)->with('garage', 'user', 'meetingstatus')->first();
        $status = MeetingStatus::whereId(1)->firstOrFail();
        $agents = [
            "agent" => "walid",
            "lat" => 33.45962677614,
            "lng" => -7.6016313897823
        ];
        if ($meeting->garage) {
            $markers = [
                'lat' => $meeting->garage->lat,
                'lng' => $meeting->garage->lng,
                'libelle' => $meeting->garage->libelle,
            ];
        } elseif ($meeting->lat) {
            $markers = [
                'lat' => $meeting->lat,
                'lng' => $meeting->lng,
                'libelle' => "",
            ];
        } else {
            $markers = [];
        }

        $observations = Observation::where('dossier_id', $meeting->dossier_id)->get();

        return view('configuration.meeting.show', compact('meeting', 'agents', 'markers', 'observations', 'status'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Meeting  $meeting
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $this->authorize('update', Meeting::class);

        $meeting = Meeting::whereId($id)->with('user')->firstOrFail();
        $dossier = Dossier::whereId($meeting->dossier_id)->firstOrFail();
        if ($dossier->update != 0 && Auth::user()->role_id != 4 ||  $dossier->dossier_status_id == 3 && Auth::user()->role_id != 4) {
            return redirect()->route('Dossier.show', $dossier->id)->with('error', 'Dossier est interdit de le modifier Envoyer une demande a Admin ');
        }
        // $step = DB::table('step_dossier')
        //     ->where('dossier_id', $dossier->id)
        //     ->latest()->first();

        // if (Auth::user()->id != $step->user_id) {
        //     return redirect()->route('Dossier.show', $dossier->id)->with('error', 'Vous avez pas le droit de apporter des modification a ce dossier maintenant');
        // }
        // if ($dossier->update) {
        //     return redirect()->route('Dossier.show', $dossier->id)->with('error', 'Dossier est interdit de le modifier Envoyer une demande a Admin ');
        // }
        return view('configuration.meeting.show');
    }

    public function status(Request $request, $id)
    {
        $this->authorize('annuler', Meeting::class);

        $request->validate([
            'observation' => 'required',
        ]);

        $meeting = Meeting::whereId($id)->with('user')->firstOrFail();
        $dossier = Dossier::whereId($meeting->dossier_id)->firstOrFail();
        if ($dossier->update != 0 && Auth::user()->role_id != 4 ||  $dossier->dossier_status_id == 3 && Auth::user()->role_id != 4) {
            return redirect()->route('Dossier.show', $dossier->id)->with('error', 'Dossier est interdit de le modifier Envoyer une demande a Admin ');
        }
        $meeting->meeting_status_id = 1;
        $meeting->update();

        Observation::create([
            'observation' => $request->observation,
            'dossier_id' => $meeting->dossier_id,
            'user_id' => Auth::user()->id
        ]);
        
        \App\Services\SidebarCache::clear();

        return redirect()->route('Dossier.show', $meeting->dossier_id)->with('Success', 'Meeting Annuler');
    }

    public function editing($id)
    {
        $this->authorize('update', Meeting::class);
        $meeting = Meeting::whereId($id)->with('user', 'garage')->first();
        if ($meeting->meeting_status_id != 2) {
            return redirect()->back()->with('error', 'Meeting ne peut pas étre modifier');
        }
        $meetings = Meeting::where('date', '>=', Carbon::today())->where('meeting_status_id', 2)->with('user')->get();
        $markers = Garage::select('libelle', 'lat', 'lng')->get()->toArray();
        $agents = Location::with('user')->get()->toArray();
        $users = User::where('role_id', 5)->whereNot('id', $meeting->user_id)->get();
        $garages = Garage::whereNot('id', $meeting->garage_id)->get();
        return view('configuration.meeting.editing', compact('meeting', 'meetings', 'users', 'garages', 'markers', 'agents'));
    }
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Meeting  $meeting
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->authorize('update', Meeting::class);

        $request->validate([
            'user' => 'required',
            'date' => 'required|date',
            'start' => 'required',
            'type' => 'required',
            'adress' => 'required'
        ]);
        $meeting = Meeting::whereId($id)->with('user', 'garage')->firstOrFail();
        $dossier = Dossier::whereId($meeting->dossier_id)->firstOrFail();
        if ($dossier->update != 0 && Auth::user()->role_id != 4 ||  $dossier->dossier_status_id == 3 && Auth::user()->role_id != 4) {
            return redirect()->route('Dossier.show', $dossier->id)->with('error', 'Dossier est interdit de le modifier Envoyer une demande a Admin ');
        }
        $meeting->user_id = $request->user;
        $meeting->date = $request->date;
        $meeting->start = $request->start;
        $meeting->type = $request->type;
        $meeting->assure = $request->assure;
        $meeting->adress = $request->adress;
        $meeting->garage_id = $request->garage_id;
        $meeting->lat = $request->lat;
        $meeting->lng = $request->lng;
        $meeting->update();
        \App\Services\SidebarCache::clear();
        return redirect()->route('Meeting.index', $meeting->dossier_id);
    }

    // public function historique(Request $request){

    //     $meet = Meeting::with('user','dossier','meetingstatus')->->get();

    // }

    public function historique(Request $request)
    {

        $this->authorize('viewAny', Meeting::class);


        $meetings = Meeting::with('user', 'dossier')->when($request->user, function ($q) use ($request) {
            return $q->where('user_id', $request->user);
        })->when($request->status_id, function ($q) use ($request) {
            return $q->where('meeting_status_id', $request->status_id);
        })
            ->when([$request->datedebut, $request->datefin], function ($q) use ($request) {
                return $q->whereBetween('date', [$request->datedebut, $request->datefin]);
            })->get();

        $users = User::where('role_id', 5)->get();
        $statuses = MeetingStatus::all();

        return view('configuration.meeting.historique', compact('meetings', 'users', 'statuses'));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Meeting  $meeting
     * @return \Illuminate\Http\Response
     */
    public function destroy(Meeting $meeting)
    {
        //
    }
}
