<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use App\Http\Controllers\Controller;
use App\DTOs\UnitMeasure\UnitMeasureCreateDto;
use App\DTOs\UnitMeasure\UnitMeasureUpdateDto;
use App\Repositories\Interfaces\IUnitMeasureRepository;

class UnitMeasureController extends Controller
{

    private $unitmeasureRepository;

    private $errorConnection = "";

    public function __construct(Request $request, IUnitMeasureRepository $unitmeasureRepository)
    {
        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->unitmeasureRepository = $unitmeasureRepository;
            }
        } 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->unitmeasureRepository->paginate($request->all());

        if ($result) {
            if( $result['total'] > 0){
                return $this->successResponse($result, "Unidades de medida encontradas correctamente.", 201);
            } else {
                return $this->successResponse($result,"No hay unidades de medida cargadas en el sistema.", 201);
            }
            //return $this->successResponse($result, "Unidades de medida encontradas correctamente", 201);
        } else {
            return $this->errorResponse("No hay Unidades de medidas", 201);
        }
    }

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

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

        if ($result) {
            return $this->successResponse($result, "Unidad de medida encontrada correctamente", 201);
        } else {
            return $this->errorResponse("Unidad de medida no encontrada", 201);
        }
    }

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

            $this->validate($request, [
                'code' => 'required|max:10',
                'description' => 'required|max:250',
                'code_sunat' => 'required|max:10',
                'description' => 'required|max:250'
            ]);

            $store = new UnitMeasureCreateDto($request->except('business_information'));
            $result = $this->unitmeasureRepository->store($store);
    
            return $this->successResponse($result, "Unidad de medida creada correctamente", 201);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return $this->errorResponse($e->response->original, 201);
        }

    }

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

            $this->validate($request, [
                'code' => 'required|max:10',
                'description' => 'required|max:250',
                'code_sunat' => 'required|max:10',
                'description' => 'required|max:250'
            ]);
    
            $data = $request->except('business_information');
            $data['id'] = $id;
    
            $entry = new UnitMeasureUpdateDto($data);
            $this->unitmeasureRepository->update($entry);
            $result = $this->unitmeasureRepository->find($id);

            return $this->successResponse($result, "Unidad de medida actualizada correctamente", 201);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return $this->errorResponse($e->response->original, 201);
        }
    }

    public function destroy(int $id)
    {
        if($this->errorConnection != ''){
            return $this->messageError($this->errorConnection, 201); 
        }
        
        $result = $this->unitmeasureRepository->find($id);

        if ($result) {
            $this->unitmeasureRepository->destroy($id);

            return $this->successResponse($id, "Unidad de medida eliminada correctamente", 201);    
        } else {
            return $this->errorResponse("Unidad de medida ingresada no existe", 201);
        }

    }
}
