<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Level;
use App\Models\Vehicle;
use App\Models\User;
use App\Models\UserVehicle;
use App\Library\FinancialLib;
use App\Models\Park;
use DB;
use Carbon\Carbon;

class ParkController extends Controller
{
    public function create() {
        if (!session()->has('park') || !session()->has('park.user')) {
            return redirect('/');
        }
        
        return view('parks.create');
    }
    
    public function storelocal(Request $request) {
        try {
            DB::beginTransaction();
            
            $level = Level::with('area')->find($request->get('level_id'));

            $vehicle = $this->getVehicle($request->get('vehicle_plate'), $level->tipo_veicolo_id);

            $user = $this->getUser(session()->get('park.user'), $vehicle);

            $park = $this->buildPark($user, $level, $vehicle, (object) [
                'park_date' => $request->get('park_date'),
                'from_time' => $request->get('from_time'),
                'to_time'   => $request->get('to_time'),
                'cost'      => $request->get('park_cost'),
                'lat'       => $request->get('lat'),
                'lng'       => $request->get('lng'),
            ]);
            
            $sessionData = session()->get('park');
            $sessionData['item'] = $park->id;

            session()->put('park', $sessionData);

            DB::commit();

            return redirect('payment/createlocal');
        } catch (\Exception $ex) {
            if (config()->get('app.debug')) {
                dd($ex);
            }
            
            DB::rollback();
            
            
        }
    }
    
    private function getVehicle($plate, $vehicleTypeId) {
        $vehicle = Vehicle::create([
                    'tipo_veicolo_id'   => $vehicleTypeId,
                    'targa'             => strtoupper($plate),
                    'fast'              => true,
                ]);
        
        return $vehicle;
    }
    
    private function getUser($userData, $vehicle) {
        $user = User::create([
            'nome'                      => '',
            'cognome'                   => '',
            'sesso'                     => '-',
            'comune_nascita'            => 0,
            'provincia_istat_nascita'   => '',
            'nazione_nascita_id'        => 380,
            'lingua_default'            => 'it',
            'telefono'                  => '',
            'fax'                       => '',
            'piva'                      => '',
            'completo'                  => '',
            'cellulare'                 => $userData['mobile'],
            'email'                     => $userData['email'],
        ]);
        
        UserVehicle::create([
            'utente_id'     => $user->id,
            'veicolo_id'    => $vehicle->id,
            'fast'          => true,
        ]);
        
        return $user;
    }
    
    private function buildPark($user, $level, $vehicle, $parkData) {
        $parkInterval = $this->getParkInterval($level, $parkData);
        
        $park = Park::create([ 
            'utente_id'     => $user->id,
            'livello_id'    => $level->id, 
            'veicolo_id'    => $vehicle->id,
            'latlng'        => $parkData->lat . ',' . $parkData->lng,
            'inizio'        => $parkInterval->start,
            'fine'          => $parkInterval->end,
            'costo'         => FinancialLib::euroToCent($parkData->cost),
            'stato'         => Park::PARK_CREATED,
            'fast'          => true,
        ]);
        
        return $park;
    }
    
    private function getParkInterval($level, $parkData) {
        switch ($level->tipo_sosta) {
            case 'std':
                $start  = Carbon::createFromFormat('d/m/Y H:i:s', $parkData->park_date . ' ' . $parkData->from_time . ':00');
                $end    = Carbon::createFromFormat('d/m/Y H:i:s', $parkData->park_date . ' ' . $parkData->to_time  . ':00');
                break;
            case 'gio':
                $start  = Carbon::createFromFormat('d/m/Y H:i:s', $parkData->park_date . ' ' . $parkData->from_time . ':00');
                $end    = Carbon::createFromFormat('d/m/Y H:i:s', $parkData->park_date . ' ' . $parkData->from_time . ':00')->addDay();
                break;
            case 'fse':
                $start  = Carbon::createFromFormat('d/m/Y H:i:s', $parkData->park_date . ' 00:00:00');
                $end    = Carbon::createFromFormat('d/m/Y H:i:s', $parkData->park_date . ' 23:59:59')->addDays(2);
                break;
            case 'set':
                $start  = Carbon::createFromFormat('d/m/Y H:i:s', $parkData->park_date . ' 00:00:00');
                $end    = Carbon::createFromFormat('d/m/Y H:i:s', $parkData->park_date . ' 23:59:59')->addDays(6);
                break;
            case 'men':
                $start  = Carbon::createFromFormat('d/m/Y H:i:s', $parkData->park_date . ' 00:00:00');
                $end    = Carbon::createFromFormat('d/m/Y H:i:s', $parkData->park_date . ' 23:59:59')->addMonth()->subDay();
                break;
        }
        
        return (object) [
            'start' => $start,
            'end'   => $end,
        ];
    }
}
