<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use App\Http\Controllers\Controller;
use App\DTOs\PaymentMethods\PaymentMethodCreateDto;
use App\DTOs\PaymentMethods\PaymentMethodUpdateDto;
use App\Repositories\Interfaces\IPaymentMethodRepository;
use Exception;
use App\Models\PaymentMethod;

class PaymentMethodController extends Controller
{

    private $paymentmethodRepository;

    private $errorConnection = "";
    private $rucNumber = '';

    public function __construct(Request $request, IPaymentMethodRepository $paymentmethodRepository)
    {
        if (isset($request['business_information'])) {
            $business_information = $request['business_information'];
            $this->rucNumber = $business_information['ruc_number'];
            $this->paymentmethodRepository = $paymentmethodRepository;
            /*$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->paymentmethodRepository = $paymentmethodRepository;
            }*/
        } 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); 
        }

        $input = $request->all();
        $input['ruc_number'] = $this->rucNumber;
        $result = $this->paymentmethodRepository->paginate($input);

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

    public function show(int $id)
    {
        try{
            if($this->errorConnection != ''){
                return $this->messageError($this->errorConnection, 201); 
            }
            //$result = $this->paymentmethodRepository->find($id);
            $result = PaymentMethod::where('ruc_number', '=', $this->rucNumber)->find($id);

            if ($result) {
                return $this->successResponse($result, "Forma de Pago encontrado correctamente", 201);
            } else {
                return $this->errorResponse("Forma de Pago no encontrado", 201);
            }
        } catch(\Exception $ex){
            return $this->errorResponse("No se pudo encontrar la forma de pago.", 201);
        }
    }

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

            $code = $request['code'];
            $codeExist = PaymentMethod::where('code', '=', $code)->where('ruc_number', '=', $this->rucNumber)->get();

            if (count($codeExist) == 0) {
                $this->validate($request, [
                    'code' => 'required|max:10',
                    'description' => 'required|max:250',
                    'type' => 'required|max:10',
                    'days' => 'required'
                ], [
                    'code.required' => 'El código de Forma de Pago es requerido',
                    'code.max' => 'El código de Forma de Pago no puede superar los :max caracteres',
                    'description.required' => 'El nombre de Forma de Pago es requerido',
                    'type.required' => 'El tipo de Forma de Pago es requerido',
                    'days.required' => 'Los dias de Forma de Pago es requerido'
                ]);
    
                $input = $request->except('business_information');
                $input['ruc_number'] = $this->rucNumber;
                $store = new PaymentMethodCreateDto($input);
                $result = $this->paymentmethodRepository->store($store);
        
                return $this->successResponse($result, "Forma de Pago creado correctamente", 201);    
            } else {
                return $this->errorResponse("Codigo de Forma de Pago ingresado ya existe", 201);
            }
        } catch (\Illuminate\Validation\ValidationException $e) {
            return $this->errorResponse($e->response->original, 201);
        } catch(\Exception $ex){
            return $this->errorResponse("No se pudo guardar la forma de pago.", 201);
        }
    }

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

            $result = $this->paymentmethodRepository->find($id);

            if ($result) {
                $code = $request['code'];
                $codeExist = PaymentMethod::where('id', '!=', $id)->where('code', '=', $code)
                    ->where('ruc_number', '=', $this->rucNumber)->get();
    
                if (count($codeExist) == 0) {
                    $this->validate($request, [
                        'code' => [
                            'required',
                            'max:10'
                        ],
                        'description' => 'required|max:250',
                        'type' => 'required|max:10',
                        'days' => 'required'
                    ], [
                        'code.required' => 'El código de Forma de Pago es requerido',
                        'code.max' => 'El código de Forma de Pago no puede superar los :max caracteres',
                        'description.required' => 'El nombre de Forma de Pago es requerido',
                        'type.required' => 'El tipo de Forma de Pago es requerido',
                        'days.required' => 'Los dias de Forma de Pago es requerido'
                    ]);
            
                    $data = $request->except('business_information');
                    $data['id'] = $id;
                    $data['ruc_number'] = $this->rucNumber;
                    $entry = new PaymentMethodUpdateDto($data);
                    $this->paymentmethodRepository->update($entry);
                    //$result = $this->paymentmethodRepository->find($id);
                    $result = PaymentMethod::where('ruc_number', '=', $this->rucNumber)->find($id);
        
                    return $this->successResponse($result, "Forma de Pago actualizado correctamente", 201);
                } else {
                    return $this->errorResponse("Codigo de Forma de Pago ingresado ya existe", 201);
                }
            } else {
                return $this->errorResponse("Forma de Pago ingresado no existe", 201);
            }
        } catch (\Illuminate\Validation\ValidationException $e) {
            return $this->errorResponse($e->response->original, 201);
        } catch(\Exception $ex){
            return $this->errorResponse("No se pudo guardar la forma de pago: " . $ex->getMessage(), 201);
        }
    }

    public function destroy(int $id)
    {
        try{
            if($this->errorConnection != ''){
                return $this->messageError($this->errorConnection, 201); 
            }
            //$result = $this->paymentmethodRepository->find($id);
            $result = PaymentMethod::where('ruc_number', '=', $this->rucNumber)->find($id);
            if ($result) {
                $result->delete();

                return $this->successResponse($id, "Forma de Pago eliminado correctamente", 201);    
            } else {
                return $this->errorResponse("Forma de Pago ingresado no existe", 201);
            }
        } catch(\Exception $ex){
            return $this->errorResponse("No se pudo eliminar la forma de pago.", 201);
        }
    }    
}
