<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use App\Http\Controllers\Controller;
use App\DTOs\Categories\CategoriesCreateDto;
use App\DTOs\Categories\CategoriesUpdateDto;
use App\Repositories\Interfaces\ICategoriesRepository;
use Exception;
use App\Models\Categories;


class CategoriesController extends Controller
{
    private $categoriesRepository;

    private $errorConnection = "";

    public function __construct(Request $request, ICategoriesRepository $categoriesRepository)
    {
        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 numero de RUC valido.", 201);
            }else{
                $this->categoriesRepository = $categoriesRepository;
            }
        }else{
            $this->errorConnection='Error en la conexion. Se espera numero de RUC';
        }
    }

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

        $result = $this->categoriesRepository->paginate($request->all());
        
        if ($result) {
            if( $result['total'] > 0){
                return $this->successResponse($result, "Categorias encontrados correctamente.", 201);
            } else {
                return $this->successResponse($result,"No hay Categorias cargadas en el sistema.", 201);
            }
            //return $this->successResponse($result, "Marcas encontrados correctamente", 201);
        } else {
            return $this->errorResponse("No hay Categorias.", 201);
        }
    }

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

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

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

    public function store(Request $request)
    {
        try {
            if($this->errorConnection != ''){
                return $this->messageError($this->errorConnection, 201);
            }
            
            $code = $request['code'];
            $codeExist = Categories::where('code', '=', $code)->get();

            if(count($codeExist) == 0) {
                $this->validate($request, [
                    'code' => 'required|max:50',
                    'name' => 'required|max:250',
                    'image' => 'max:255'
                ], [
                    'code.required' => 'El codigo de Categoria es requerido',
                    'code.max' => 'El codigo de Categoria no puede superar los :max caracteres',
                    'name.required' => 'El nombre de Categoria es requerido',
                    
                ]);

                $store = new CategoriesCreateDto($request->except(array('business_information', 'items')));
                $result = $this->categoriesRepository->store($store);

                return $this->successResponse($result, "La Categoria fue creada correctamente", 201);
            } else {
                return $this->successResponse("El codigo de categoria ingresado ya existe", 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);
            }

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

            if ($result) {
                $code = $request['code'];
                $codeExist = Categories::where('id', '!=', $id)->where('code', '=', $code)->get();

                if (count($codeExist) ==0) {
                    $this->validate($request, [
                        'code' => [
                            'required',
                            'max:50'
                        ],
                        'name' => 'required|max:250',
                        
                    ], [
                        'code.required' => 'El codigo de Categoria es requerido',
                        'code.max' => 'El codigo de Categoria no puede superar los :max caracteres',
                        'name.required' => 'El nombre de Categoria es requerido'
                    ]);

                    $data = $request->except('business_information');
                    $data['id'] = $id;

                    $entry = new CategoriesUpdateDto($data);

                    $this->categoriesRepository->update($entry);

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

                    return $this->successResponse($result, "La Categoria fue actualizada correctamente", 201);
                } else {
                    return $this->errorResponse("El codigo de categoria ingresado ya existe", 201);
                }
            } else {
                return $this->errorResponse("Categoria ingresada no existe", 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->categoriesRepository->find($id);

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

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

}