<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use App\Http\Controllers\Controller;
use App\DTOs\CustomerType\CustomerTypeCreateDto;
use App\DTOs\CustomerType\CustomerTypeUpdateDto;
use App\Repositories\Interfaces\ICustomerTypeRepository;
use Exception;
use App\Models\CustomerType;

class CustomerTypeController extends Controller
{

    private $customerTypeRepository;
    private $errorConnection = "";

    public function __construct(Request $request, ICustomerTypeRepository $customerTypeRepository)
    {
        if (isset($request['business_information'])) {
            $business_information = $request['business_information'];
            $ruc = $business_information['ruc_number'];

            $existe_conexion = $this->setDBClient($ruc);

            if ($existe_conexion['error']) {
                $this->errorConnection = $existe_conexion['message'];
                return $this->messageError("Se espera un número de RUC válido.", 201);
            } else {
                $this->customerTypeRepository = $customerTypeRepository;
            }
        } else {
            $this->errorConnection = 'Error en la conexión. Se espera número de RUC';
        }
    }

    public function index(Request $request)
    {
        if ($this->errorConnection != '') {
            return $this->messageError($this->errorConnection, 201);
        }

        $result = $this->customerTypeRepository->paginate($request->all());

        if ($result) {
            return $this->successResponse($result, "Tipos de Clientes encontrados correctamente", 201);
        } else {
            return $this->errorResponse("No hay Tipos de Clientes", 201);
        }
    }

    public function show(int $id,Request $request)
    {
        $business_ruc = $request['business_information']['ruc_number'];
        if ($this->errorConnection != '') {
            return $this->messageError($this->errorConnection, 500);
        }

        $result = $this->customerTypeRepository->find($id,$business_ruc);

        if ($result) {
            return $this->successResponse($result, "Tipo de cliente encontrado correctamente", 200);
        } else {
            return $this->errorResponse("Tipo de cliente no encontrado", 200);
        }
    }

    public function store(Request $request)
    {
        try {
            if ($this->errorConnection != '') {
                return $this->messageError($this->errorConnection, 500);
            }

            $business_information = $request['business_information'];
            $business_ruc = $business_information['ruc_number'];

            //VALIDANDO SI EXISTE CUSTOMER_TYPE
            $customerTypeDescripcion = $request['customers_type'];
            $customerTypeDescripcion = trim(strtolower($customerTypeDescripcion));
            if($customerTypeDescripcion != null){
                $customerTypeDescripcionExist = CustomerType::whereRaw('LOWER(customers_type) = ?', $customerTypeDescripcion)
                ->where('status', 1)
                ->get();

                //CustomerType::whereRaw('LOWER(tu_columna) = ?', [strtolower($textoEnMinusculas)])->get();

                if (count($customerTypeDescripcionExist) >= 1) {
                    return $this->errorResponse("El tipo de cliente que intenta registrar ya existe.", 422);
                }
            }

            $this->validate(
                $request,
                [
                    'customers_type' => 'required|max:80',
                    'created_by' => 'required|numeric|max:11',
                ],
                [
                    'customers_type.required' => 'El campo Tipo de Cliente es obligatorio.',
                    'customers_type.max' => 'El campo Tipo de Cliente no debe superar los 80 caracteres.',

                    'created_by.required' => 'El campo Creado Por es obligatorio.',
                    'created_by.numeric' => 'El campo Creado Por debe ser un valor numérico.',
                    'created_by.max' => 'El campo Creado Por no debe tener más de 11 caracteres.'
                ,]
            );

            $store = new CustomerTypeCreateDto();
            $store->customers_type = $request["customers_type"];

            $store->created_by = $request['created_by'];
            $store->created_at = date('Y-m-d h:m:s');
            $store->status = 1;
            $store->ruc = $business_ruc;

            $result = $this->customerTypeRepository->store($store);
            return $this->successResponse($result, "El tipo de cliente se registró correctamente.", 201);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return $this->errorResponse($e->response->original, 422);
        }
    }

    public function update(int $id, Request $request)
    {
        try {
            $business_information = $request['business_information'];
            $business_ruc = $business_information['ruc_number'];
            if ($this->errorConnection != '') {
                return $this->messageError($this->errorConnection, 500);
            }
            $result = $this->customerTypeRepository->find($id,$business_ruc);

            //VALIDANDO SI EXISTE CUSTOMER_TYPE
            $business_information = $request['business_information'];
            $business_ruc = $business_information['ruc_number'];

            //VALIDANDO SI EXISTE CUSTOMER_TYPE
            $customerTypeDescripcion = $request['customers_type'];
            $customerTypeDescripcion = trim(strtolower($customerTypeDescripcion));
            if ($customerTypeDescripcion != null) {
                $customerTypeDescripcionExist = CustomerType::whereRaw('LOWER(customers_type) = ? and `id` != ?', [$customerTypeDescripcion, $id])
                    ->where('status', 1)
                    ->get();

                //CustomerType::whereRaw('LOWER(tu_columna) = ?', [strtolower($textoEnMinusculas)])->get();

                if (count($customerTypeDescripcionExist) >= 1) {
                    return $this->errorResponse("El tipo de cliente que intenta registrar ya existe.", 422);
                }
            }

            if ($result) {
                $this->validate($request, [
                    'customers_type'=>'required|max:80',
                    "updated_by" => 'required|numeric|max:11',
                ],
                [
                    'customers_type.required' => 'El tipo de cliente es requerido.',
                    'updated_by.required' => "El usuario de modificación es requerido",
                    'updated_by.numeric' => 'El campo modificación debe ser un valor numérico.',
                    'updated_by.max' => 'El campo modificación no debe tener más de 11 caracteres.',
                    'customers_type.max' => 'El campo Tipo de Cliente no debe superar los 80 caracteres.',
                ]);

                //DATA DEL REQUEST
                //$data['id'] = $id;
                //ENVIAMOS AL DTO
                $entry = new CustomerTypeUpdateDto();
                $entry-> id=$id;
                $entry-> customers_type = $request['customers_type'];
                $entry-> created_by = $result -> created_by;
                $entry-> created_at = $result -> created_at;
                $entry-> updated_by = $request['updated_by'];
                $entry-> updated_at = date('Y-m-d h:m:s');

                $entry-> ruc=$business_ruc;
                $entry-> status=1;


                //ACTUALIZAMOS INFORMACION
                $this->customerTypeRepository->update($entry);
                //Nuevamente se consulta la data del ID
                $result = $this->customerTypeRepository->find($id,$business_ruc);

                return $this->successResponse($result, "El Cliente fue actualizado correctamente.", 200);

            } else{
                return $this->errorResponse("Cliente ingresado no existe", 404);
                }
        }catch(\Illuminate\Validation\ValidationException $e) {
            return $this->errorResponse($e->response->original, 422);
        }
    }

    public function destroy(int $id, Request $request)
    {
        $business_ruc = $request['business_information']['ruc_number'];
        if ($this->errorConnection != '') {
            return $this->messageError($this->errorConnection, 500);
        }

        $result = $this->customerTypeRepository->find($id,$business_ruc);
        if ($result) {
            $this->customerTypeRepository->destroy($id);

            return $this->successResponse($id, "Cliente eliminado correctamente.", 200);
        } else {
            return $this->errorResponse("Cliente ingresado no existe", 404);
        }
    }
}
