<?php

namespace App\Http\Controllers;

use App\Models\Docente;
use App\Models\Role;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Illuminate\Auth\Notifications\ResetPassword;

class DocenteController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {

    $user = Auth::user();
    $plantelesIds = $user->plantelUsuarios->pluck('id');

    $docentes = Docente::with(['docentes.plantelUsuarios', 'docentes.roles'])
        ->whereHas('docentes', function($query) use ($plantelesIds) {
            $query->whereHas('plantelUsuarios', function($q) use ($plantelesIds) {
                $q->whereIn('plantels.id', $plantelesIds);
            });
        })
        ->get();

    return view('Docente.index', compact('docentes'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $user = Auth::user();
        $roles = Role::where('name','Docente')->get();
        $plantels = $user->plantelUsuarios;
        return view('Docente.create',compact(['plantels','roles']));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
         if (User::where('email', $request->email)
        ->orWhere('telefono', $request->telefono)
        ->exists()) {

            return redirect()->route('docente.create')->with('warn','Ya se encuentra registrado el número de teléfono o correo electrónico, porfavor cambialos')->withInput();
        }

        if ($request->plantel ==0) {
            return redirect()->route('docente.create')->with('warn','Selecciona el campus')->withInput();
        }

        if ($request->rol ==0) {
            return redirect()->route('docente.create')->with('warn','Selecciona el rol')->withInput();
        }

        $passwordTemporal = Str::random(12);

        $user = User::create([
            'name' => mb_strtoupper($request->name, 'UTF-8'),
            'apellidoPaterno' => mb_strtoupper($request->apellidoPaterno, 'UTF-8'),
            'apellidoMaterno' => mb_strtoupper($request->apellidoMaterno, 'UTF-8'),
            'email'     => $request->email,
            'telefono'  => $request->telefono,
            'direccion' => $request->direccion,
            'password'  => Hash::make($passwordTemporal),
            'status' => $request->status
        ]);

        $user->roles()->sync($request->rol);
        $user->plantelUsuarios()->sync([$request->plantel]);

        $token = Password::createToken($user);
        $user->notify(new ResetPassword($token));

        $docente = Docente::create([
            'usuario_registro' => Auth::id(),
            'status'            => $request->status,
        ]);

        $docente->docentes()->sync([$user->id]);

        return redirect()->route('docente.edit',compact('docente'))->with('info','Se creó el docente correctamente');

    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Docente $docente)
    {
        $user = Auth::user();
        $roles = Role::where('name', 'Docente')->get();
        $plantels = $user->plantelUsuarios;
        $usr = $docente->docentes->first();

        return view('Docente.edit', compact(['docente', 'plantels', 'roles', 'usr']));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Docente $docente)
    {
           $user = $docente->docentes->first();

            $docente->grupos()->detach();

            $docente->docentes()->detach();

            $docente->delete();

            if ($user) {
                $user->roles()->detach();
                $user->plantelUsuarios()->detach();
                $user->delete();
            }

            session()->flash('swal', [
                'icon'  => 'success',
                'title' => 'Eliminado!',
                'text'  => 'Se ha eliminado el registro correctamente'
            ]);

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