<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\City;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class CityController extends Controller
{

    public function show()
    { 
        $DatabaseController = new DatabaseController();
        return view('cities', [        
            'cities' => $DatabaseController->getNewestWeatherDataForAllCities()
        ]);
    }        

    public function create(Request $request) {     
        $request->validate([
            'name' => 'required|max:85|regex:/^[a-zA-Z\säöüÄÖÜß]+$/',
        ]);

        $city = $request->name; 

        $response = WeatherstackController::requestByCity($city);

        $WeatherstackController = new WeatherstackController();
        $isValidResponse = $WeatherstackController->checkResponse($city, $response);

        ($isValidResponse[0]) ? DatabaseController::store($response) : redirect('/')->withErrors(['name' => $isValidResponse[1]]);

        return redirect('/');
    }

    public function delete($id) {
        City::findOrFail($id)->delete();

        return redirect('/');
    }   

    public function refresh() {    
        $cities = DB::table('cities')
            ->select('id', 'location_name', 'location_country')
            ->get();
        
        foreach ($cities as $city) {
            $city = "$city->location_name,$city->location_country";

            $response = WeatherstackController::requestByCity($city);
            
            ($response->successful() === false) ? redirect('/')->withErrors(['name' => "Aktualisierung fehlgeschlagen"])
                                                : DatabaseController::store($response);
        }
        
        return redirect('/');
    }

    public function setup() {
        $credentials = [
            'email' => 'admin@admin.com',
            'password' => 'password'
        ];
    
        if (!Auth::attempt($credentials)) {
            $user = new \App\Models\User();
    
            $user->name = 'Admin';
            $user->email = $credentials['email'];
            $user->password = Hash::make($credentials['password']);
        
            $user->save();
    
            if (Auth::attempt($credentials)) {
                $user = Auth::user();
    
                $adminToken = $user->createToken('admin-token', ['create','update','delete']);
                $updateToken = $user->createToken('update-token', ['create','update']);
                $basicToken = $user->createToken('basic-token', ['none']);
    
                return [
                    'admin' => $adminToken->plainTextToken,
                    'update' => $updateToken->plainTextToken,
                    'basic' => $basicToken->plainTextToken,
                ];
            }
        }
    }

}