<?php

namespace App\Http\Controllers;

use App\Models\City;
use App\Models\Company;
use App\Models\Dossier;
use App\Models\Garage;
use App\Models\Guarantee;
use App\Models\Permission;
use App\Models\Role;
use App\Models\Step;
use App\Models\Substitute;
use App\Models\TypeDocument;
use App\Models\TypeExpertise;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $this->authorize('viewAny', App\Models\User::class);

        $users = User::with('role')->get();
        return view('configuration.user.index', compact('users'));
    }

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

        $cities = City::all();
        $roles = Role::all();
        return view('configuration.user.create', compact('cities', 'roles'));
    }

    public function profile()
    {
        $user = User::whereId(Auth::user()->id)->firstOrFail();
        return view('configuration.user.profile', compact('user'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->authorize('create', App\Models\User::class);

        $request->validate([
            'name' => 'required',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|min:6',
            'civility' => 'required',
            'role' => 'required',
            'city' => 'required',
            'email_pro' => 'email|nullable',
            'password_pro' => 'min:6|nullable'
        ]);
        if ($request->controler === "on") {
            $check = 1;
        } else {
            $check = 0;
        }

        User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'role_id' => $request->role,
            'city_id' => $request->city,
            'civility' => $request->civility,
            'controler' => $check,
            'email_pro' => $request->email_pro,
            'password_pro' => $request->password_pro,
        ]);

        return redirect()->route('user.index');
    }

    public function typedocument(Request $request , $id)
    {
        $this->authorize('update', App\Models\User::class);
        $user = User::whereId($id)->with('role', 'typedocument')->firstOrFail();
        if($user->role_id != 5){
            return redirect()->route('user.index')->with('error','Vous n etes pas un agent');
        }

        if ($request->has('type')) {
            $user->typedocument()->detach();
            foreach ($request->type as $p) {
             $type = TypeDocument::findOrFail($p);
                $user->typedocument()->syncWithoutDetaching($type);
             }
        }
        else{
            $user->typedocument()->detach();
        }

        return redirect()->route('user.index');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $this->authorize('view', App\Models\User::class);

        $user = User::whereId($id)->with('role', 'role.permission', 'city', 'permission', 'company', 'typeexpertise', 'guarantee','typecompany.usertypes')->firstOrFail();
        $permissions = Permission::all();
        $companies = Company::all();
        $types = TypeExpertise::all();
        $guarantees = Guarantee::all();
        $typedocs = TypeDocument::where('is_pdf',false)->get();
        $garages = Garage::all();
        // $dd = DB::select(DB::raw('select distinct ds.status, count(distinct s.dossier_id) as nbr from  step_dossier s
        // join dossiers d on s.dossier_id = d.id
        // join dossier_statuses ds on d.dossier_status_id = ds.id
        // where s.user_id = 9  group by ds.status'));
        // dd($dd);

        return view('configuration.user.show', compact('user', 'permissions', 'companies', 'types', 'guarantees','typedocs','garages'));

    }

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

        $cities = City::all();
        $roles = Role::all();
        $user = User::whereId($id)->with('role', 'city')->firstOrFail();
        return view('configuration.user.edit', compact('user', 'cities', 'roles'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->authorize('update', App\Models\User::class);

        $request->validate([
            'email' => 'required|email|unique:users,email,' . $id,
            'civility' => 'required',
            'role' => 'required',
            'city' => 'required',
            'name' => 'required',
            'password' => 'min:6||nullable',
            'email_pro' => 'email||nullable',
            'password_pro' => 'min:6||nullable'
        ]);

        $user = User::whereId($id)->firstOrFail();
        if ($user->role_id != 4) {
            if ($request->controler === "on") {
                $check = 1;
            } else {
                $check = 0;
            }
        } else {
            $check = 0;
        }

        $user->name = $request->name;
        $user->email = $request->email;
        $user->role_id = $request->role;
        if ($request->password) {
            $user->password =  Hash::make($request->password);
        }
        $user->city_id = $request->city;
        $user->civility = $request->civility;
        $user->controler = $check;
        $user->email_pro = $request->email_pro;
        $user->password_pro = $request->password_pro;
        $user->update();

        return redirect()->route('user.index');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $this->authorize('delete', App\Models\User::class);

        $user = User::whereId($id)->with('substitute')->firstOrFail();
        if (!$user->substitute) {
            return redirect()->route('Substitute.show', $id);
        }

        $sub = Substitute::where('user_id', $id)->firstOrFail();
        $dossiers = Dossier::where('dossier_status_id', 2)
            ->whereHas('step', function ($query) use ($id) {
                $query->where('user_id', $id);
            })->get();

        $step = Step::whereId(17)->firstOrFail();
        foreach ($dossiers as $dossier) {
            $dossier->step()->attach($step, ['user_id' => $sub->substitute_id]);
        }

        $user->delete();
        return redirect()->route('user.index');
    }

    public function trash()
    {
        $this->authorize('delete', App\Models\User::class);

        $users = User::onlyTrashed()->get();
        // dd($users);

        return view('configuration.user.trash', compact('users'));
    }

    public function restore($id)
    {
        $this->authorize('delete', App\Models\User::class);

        User::withTrashed()->find($id)->restore();
        return redirect()->route('user.index');
    }

    public function AsignToCompany($id)
    {
        $user = User::findOrFail($id);

        return redirect()->route('user.index');
    }

    public function AsignToExpertise($id)
    {
        $user = User::findOrFail($id);

        return redirect()->route('user.index');
    }

    public function password(Request $request)
    {
        $request->validate([
            'password'=>'min:6|required'
        ]);
        $user = User::findOrFail(Auth::user()->id);
        $user->password = Hash::make($request->password);
        $user->update();
        return redirect()->route('home')->with('success','Mot de passe modifier avec Succés');
    }

}
