/home/dvjjulio/softtrash/app/Http/Controllers/AdminController.php
<?php

namespace Trash\Http\Controllers;

use Illuminate\Http\Request;

use Trash\Http\Requests;
use Trash\Http\Controllers\Controller;
use Trash\Histories;
use Trash\Ordenes;
use Trash\User;
use Trash\Clientes;
use Trash\Camiones;
use Trash\Reciclables;
use Trash\OrdenC;
use Auth;
use Trash\Http\Controllers\RouteController;

class AdminController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index($fecha = 'null')
    {
      if(Auth::user()->tipo_usuario_id == 3){
        return redirect('report/reportCliente');
      }
        //
        if($fecha == 'null'){
            $fecha = date('Y-m-d');
        }
        $histories = new Histories();
        $history = $histories->history_day($fecha);

        $ordenes = new Ordenes();
         $orden = $ordenes->orden_day($fecha);

        $users = User::all();
        $camiones = Camiones::all();
        $reciclables = Reciclables::all();
        $clientes = Clientes::where('status_id','=',1)->get();

        $check = new OrdenC;
        $checklist = $check->clientes_faltantes($fecha);


        return view('welcome')->with(compact('history','orden','users','clientes','camiones','reciclables','fecha','checklist'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function getOrden()
    {
        //
        $data = \Input::all();
        $ordenes = new Ordenes;
        $orden = $ordenes->getOrden($data['id'],$data['fecha']);
        return response()->json(array('status'=> true, 'data'=>$orden->getData()->data[0]));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function saveOrden()
    {
        //
        $data = \Input::all();
        $validator = $this->get_validate($data);
        if( $validator->fails() )
            return response()->json( array( 'status' => false, 'message' => $validator->errors()->all() ));
        return response()->json( $this->store($data));
    }

        public function get_validate( $data ){
        $array_rules = array(
                'id'       => 'required',
                'user'     => 'required',
                'orden'    => 'required',
                'cliente'  => 'required',
                'camion'   => 'required',
                'cantidad' => 'required',
                'km'       => 'required',
                'km_dif'   => 'required',
                 );
        $messages    =  array(
                'id.required'       => 'Hay un error Grave regresa a modificar la Orden',
                'user.required'     => 'Por favor seleccione el Usuario',
                'orden.required'    => 'Por favor ingrese la Orden',
                'cliente.required'  => 'Por favor Seleccione el Cliente',
                'camion.required'   => 'Por favor Seleccione el Camion',
                'cantidad.required' => 'Por favor ingrese la Cantidad',
                'km.required'       => 'Por favor ingrese el Kilometraje',
                'km_dif.required'   => 'Error en la Comparativa de Kilometrajes',
                 );

        return \Validator::make( $data, $array_rules, $messages );
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store($data, Ordenes $o = null)
    {
        try{
            $routeControllers = new RouteController();
            \DB::beginTransaction();
            if(  $data[ 'id' ] != 'undefined' ){
                $orden = Ordenes::find($data['id']);
            }
            /*else {
                $user = new User();
                $existUser=$this->checkUser($data);
                if( $existUser==false )throw new \Exception('Ya existe usuario: '.$data['usuario']);
            }*/

            if(Auth::user()->id == null){ throw new \Exception('La sessión ha caducado vuelve a iniciar');
              URL:To('/');
            }

            if($data['km'] > $data['km_first']){
              $dif = $data['km'] - $data['km_first'];
              $dif = $dif+$data['km_dif'];
            }else if($data['km'] < $data['km_first']){
              $dif = $data['km_first'] - $data['km'];
              $dif =  $data['km_dif'] - $dif;
            }else{
              $dif = $data['km_dif'];
            }

            if ($data['giro'] === 'Combustible') {
                if ($data['litros'] === '') {
                    throw new \Exception('Litros no puede ir vacio');
                } else if ($data['tipo'] === '') {
                    throw new \Exception('Tipo de combustible no puede ir vacio');
                } else if ($data['precio'] === '') {
                    throw new \Exception('Precio de combustible no puede ir vacio');
                } else {
                  if (!$routeControllers->createUpdateCombustible(($data))) {
                    throw new \Exception('Error combustible no puedo guardarse');
                  }
                }
            }
            if ($data['giro'] === 'Vertedero') {
                if ($data['tipo'] === '') {
                    throw new \Exception('Tipo no puede ir vacio');
                } else if ($data['peso'] === '') {
                    throw new \Exception('Peso de combustible no puede ir vacio');
                } else if ($data['precio'] === '') {
                    throw new \Exception('Precio de vertedero no puede ir vacio');
                } else {
                  if (!$routeControllers->createUpdateVertedero(($data))) {
                    throw new \Exception('Error vertedero no puedo guardarse');
                  }
                }
            }

            $orden->orden_no         = $data['orden'];
            $orden->user_id          = $data['user'];
            $orden->cliente_id       = $data['cliente'];
            $orden->camion_id        = $data['camion'];
            $orden->cantidad         = $data['cantidad'];
            $orden->km               = $data['km'];
            $orden->observaciones    = $data['obs'];
            $orden->km_dif           = $dif;
            $orden->reciclable_id    = ($data['reciclable_id']=='undefined')? '' : $data['reciclable_id'];
            $orden->peso_reciclable  = ($data['reciclable_peso']=='undefined')? '' : $data['reciclable_peso'];
            $orden->cancel           = ($data['cancel']=='undefined')? 0 : $data['cancel'];
            $orden->save();

        } catch( \Exception $e ){
            \DB::rollback();
            return array( 'status' => false, 'message' => $e->getMessage() );
        }
        \DB::commit();
        return  array( 'status' => true , 'data' => $orden );
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function reset_history_inicio($id)
    {
        //
        $histories = new Histories;
        $history = $histories->reset_inicio($id);
        return $history;

    }
    public function reset_history_termino($id)
    {
        //
        $histories = new Histories;
        $history = $histories->reset_termino($id);
        return $history;

    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}