<?php

namespace App\Http\Controllers;

use App\Mail\AutoAvisoNuevoCliente;
use App\Mail\AutoAvisoNuevoClienteLocal;
use App\Mail\AvisoActivacionCliente;
use App\Mail\AvisoNuevoCliente;
use App\Models\Cliente;
use App\Models\ConfigUserSucursal;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules;
use Illuminate\Support\Facades\Mail;

class UserController extends Controller
{
    public function getUsers(): JsonResponse
    {
        $users = User::leftjoin('model_has_roles', 'users.id', '=', 'model_has_roles.model_id')
        ->leftjoin('roles', 'roles.id', '=', 'model_has_roles.role_id')
        ->selectRaw('
            users.*,
            roles.name role
        ')->where(['estatus' => 'activo','autorizado'=>'si'])->get();
        return response()->json([
            'data' => $users->load("roles","cliente"),
        ], JsonResponse::HTTP_OK);
    }

    public function getRevision(): JsonResponse
    {
        $users = User::leftjoin('model_has_roles', 'users.id', '=', 'model_has_roles.model_id')
        ->leftjoin('roles', 'roles.id', '=', 'model_has_roles.role_id')
        ->selectRaw('
            users.*,
            roles.name role
        ')->where(['estatus' => 'activo','autorizado'=>'no'])->get();
        return response()->json([
            'data' => $users->load("roles","cliente"),
        ], JsonResponse::HTTP_OK);
    }

    public function registro(Request $request): JsonResponse
    {
        $request->validate(
            [
                'name' => ['required', 'string', 'max:255'],
                'paternal_surname' => ['required', 'string', 'max:255'],
                'maternal_surname' => ['required', 'string', 'max:255'],
                'telefono' => ['max:45'],
                'tipo_cliente' => ['required'],
                'email' => ['required', 'string', 'email', 'max:255', 'unique:'.User::class],
                'password' => [
                    'required',
                    Rules\Password::min(8)->letters(),
                ],
                'password' => ['required', 'confirmed', Rules\Password::defaults()],
            ],
            [
                'tipo_cliente.required'=>'El campo tipo cliente es obligatorio',
                'paternal_surname.required'=>'El campo Ap. Paterno es obligatorio',
                'maternal_surname.required'=>'El campo Ap. Materno es obligatorio',
            ]
        );
        $name = "{$request->name} {$request->paternal_surname} {$request->maternal_surname}";
        $dataUser = [
            'name' => $name,
            'email' => $request->email,
            'telefono' => $request->telefono,
            'password' => Hash::make($request->password),
            'autorizado' => 'no',
            'nota' => $request->nota,
        ];

        if ($request->tipo_cliente == 'cliente_linea') {
            $cliente = Cliente::create([
                'rfc' => '',
                'razonSocial' => $name,
                'celular' => $request->telefono,
                'email' => $request->email,
                'observacion' => $request->nota,
                'tipo' => $request->tipo_cliente,
            ]);

            $dataUser = [
                'name' => $name,
                'email' => $request->email,
                'telefono' => $request->telefono,
                'password' => Hash::make($request->password),
                'autorizado' => 'si',
                'nota' => $request->nota,
                'cliente_id' => $cliente->id,
                'tipo_cliente' => $request->tipo_cliente,
            ];
        }

        $user = User::create($dataUser);

        $user->assignRole('Cliente');

        $aviso = new AutoAvisoNuevoCliente($user);
        if ($request->tipo_cliente == 'cliente_linea') {
            $aviso = new AutoAvisoNuevoClienteLocal($user);
        }
        Mail::to($user->email)->send($aviso);
        Mail::to(env('MAIL_FROM_ADDRESS'))->send(new AvisoNuevoCliente($user));

        return response()->json([
            'data' => $user,
        ], JsonResponse::HTTP_OK);
    }

    public function store(Request $request): JsonResponse
    {
        $request->validate(
            [
                'name' => ['required', 'string', 'max:255'],
                'role' => ['required', Rule::exists('roles', 'name')],
                'tipo_cliente' => ['required'],
                'email' => ['required', 'email',Rule::unique('users')->ignore('inactivo','estatus')],
                'password' => [
                    'required',
                    Rules\Password::min(8)->letters(),
                ],
                'password' => ['required', 'confirmed', Rules\Password::defaults()],
                'cliente_id'=> ['required_if:role,Cliente'],
            ],
            [
                'tipo_cliente.required'=>'El campo tipo cliente es obligatorio',
            ]
        );

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'tipo_cliente' => 'cliente_local',
            'cliente_id' => $request->cliente_id,
            'password' => Hash::make($request->password),
            'tipo_cliente' => $request->tipo_cliente,
        ]);

        $user->assignRole($request->role);

        return response()->json([
            'data' => $user,
        ], JsonResponse::HTTP_OK);
    }

    public function update(Request $request, User $user): JsonResponse
    {
        $request->validate(
            [
                'name' => ['required', 'string', 'max:255'],
                'role' => ['required', Rule::exists('roles', 'name')],
                'tipo_cliente' => ['required'],
                'email' => ['required', 'email',Rule::unique('users')->where(function ($query) use ($user) {
                    $query->whereNotIn('id', [$user->id])->whereNotIn('estatus', ['inactivo']);
                    return $query;
                })],
                'cliente_id'=> ['required_if:role,Cliente'],
            ],
            [
                'tipo_cliente.required'=>'El campo tipo cliente es obligatorio',
            ]
        );
        $params=$request->only([
            'name',
            'email',
            'cliente_id',
            'tipo_cliente',
        ]);
        $notificar = false;
        if(isset($request->autorizado))
        {
            $params['autorizado']=$request->autorizado;
            if($request->autorizado == 'si') $notificar = true;
        }
        if(isset($request->nota))
        {
            $params['nota']=$request->nota;
        }
        $user->update($params);

        if($notificar){
            Mail::to($user->email)->send(new AvisoActivacionCliente($user));
        }

        if(!$user->hasRole($request->role))
        {
            $roles= $user->getRoleNames();
            foreach ($roles as $role) {
                $user->removeRole($role);
            }
            $user->assignRole($request->role);
        }

        return response()->json([
            'data' => $user,
        ], JsonResponse::HTTP_OK);
    }

    public function updatePassword(Request $request, User $user): JsonResponse
    {
        $request->validate([
            'password' => [
                'required',
                Rules\Password::min(8)->letters(),
            ],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
        ]);

        $user->update([
            'password' => Hash::make($request->password),
        ]);

        return response()->json([
            'data' => $user,
        ], JsonResponse::HTTP_OK);
    }

    public function updatePerfil(Request $request): JsonResponse
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255'],
        ]);

        $request->user()->update($request->only([
            'name',
            'email',
        ]));

        return response()->json([
            'data' => $request->user(),
        ], JsonResponse::HTTP_OK);
    }

    public function getUser(User $user): JsonResponse
    {
        return response()->json([
            'data' => $user->load("roles","cliente"),
        ], JsonResponse::HTTP_OK);
    }

    public function destroy(User $user): JsonResponse
    {
        $user->update([
            'estatus' => 'inactivo',
        ]);

        return response()->json(null, JsonResponse::HTTP_NO_CONTENT);
    }

    public function getConfigSucursal(Request $request): JsonResponse
    {
        $model = [
            'id'=>0,
            'nombre'=>'Sin sucursal'
        ];
        if (count($request->user()->configUsersSucursales) > 0) {
            $model['id'] = $request->user()->configUsersSucursales[0]->sucursal_id;
            $model['nombre'] = $request->user()->configUsersSucursales[0]->sucursal->nombre;
        }
        return response()->json([
            'data' => $model,
        ], JsonResponse::HTTP_OK);
    }

    public function setConfigSucursal(Request $request): JsonResponse
    {
        $model = null;
        if (count($request->user()->configUsersSucursales) > 0) {
            if($request->sucursal_id==0){
                $model = $request->user()->configUsersSucursales[0]->delete();
            } else {
                $model = $request->user()->configUsersSucursales[0]->update(['user_id'=>$request->user()->id,'sucursal_id'=>$request->sucursal_id]);
            }
        } else if($request->sucursal_id != 0){
            $model = ConfigUserSucursal::create([
                'user_id'=>$request->user()->id,
                'sucursal_id'=>$request->sucursal_id,
            ]);
        }
        return response()->json([
            'data' => $model,
        ], JsonResponse::HTTP_OK);
    }

    public function getTerapistas(Request $request): JsonResponse
    {
        $terapistas = User::role('Terapista')->where(['estatus' => 'activo'])->select(['id','name'])->get();
        return response()->json([
            'data' => $terapistas,
        ], JsonResponse::HTTP_OK);
    }

    public function getAdministradores(Request $request): JsonResponse
    {
        $administradores = User::role(User::ADMIN_ROL)->where(['estatus' => 'activo'])->select(['id','name'])->get();
        return response()->json([
            'data' => $administradores,
        ], JsonResponse::HTTP_OK);
    }
}
