<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Tgastos;
use DB;

class TgastosCtrl extends Controller
{
    public function list() {
        $tgastos = Tgastos::orderBy('tipo')->get();
        return $tgastos;
    }

  
    public function save(Request $request) {

        try
        {
           
            $rules = [
                'tipo' => 'required'
                
            ];
            

            $validator = \Validator::make($request->all(),$rules);

            if($validator->fails())
                return ['fails' => $validator->errors()->getMessages()];

            Tgastos::create($request->all());

            return [
                'success' => true,
                'message' => "Ruta registrada correctamente"
            ];
        }
        catch(\Exception $e)
        {
            return [
                'success' => false,
                'message' => 'Ocurrio un error al intentar registrar una ruta',
                'error'   => $e->getMessage()
            ];
        }
    }

    public function update($id, Request $request) {

        try
        {
            $rules = [
                'tipo' => 'required'
                
            ];

            $validator = \Validator::make($request->all(),$rules);

            if($validator->fails())
                return ['fails' => $validator->errors()->getMessages()];

            $tgastos = Tgastos::find($id);

            if (is_null($tgastos)) {
                return [
                    'success' => false,
                    'message' => "Ruta no existe!"
                ];
            } 

            $tgastos->update([
                'tipo' => $request->get('tipo'),
                'enabled' => $request->get('enabled')
            ]);

            return [
                'success' => true,
                'message' => "# actualizada correctamente"
            ];
        }
        catch(\Exception $e)
        {
            return [
                'success' => false,
                'message' => 'Ocurrio un error al intentar registrar #',
                'error'   => $e->getMessage()
            ];
        }
    }

    public function delete($id) {
        try
        {
            $tgastos = Tgastos::find($id);

            if (is_null($tgastos)) {
                return [
                    'success' => false,
                    'message' => "Usuario no existe!"
                ];
            } 

           
            $tgastos->delete();

            //Cambiar estado a 1
            
            return [
                'success' => true,
                'message' => "Ruta eliminado correctamente"
            ];
        }
        catch(\Exception $e)
        {
            return [
                'success' => false,
                'message' => 'Ocurrio un error al intentar eliminar un usuario',
                'error'   => $e->getMessage()
            ];
        }
    }
    
}