<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Redirect;
use Tymon\JWTAuth\Facades\JWTAuth;
use App\Models\User;
use Exception;

class AuthController extends Controller
{
    public function test_login()
    {
        $user = User::where('uuid', 'QweVbk6O285ztLA716xTet6d1J6h8ZbiLZ4ZmQQdO0kwVP1rsn0j9mG0gtZrKKEK')->first();

        if (!$user) {
            return response()->json(['message' => 'Invalid UUID'], 401);
        }

        $token = Str::random(60);
        $user->api_token = $token;
        $user->save();
    
        Auth::guard('web')->loginUsingId($user->id, true);

        return response()->json([
            'token' => $token,
            'user' => $user,
        ]);
    }

    public function login($token)
    {
        try {
            $userData = JWTAuth::setToken($token)->getPayload();
            
            // $userData = User::where('uuid', 'QweVbk6O285ztLA716xTet6d1J6h8ZbiLZ4ZmQQdO0kwVP1rsn0j9mG0gtZrKKEK')->first();
        } catch (Exception $e) {
            return Redirect::back()->withErrors(['incorrect' => "Token Invalid"]);
        }
		//判斷uuid ，在判斷role，若role不是審核員及查核員，則為母公司帳號
		//若role是審核員及查核員，則找事業單位ID，
        /* 流程
            -進入先判斷該名User在資料庫中有無有uuid
                 -抓取該名User的belongsParent是否存在
                    -判斷該母公司在資料庫中有無uuid
                        -有：該母帳號之前有登入過，僅需更新資料
                        -無：該母帳號第一次登入，需新建資料
                        
                -有：該名User之前有登入過，僅需更新資料
                -無：該名User第一次登入，需新建資料
        */

        $data_check = User::where('uuid', $userData['uuid'])->first();
        $data['name'] = $userData['name'];
        $data['contact_name'] = $userData['contact_name'];
        $data['tax_number'] = $userData['tax_number'];
        $data['email'] = $userData['email'];
        $data['phone'] = $userData['phone'];
        $data['role'] = $userData['role'];
        $data['belongs_parent'] = null; //事業單位user ID
        $parentData = $userData['belongsParent'];

        if ($parentData != null && is_array($parentData)) {
            $parent_check = User::where('uuid', $parentData['uuid'])->first();
            $parent['name'] = $parentData['name'];
            $parent['contact_name'] =   $parentData['contact_name'];
            $parent['tax_number'] = $parentData['tax_number'];
            $parent['email'] = $parentData['email'];
            $parent['phone'] = $parentData['phone'];
            if (!$parent_check) {
                $parentData['role'] = "admin";
                $parent['role'] = $parentData['role'];
                $parent['uuid'] = $parentData['uuid'];
                $parent['api_token'] = Str::random(64);
                $pid = User::create($parent)->id;
            } else {
                $pid = $parent_check->id;
                User::where('id', $pid)->update($parent);
            }
            $data['belongs_parent'] = $pid;
        }
        if (!$data_check) {

            $data['uuid'] = $userData['uuid'];
            $data['api_token'] = Str::random(64);
            $uid = User::create($data)->id;
        } else {
            // 更新登入用戶資料
            $uid = $data_check->id;
            User::where('id', $uid)->update($data);
        }
        Auth::guard('web')->loginUsingId($uid, true);

        return redirect('/');
    }
    
    public function logout()
    {
        Auth::logout();
        return redirect('/');
    }
}