<?php  
namespace App\Business\CustomerProfile\Customer;

use App\Business\CustomerProfile\GasStation\GasStationGetter;
use App\Business\CustomerProfile\Survies\SurveyGetter;
use App\Models\Customer;
use Illuminate\Support\Facades\Auth;
use App\Models\Entities\OsType;
use App\Models\Entities\DeviceType;
use Exception;
use PHPOpenSourceSaver\JWTAuth\Facades\JWTAuth;

class CustomerService
{
    public static function makeLogin($request){
        $customerInfo = self::getcustomerInfo($request);
        $customer = self::saveUser($customerInfo);
        $token = Auth::guard('customer')->setTTL(1440)->login($customer);

        $user = auth()->setToken($token)->user();

        return self::respondWithToken($token, $user);
    }

    public static function getAllData($qrToken){
        try {
            $user = Auth::guard('customer')->user();
            $station = GasStationGetter::getGasStationByToken($qrToken);
            if (!$station) throw new Exception("Internal gas station error", 1);

            $questions = SurveyGetter::getQuestionsBySurvey($station->survey);

            return ['station' => $station, 'questions' => $questions];
        } catch (Exception $e) {
            throw new Exception($e->getMessage(), 1);
        }
        
    }

    private static function saveUser($data){
        $customer = Customer::create([
            'device_type' => $data->device,
            'so_type' => $data->os,
            'IP' => $data->ip
        ]);

        return $customer;
    }

    private static function getcustomerInfo($request){
        $ip = $request->ip();
        $userAgent = $request->header('User-Agent');

        $os = OsType::Unknown->value; //'Unknown OS';
        $device = DeviceType::Unknown->value; //'Unknown Device';

        if (preg_match('/Windows NT/i', $userAgent)) {
            $os = OsType::Windows->value;//'Windows';
        } elseif (preg_match('/Mac OS X/i', $userAgent)) {
            $os = OsType::MacOS->value;//'MacOS';
        } elseif (preg_match('/Android/i', $userAgent)) {
            $os = OsType::Android->value;//'Android';
        } elseif (preg_match('/iPhone|iPad|iPod/i', $userAgent)) {
            $os = OsType::IOS->value;//'iOS';
        } elseif (preg_match('/Linux/i', $userAgent)) {
            $os = OsType::Linux; //'Linux';
        }

        if (preg_match('/Mobile|Android|iPhone|iPad|iPod/i', $userAgent)) {
            $device = DeviceType::Mobile->vslue;//'Mobile';
        } else {
            $device = DeviceType::Desktop->value;//'Desktop';
        }

        return (object) [
            'ip' => $ip,
            'os' => $os,
            'device' => $device,
        ];
    }

    private static  function respondWithToken($token)
    {
        return [
            'access_token' => $token,
            'expires_in' => 1440
        ];
    }
}
