<?php

namespace App\Http\Controllers;

use App\Models\Alumno;
use App\Models\AreaCode;
use App\Models\Docente;
use App\Models\Plantel;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use App\Models\Role;
use Illuminate\Auth\Notifications\ResetPassword;

class UserController extends Controller
{

    public function __construct() {
        $this->middleware('can:user.index')->only('index','show');
        $this->middleware('can:user.create')->only('create','store');
        $this->middleware('can:user.edit')->only('edit','update');
        $this->middleware('can:user.destroy')->only('destroy');
    }

    public function index()
    {
        $users=User::with(['roles','plantelUsuarios'])->get();
        return view('user.index',compact('users'));
    }


    public function create()
    {
        $plantels = Plantel::where('status','=','1')->get();
        $codigos = AreaCode::all();
        $roles= Role::all();
        return view('user.create',compact('roles','plantels','codigos'));
    }

    public function store(Request $request)
    {
        $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 ?? null,
            'direccion' => $request->direccion ?? null,
            'code' => $request->code ?? null,
            'status' => $request->status,
            'password' => Hash::make($passwordTemporal),
        ]);

        $user->roles()->sync($request->roles);

        $user->plantelUsuarios()->sync($request->plantels);

        $this->syncAlumnoDocente($user, $request->roles ?? []);

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

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

    public function show(User $user)
    {
        return view('user.show',compact('user'));
    }

    public function edit(User $user)
    {
        $plantels=Plantel::all();
        $codigos = AreaCode::all();
        $roles= Role::all();
        return view('user.edit',compact('user','roles','plantels','codigos'));
    }

    public function update(Request $request, User $user)
    {
        $user->update($request->except(['plantels']));
        $user->roles()->sync($request->roles);
        $user->plantelUsuarios()->sync($request->plantels);
        $this->syncAlumnoDocente($user, $request->roles ?? []);
        return redirect()->route('user.edit',compact('user'))->with('info','Se modifico el usuario correctamente');
    }


    public function destroy(User $user)
    {
        $this->detachAlumnoDocente($user);
        $user->plantelUsuarios()->detach();
        $user->roles()->detach();
        $user->delete();
        session()->flash('swal',[
            'icon'=>'success',
            'title'=>'Eliminado!',
            'text'=>'Se ha eliminado el registro correctamente'
        ]);
        return redirect()->route('user.index');
    }

    public function profile(){
        return view('profile.show');
    }

    private function syncAlumnoDocente(User $user, array $roleIds): void
    {
        $roleNames = Role::whereIn('id', $roleIds)->pluck('name')->toArray();

        // ── Alumno ──────────────────────────────────────────────────
        if (in_array('Alumno', $roleNames)) {
            $alumno = Alumno::whereHas('alumnos', fn($q) => $q->where('id', $user->id))->first();

            if (!$alumno) {
                $alumno = Alumno::create([
                    'nivel'            => 0,
                    'plan_id'          => 0,
                    'ciclo'            => 0,
                    'turno'            => 0,
                    'medio'            => 0,
                    'usuario_registro' => Auth::id(),
                ]);
            }

            $alumno->alumnos()->syncWithoutDetaching([$user->id]);
        } else {
            $this->detachFromAlumno($user);
        }

        // ── Docente ─────────────────────────────────────────────────
        if (in_array('Docente', $roleNames)) {
            $docente = Docente::whereHas('docentes', fn($q) => $q->where('id', $user->id))->first();

            if (!$docente) {
                $docente = Docente::create([
                    'usuario_registro' => Auth::id(),
                    'status'           => 1,
                ]);
            }

            $docente->docentes()->syncWithoutDetaching([$user->id]);
        } else {
            $this->detachFromDocente($user);
        }
    }

    private function detachAlumnoDocente(User $user): void
    {
        $this->detachFromAlumno($user);
        $this->detachFromDocente($user);
    }

    private function detachFromAlumno(User $user): void
    {
        Alumno::whereHas('alumnos', fn($q) => $q->where('id', $user->id))
            ->get()
            ->each(fn($a) => $a->alumnos()->detach($user->id));
    }

    private function detachFromDocente(User $user): void
    {
        Docente::whereHas('docentes', fn($q) => $q->where('id', $user->id))
            ->get()
            ->each(fn($d) => $d->docentes()->detach($user->id));
    }
}
