<?php

namespace App\Livewire;

use App\Models\Alumno;
use App\Models\Campan;
use App\Models\Concepto;
use App\Models\Documento;
use App\Models\Medio;
use App\Models\Nivel;
use App\Models\Pago;
use App\Models\Plan;
use App\Models\Plane;
use App\Models\Plantel;
use App\Models\Role;
use App\Models\Turno;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Livewire\Attributes\On;
use Livewire\Component;

class DataProspecto extends Component
{
    public $full;

    public $activeProspectId = null;

    public $pname;
    public $papellidoPaterno;
    public $papellidoMaterno;
    public $pemail;
    public $ptelefono;
    public $pdireccion;
    public $ppassword;
    public $pplantels;
    public $proles;

    public $selectedNivel;
    public $selectedplan;
    public $selectedplane;
    public $pciclo;
    public $pturno;
    public $pmedio;


    public $niveles = [];
    public $plans   = [];
    public $turnos  = [];

    public $planesPago = [];
    public $conceptos  = [];
    public $conceptosNombres  = [];

    public $active = "disabled";

    public $prospecto;

    public $documentoSeleccionado;

    public function failedValidation(ValidationException $e)
    {
        $this->dispatch('swal',
                icon: 'error',
                title: 'Error de validación',
                text: $e->validator->errors()->first(),
                timer: 2000,
                confirm: false,
                closeModal: true
            );

        throw $e;
    }

    #[On('set-documento')]
    public function setDocumento($id)
    {
        $this->documentoSeleccionado = $id;
    }

    public function aprobarDocumento()
    {
        if (!$this->documentoSeleccionado) return;

        Documento::where('id', $this->documentoSeleccionado)
            ->update(['status' => 1]);

            $this->dispatch('cerrar-modal');

        $this->dispatch('swal',
                icon: 'success',
                title: 'Validádo',
                text: 'notificado',
                timer: 2000,
                confirm: false,
                closeModal: true
            );
            $this->prospecto->refresh();
    }

    public function rechazarDocumento()
    {
        if (!$this->documentoSeleccionado) return;

        Documento::where('id', $this->documentoSeleccionado)
            ->update(['status' => 2]);
        $this->dispatch('cerrar-modal');

        $this->dispatch('swal',
                icon: 'error',
                title: 'Rechazado',
                text: 'notificado',
                timer: 2000,
                confirm: false,
                closeModal: true
            );

            $this->prospecto->refresh();
    }

    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 updatedSelectedplane()
    {
        $this->conceptos = [];

        if (!$this->selectedplane) {
            return;
        }

        // $plane = Plane::with(['conceptos' => function ($query) {
        //     $query->where('tipo', 1);
        //     }])->find($this->selectedplane);

            $plane = Plane::with('conceptos')->find($this->selectedplane);

        if ($plane) {
            $this->conceptos = $plane->conceptos;

        }
    }

    public function actualizarProspecto()
    {
        $user = $this->prospecto->alumnos()->first();
        if (!$user) return;

        try {

            $this->validate([
            'pname' => 'required',
            'papellidoPaterno' => 'required',
            'papellidoMaterno' => 'required',

            'pemail' => [
                'required',
                'email',
                Rule::unique('users', 'email')->ignore($user->id),
            ],

            'ptelefono' => [
                'required',
                'regex:/^[0-9]{10}$/',
                Rule::unique('users', 'telefono')->ignore($user->id),
            ],

        ], [
            'pname.required'      => 'El nombre es obligatorio',
            'papellidoPaterno.required'      => 'El apellido paterno es obligatorio',
            'papellidoMaterno.required'      => 'El apellido materno es obligatorio',
            'pemail.required'    => 'El correo es obligatorio',
            'pemail.email'       => 'El correo no es válido',
            'pemail.unique'      => 'Este correo ya está registrado',

            'ptelefono.required' => 'El teléfono es obligatorio',
            'ptelefono.regex'    => 'El teléfono debe tener 10 dígitos numéricos',
            'ptelefono.unique'   => 'Este teléfono ya está registrado',
        ]);

        } catch (ValidationException $e) {


            $mensaje = collect($e->validator->errors()->all())->first();

            $this->dispatch('swal',
                icon: 'error',
                title: 'Error de validación',
                text: $mensaje,
                timer: 2000,
                confirm: false,
                closeModal: true
            );


            return;
        }

        $user->update([
            '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,
        ]);

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

        $this->prospecto->update([
            'nivel'   => $this->selectedNivel,
            'plan_id' => $this->selectedplan,
            'ciclo'   => $this->pciclo,
            'turno'   => $this->pturno,
            'medio'   => $this->pmedio,
        ]);


        $this->dispatch('swal',
                icon: 'success',
                title: 'Datos actualizados!',
                text: 'Se modificaon los datos del prospecto',
                timer: 2000,
                confirm: false,
                closeModal: true
            );
    }

    #[On('edit-prospecto')]
    public function editProspecto($id)
    {
        $this->activeProspectId = $id;

        $this->resetForm();

        $this->prospecto = Alumno::findOrFail($id);
        $user = $this->prospecto->alumnos()->first();
        if (!$user) return;

        $this->pname      = $user->name;
        $this->papellidoPaterno      = $user->apellidoPaterno;
        $this->papellidoMaterno      = $user->apellidoMaterno;
        $this->pemail     = $user->email;
        $this->ptelefono  = $user->telefono;
        $this->pdireccion = $user->direccion;
        $this->proles     = $user->roles()->pluck('id')->first();
        $this->pplantels  = $user->plantelUsuarios()->value('plantels.id');

        $this->selectedNivel = $this->prospecto->nivel;
        $this->pciclo        = $this->prospecto->ciclo;
        $this->pturno        = $this->prospecto->turno;
        $this->pmedio        = $this->prospecto->medio;

        $this->selectedplane = $this->prospecto->plane_id;

        $plane = Plane::with(['conceptos' => function ($query) {
            $query->where('tipo', 1);
            }])->find($this->selectedplane);

            if ($plane) {
                $this->conceptos = $plane->conceptos;
            }


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

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

        $this->planesPago = Plane::query()
            ->whereHas('nivelPlane', function ($q) {
                $q->where('nivels.id', $this->selectedNivel);
            })
            ->whereHas('planPlantel', function ($q) {
                $q->where('plantels.id', $this->pplantels);
            })
            ->get();

        $this->conceptosNombres = Concepto::where('tipo','=','3' )->get();

        $this->full = true;
        $this->selectedplan = $this->prospecto->plan_id;
        $this->active = "";
        $this->dispatch('mark-active-prospect', id: $id);
    }

    public function plan()
    {

        if($this->prospecto->plane_id != $this->selectedplane){

        Pago::where('user_id', '=', $this->prospecto->id)->delete();

        $this->prospecto->update([
            'plane_id' => $this->selectedplane,
            ]);

         $promotor = Auth::user();
            foreach($this->conceptos as $concepto){
                        Pago::create([
                            'plans_id' => $this->selectedplane,
                            'folio' => 0,
                            'concepto' => $concepto->name,
                            'beca' => 0,
                            'monto' => $concepto->monto,
                            'fecha_pago' => $concepto->fecha_pago,
                            'pago'=>0,
                            'user_id'=> $this->prospecto->id,
                            'asignacion' =>$promotor->id,
                            'status'=> 1
                        ]);
            }

            $this->dispatch('swal',
                icon: 'success',
                title: 'Éxito!',
                text: 'Plan de pago asignado',
                timer: 2000,
                confirm: false,
                closeModal: true
            );

        }else{

            $this->dispatch('swal',
                icon: 'error',
                title: 'Error!',
                text: 'Plan de pago actualmente asignado',
                timer: 2000,
                confirm: false,
                closeModal: true
            );
        }


    }

    public function resetForm()
    {
        // Usuario
        $this->pname = null;
        $this->papellidoPaterno = null;
        $this->papellidoMaterno = null;
        $this->pname = null;
        $this->pemail = null;
        $this->ptelefono = null;
        $this->pdireccion = null;
        $this->ppassword = null;
        $this->pplantels = null;
        $this->proles = null;

        // Prospecto
        $this->selectedNivel = null;
        $this->selectedplan = null;
        $this->pciclo = null;
        $this->pturno = null;
        $this->pmedio = null;

        // Selects
        $this->niveles = [];
        $this->plans = [];
        $this->turnos = [];
        $this->conceptos = [];

        $this->active = "disabled";
        $this->prospecto = null;
    }

    public function render()
    {
        return view('livewire.data-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(),
        ]);
    }
}
