<?php

namespace App\Livewire;

use App\Models\Alumno;
use App\Models\Campan;
use App\Models\Medio;
use App\Models\Nivel;
use App\Models\Plan;
use App\Models\Plantel;
use App\Models\Turno;
use App\Models\User;
use Illuminate\Auth\Notifications\ResetPassword;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Str;
use Livewire\Attributes\On;
use Livewire\Component;
use App\Models\Role;

class ModalProspecto extends Component
{
    // Usuario
    public $pname;
    public $papellidoPaterno;
    public $papellidoMaterno;
    public $pemail;
    public $ptelefono;
    public $pdireccion;
    public $pplantels;
    public $proles;

    // Prospecto
    public $selectedNivel;
    public $selectedplan;
    public $pciclo;
    public $pturno;
    public $pmedio;

    // Selects dependientes
    public $niveles = [];
    public $plans   = [];
    public $turnos  = [];

    public $active = "disabled";

    public $prospecto = null;

    /* ------------------ RESET REAL ------------------ */
    private function resetForm()
    {
        $this->reset([
            'pname',
            'papellidoPaterno',
            'papellidoMaterno',
            'pemail',
            'ptelefono',
            'pdireccion',
            'pplantels',
            'proles',
            'selectedNivel',
            'selectedplan',
            'pciclo',
            'pturno',
            'pmedio',
            'prospecto',
        ]);

        $this->niveles = [];
        $this->plans   = [];
        $this->turnos  = [];
        $this->active  = "disabled";
    }

    /* ------------------ NUEVO ------------------ */
    #[On('create-prospecto')]
    public function createProspecto()
    {
        $this->resetForm();
        $this->dispatch('open-prospecto-modal');
    }

    /* ------------------ SELECTS ------------------ */
    public function updatedPplantels()
    {
        $this->selectedNivel = null;
        $this->selectedplan  = null;
        $this->plans = [];

        $this->niveles = Nivel::whereHas('nivelPlantel', fn($q) =>
            $q->where('plantels.id', $this->pplantels)
        )->get();

        $this->turnos = Turno::whereHas('turnoPlantel', fn($q) =>
            $q->where('plantels.id', $this->pplantels)
        )->get();
    }

    public function updatedSelectedNivel()
    {
        if (!$this->selectedNivel || !$this->pplantels) {
            $this->plans = [];
            $this->active = "disabled";
            return;
        }

        $this->plans = Plan::where('nivel', $this->selectedNivel)
            ->whereHas('planesPlantel', fn($q) =>
                $q->where('plantels.id', $this->pplantels)
            )->get();

        $this->active = "";
    }

    public function guardarProspecto()
    {
        if (User::where('email', $this->pemail)
        ->orWhere('telefono', $this->ptelefono)
        ->exists()) {

            $this->dispatch('swal',
                icon: 'error',
                title: 'Registro duplicado',
                text: 'El correo o teléfono ya están registrados.',
                timer: 2000,
                confirm: false,
                closeModal: true
            );

            return;
        }

        $passwordTemporal = Str::random(12);

        $user = User::create([
            'name' => mb_strtoupper($this->pname, 'UTF-8'),
            'apellidoPaterno' => mb_strtoupper($this->papellidoPaterno, 'UTF-8'),
            'apellidoMaterno' => mb_strtoupper($this->papellidoMaterno, 'UTF-8'),
            'email'     => $this->pemail,
            'telefono'  => $this->ptelefono,
            'direccion' => $this->pdireccion,
            'password'  => Hash::make($passwordTemporal),
            'status' => 1
        ]);

        $user->roles()->sync($this->proles);
        $user->plantelUsuarios()->sync([$this->pplantels]);

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

        $prospecto = Alumno::create([
            'nivel'            => $this->selectedNivel,
            'plan_id'          => $this->selectedplan,
            'usuario_registro' => Auth::id(),
            'ciclo'            => $this->pciclo,
            'turno'            => $this->pturno,
            'medio'            => $this->pmedio,
        ]);

        $prospecto->alumnos()->sync([$user->id]);

        $this->dispatch('swal',
                icon: 'success',
                title: 'Registrado!',
                text: 'Se registró el prospecto correctamente',
                timer: 2000,
                confirm: false,
                closeModal: true,
                reload: 2000
        );

        $this->resetForm();
    }

    public function render()
    {
        return view('livewire.modal-prospecto', [
            'roles'   => Role::whereHas('areas', fn($q) => $q->where('areas.name', 'Promoción'))->get(),
            'plantels'=> Plantel::all(),
            'user'    => Auth::user(),
            'campans' => Campan::whereDate('periodoInicial', '<=', now())
                   ->whereDate('periodoFinal', '>=', now())
                   ->where('status', 1)
                   ->get(),
            'medios'  => Medio::all(),
        ]);
    }
}
