<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\Estacionamientos;
use App\Models\Localizacion;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class EstacionamientosController extends Controller
{
    public function index()
    {
            $estacionamientos = Estacionamientos::select('tms_am_parkinglots.*', 'tms_am_entities.codename AS entity_codename', 'tms_am_entity_status.name AS name_status')
            ->join('tms_am_entities', 'tms_am_parkinglots.fk_entity_company', 'tms_am_entities.pk_entity')
            ->join('tms_am_locations', 'tms_am_parkinglots.fk_location', 'tms_am_locations.pk_location')
            ->join('tms_am_entity_status', 'tms_am_entities.fk_entity_status', 'tms_am_entity_status.pk_entity_status')
            ->with('location')
            ->with(['entities_company'=>function($query){
                $query->select("tms_am_entities.name", "tms_am_entities.pk_entity");
              }])
            ->with('vehicles')
            ->where('tms_am_parkinglots.status', true)
            ->get();
            return response()->json([
                "data" => $estacionamientos
            ]); 
    }

    public function store(Request $request)
    {
        $request->validate([
            'nombre' => 'required',
            'alquiler' => 'required',
            'corporativo' => 'required',
            'find_direccion' => 'required',
            'calle' => 'required',
            'numero' => 'required',
            'estado' => 'required',
            'pais' => 'required',
            'cp' => 'required',
        ]);

        DB::transaction(function () use ($request) {
            //$zipcode = DB::table('tms_am_zipcodes')->where('zipcode', $request->cp)->first();

            $localizacion = new Localizacion();
            $localizacion->name = $request->find_direccion;
            $localizacion->street = $request->calle;
            $localizacion->number = $request->numero;
            $localizacion->headquarters = false;
            $localizacion->cp = $request->cp;
            $localizacion->state = $request->estado;
            $localizacion->country = $request->pais;
            $localizacion->latitude = $request->latDirec;
            $localizacion->longitude = $request->lngDirec;
            $localizacion->save();
    
            $ultimo_registro_parkinglots = Estacionamientos::orderBy('pk_parkinglot', 'desc')->first();
            $estacionamiento = new Estacionamientos();
            if($ultimo_registro_parkinglots == null){
                $estacionamiento->pk_parkinglot = 1;
            }else{
                $estacionamiento->pk_parkinglot = $ultimo_registro_parkinglots->pk_parkinglot+1;
            }
            $estacionamiento->codename = $request->nombre;
            $estacionamiento->rental = $request->alquiler;
            $estacionamiento->fk_entity_company = $request->corporativo[0];
            $estacionamiento->fk_location =  $localizacion->pk_location;
            $estacionamiento->fk_unit_rental = null;
            $estacionamiento->save();

            for ($i=0; $i < count($request->corporativo); $i++) { 
                DB::table('tms_am_entity_parkinglot')->insert([
                    'fk_entity_company' => $request->corporativo[$i],
                    'fk_parkinglot' => $estacionamiento->pk_parkinglot,
                ]);
            }
        });

        return response('success', 200);
    }

    public function show($id)
    {
        $estacionamiento = Estacionamientos::select('tms_am_parkinglots.*', 'tms_am_entities.name', 'tms_am_entities.codename AS entity_codename', 'tms_am_entity_status.name AS name_status')
        ->join('tms_am_entities', 'tms_am_parkinglots.fk_entity_company', 'tms_am_entities.pk_entity')
        ->join('tms_am_locations', 'tms_am_parkinglots.fk_location', 'tms_am_locations.pk_location')
        ->join('tms_am_entity_status', 'tms_am_entities.fk_entity_status', 'tms_am_entity_status.pk_entity_status')
        ->with('location')
        ->with(['entities_company'=>function($query){
            $query->select("tms_am_entities.pk_entity")->pluck("tms_am_entities.pk_entity");
          }])
        ->where('tms_am_parkinglots.pk_parkinglot', $id)
        ->get()->first();
        return response($estacionamiento, 200);
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'nombre' => 'required',
            'alquiler' => 'required',
            'corporativo' => 'required',
            'find_direccion' => 'required',
            'calle' => 'required',
            'numero' => 'required',
            'estado' => 'required',
            'pais' => 'required',
            'cp' => 'required',
        ]);

        DB::transaction(function () use ($request, $id) {

            $updateLocalizacion = Localizacion::where('pk_location', $request->fk_location)->update([
                'name' => $request->find_direccion,
                'street' => $request->calle,
                'number' => $request->numero,
                'state' => $request->estado,
                'country' => $request->pais,
                'latitude' => $request->latDirec,
                'longitude' => $request->lngDirec,
            ]);

            $updateEstacionamiento = Estacionamientos::where('pk_parkinglot', $id)->update([
                'codename' => $request->nombre,
                'rental' => $request->alquiler,
                'fk_entity_company' => $request->corporativo[0],
                'fk_location' => $request->fk_location,
            ]);

            $unidadesEstacionamiento = Estacionamientos::findOrFail($id);
            $unidadesEstacionamiento->entities_company()->sync($request->get('corporativo'));
            return response('success', 200);
        });

        return response('success', 200);
    }

    public function destroy($id)
    {
        //Estacionamientos::findOrFail($id)->delete();
        $updateEstacionamiento = Estacionamientos::where('pk_parkinglot', $id)->update([
            'status' => false,
        ]);
        return response('success', 200);
    }
}
