<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use App\Http\Controllers\Controller;
use App\DTOs\Models\ModelCreateDto;
use App\DTOs\Models\ModelUpdateDto;
use App\Repositories\Interfaces\IModelRepository;
use Exception;
use App\Models\Model;
use App\Models\Brand;

class ModelController extends Controller
{

    private $modelRepository;

    private $errorConnection = "";

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

        if ($result) {
            if( $result['total'] > 0){
                return $this->successResponse($result, "Modelos encontrados correctamente.", 201);
            } else {
                return $this->successResponse($result,"No hay modelos cargados en el sistema.", 201);
            }
            //return $this->successResponse($result, "Modelos encontrados correctamente", 201);
        } else {
            return $this->errorResponse("No hay Modelos.", 201);
        }
    }

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

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

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

        //return response('Almacen no encontrado', 404);
    }

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

            if (count($codeExist) == 1) {
                $code = $request['code'];
                $codeExist = Model::where('code', '=', $code)->get();
    
                if (count($codeExist) == 0) {
                    $this->validate($request, [
                        'id_brand' => 'required',
                        'code' => 'required|max:10',
                        'model' => 'required|max:250'
                    ], [
                        'id_brand.required' => 'La Marca es requerido',
                        'code.required' => 'El código de Modelo es requerido',
                        'code.max' => 'El código de Modelo no puede superar los :max caracteres',
                        'model.required' => 'El nombre de Modelo es requerido'
                    ]);
        
                    $store = new ModelCreateDto($request->except('business_information'));
                    $result = $this->modelRepository->store($store);
            
                    return $this->successResponse($result, "Modelo creado correctamente", 201);
                } else {
                    return $this->errorResponse("Codigo de modelo ingresado ya existe", 201);
                }
            } else {
                return $this->errorResponse("Ingresar una marca existente.", 201);
            }
        } catch (\Illuminate\Validation\ValidationException $e) {
            return $this->errorResponse($e->response->original, 201);
        }        
      
        //return response($result, 201);
    }

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

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

            if ($result) {
                $id_brand = $request['id_brand'];
                $codeExist = Brand::where('id', '=', $id_brand)->get();
    
                if (count($codeExist) == 1) {
                    $code = $request['code'];
                    $codeExist = Model::where('id', '!=', $id)->where('code', '=', $code)->get();
        
                    if (count($codeExist) == 0) {
                        $this->validate($request, [
                            'id_brand' => 'required',
                            'code' => [
                                'required',
                                'max:10'
                            ],
                            'model' => 'required|max:250'
                        ], [
                            'id_brand.required' => 'La Marca es requerido',
                            'code.required' => 'El código de Modelo es requerido',
                            'code.max' => 'El código de Modelo no puede superar los :max caracteres',
                            'model.required' => 'El nombre de Modelo es requerido'
                        ]);
                
                        $data = $request->except('business_information');
                        $data['id'] = $id;
                
                        $entry = new ModelUpdateDto($data);
                
                        $this->modelRepository->update($entry);
        
                        $result = $this->modelRepository->find($id);
        
                        return $this->successResponse($result, "Modelo actualizado correctamente", 201);
                    } else {
                        return $this->errorResponse("Código de modelo ingresado ya existe", 201);
                    }
                } else {
                    return $this->errorResponse("Ingresar una marca existente.", 201);
                }
            } else {
                return $this->errorResponse("Modelo ingresado no existe", 201);
            }
        } catch (\Illuminate\Validation\ValidationException $e) {
            return $this->errorResponse($e->response->original, 201);
        }

        //return response(null, 202);
    }

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

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

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

            return $this->successResponse($id, "Modelo eliminado correctamente", 201);    
        } else {
            return $this->errorResponse("Modelo ingresado no existe", 201);
        }

        //return response(null, 202);
    }    
}
