<?php

namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Illuminate\Pagination\Paginator;
use Illuminate\Pagination\LengthAwarePaginator;

class VehiculosUpdateController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
       // $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */


    public function vehiculosupdate($id,$estatus,$user){


        //consultamos el id de usuario en sigo en relalación al user de sigi
       
          $nameSigoSQL=DB::select("SELECT * FROM users WHERE name='$user'");

           if(count($nameSigoSQL)>0){

               $IdSigo=$nameSigoSQL[0]->pk_user;
           }else{
           
              $IdSigo=1954; //usuario interno de no encontrado
           }

         


          $vehicles=DB::select("SELECT * FROM vehicles where pk_vehicle=$id and fk_vehicle_status in(3,6,1) and fk_vehicle_status_group=1");

          $validaEstatus=array();

            if(count($vehicles)>0 && $estatus!=""){

                //consultanos los estatus disponibles
                 $vehiclesEstatus=DB::select("SELECT pk_vehicle_status FROM vehicle_status");

                // print_r($vehiclesEstatus);

                  foreach ($vehiclesEstatus as $key => $value) {

                      array_push($validaEstatus,$value->pk_vehicle_status);
                 
                  }

                  if (in_array($estatus, $validaEstatus)){

                         DB::table('vehicles')->where('pk_vehicle', $id)->update( array('fk_vehicle_status' =>$estatus));

                        $vehicles_history=DB::select("SELECT  pk_vehicle_history from vehicle_history vh where vehicle_id =$id order by pk_vehicle_history desc limit 1");

                         if(count($vehicles_history)){

                             //actualizamos el histórico en relación al usuario
                             $id_hist=$vehicles_history[0]->pk_vehicle_history;

                             DB::table('vehicle_history')->where('pk_vehicle_history', $id_hist)->update(array('fk_user' =>$IdSigo));

                         }

              
                    return "Vehículo actualizado";


                  }else{

                    return "No se puede actualizar el id_vehiculo: $id a estatus $estatus";
                  }

             
            }else{



                return "El id de Vehículo no existe";
            }


    }



   
}
