<?php

namespace App\Http\Controllers;

use App\Http\Services\AuthService;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use PHPOpenSourceSaver\JWTAuth\Exceptions\JWTException;
use PHPOpenSourceSaver\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Redirect;
use Exception;

class AuthController extends Controller
{

    protected $tokenService;

    public function __construct(AuthService $tokenService)
    {
        $this->tokenService = $tokenService;
    }

    public function parseToken(Request $request)
    {
        $token = $request->input('tokens');
        //token驗證
        $user = $this->tokenService->parseTokenAndValidate($token);

        if ($user) {
            Auth::login($user);
            if (Auth::check()) {
                if ($user->role == "admin") {
                    return redirect('/AdminChemicalBase');
                }
                return redirect('/dashboard');
            }
        }
        // return redirect()->back()->withErrors(['']);
    }

    public function logout(Request $request)
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        return response()->json([
            'status' => 'success',
            'message' => 'Successfully logged out',
        ]);
    }

    public function refresh()
    {
        return response()->json([
            'status' => 'success',
            'user' => Auth::user(),
            'authorisation' => [
                'token' => Auth::refresh(),
                'type' => 'bearer',
            ]
        ]);
    }
    public function login($token)
    {

        try {
            $userData = JWTAuth::setToken($token)->getPayload();
            
        } 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['password'] = Hash::make($parent['tax_number']);
                $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['account'] = $userData['email'];
            $data['password'] = Hash::make($data['tax_number']);
            $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);
        $u_data = User::find($uid);

        // Auth::login($u_data);
        // session(['user' => $u_data]);
        if($u_data->role == "admin") {
            return redirect('/AdminChemicalBase');
        }
        return redirect('/dashboard');
    }

    
    public function login_pro($token)
    {
        try {
            $userData = JWTAuth::setToken($token)->getPayload();
        } catch (Exception $e) {
            return Redirect::back()->withErrors(['incorrect' => "Token Invalid"]);
        }
        //TODO 接收資料比對資料庫
        $data_check = User::where('uuid', $userData['uuid'])->first();

        if(!$data_check){
            //$sub_user_id
            return Redirect::back()->withErrors(['incorrect' => "登入驗證失敗"]);
        }
        $uid=$data_check->id;
        
        Auth::guard('web')->loginUsingId($uid, true);
        $u_data = User::find($uid);
        // Auth::login($u_data);
        // session(['user' => $u_data]);

        if($u_data->role == "admin")
        {
            return redirect('/AdminChemicalBase');
        }
        else{
            return redirect('/dashboard');
        }
        
    }

    public function getOperateUser()
    {
        $user = Auth::user();
        return $this->tokenService->getOperateUser($user);
    }

    public function getchildcompanyForReport()
    {
        $user = Auth::user();
        return $this->tokenService->getchildcompanyForReport($user);
    }
}
