<?php

namespace App\Livewire;

use App\Models\Campan;
use App\Models\Medio;
use App\Models\User;
use App\Models\Nivel;
use App\Models\Plan;
use App\Models\Plantel;
use App\Models\Prospecto;
use App\Models\Turno;
use Livewire\Component;
use Spatie\Permission\Models\Role;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Livewire\Attributes\On;

class ModalProspecto extends Component
{
    // Usuario
    public $pname;
    public $pemail;
    public $ptelefono;
    public $pdireccion;
    public $ppassword;
    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',
            'pemail',
            'ptelefono',
            'pdireccion',
            'ppassword',
            '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 = "";
    }

    /* ------------------ GUARDAR ------------------ */
    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;
        }

        $user = User::create([
            'name'      => $this->pname,
            'email'     => $this->pemail,
            'telefono'  => $this->ptelefono,
            'direccion' => $this->pdireccion,
            'password'  => Hash::make($this->ppassword),
            'status' => 1
        ]);

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

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

        $prospecto->prospectos()->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();
    }


    /* ------------------ RENDER ------------------ */
    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::all(),
            'medios'  => Medio::all(),
        ]);
    }
}
