<?php

namespace App\Http\Services;

use App\Http\Repositories\AuthRepository;
use Exception;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;


class AuthService
{
    protected $companyRepository;
    protected $secretKey = '5nNRgb2eDbpviXaPk2rcRe3lmZbuzJYPxb9HDYfxlVMr3vrzbWlGnfCQj1q4iDmC';

    public function __construct(AuthRepository $companyRepository)
    {
        $this->companyRepository = $companyRepository;
    }

    public function parseTokenAndValidate($token)
    {
        try {
            //解析傳入的token
            $decoded = $this->decodeToken($token);
            $decodedArray = (array) $decoded;
            //判斷token有沒有符合
            $users = $this->companyRepository->findUser($decodedArray['uuid']);

            //有
            if ($users && $users->id) {
                return $this->updateUser($decodedArray);
                //沒有
            } else {
                return $this->registerNewUser($decodedArray);
            }
        } catch (Exception $e) {

            return [
                'status' => 'error',
                'message' => 'Invalid token',
            ];
        }
    }


    public function decodeToken($token)
    {
        return JWT::decode($token, new Key(env('JWT_SECRET'), 'HS256'));
    }

    //註冊新使用者
    public function registerNewUser(array $data)
    {
        
        $belong = null;
        
        //判斷有沒有母公司
        if (isset($data['belongs_parent']) && !empty($data['belongs_parent'])) {
            $parent = $this->companyRepository->findUser($data['belongs_parent']->uuid);
            //沒有，傳入母公司資料註冊
            if (!$parent) {
                $belong = $this->companyRepository->store((array)$data['belongs_parent'],$belong);
                $belong = $belong->id;
            }
            //有，更新母公司資料
            else {
                $this->updateUser((array)$data);
                $belong = $parent->id;
            }
        }
        
        $user = $this->companyRepository->store($data, $belong);
        return $user;
    }

    public function updateUser(array $data)
    {
        
        //找使用者資料
        $user = $this->companyRepository->findUser($data['uuid']);
        if ($user) {
            //如果belongs_parent非空更新母公司資料
            if (!empty($data['belongs_parent'])) {
                $belong = $this->companyRepository->findUser($data['belongs_parent']->uuid);
                if ($belong) {
                    
                    $fieldsToUpdate = [
                        'email',
                        'contact_name',
                        'name',
                        'phone',
                        'tax_number',
                        'role',
                    ];
                    $updateData = array_filter((array)$data['belongs_parent'], function($key) use ($fieldsToUpdate) {
                        return in_array($key, $fieldsToUpdate);
                    }, ARRAY_FILTER_USE_KEY);
                    $this->companyRepository->updateUser((array)$updateData, $belong->id);

                    $data['belongs_parent'] = $belong->id;
                }
                $data['belongs_parent'] = $belong->id ?? null;
            }
            $data['belongs_parent'] = $belong->id ?? null;
            $this->companyRepository->updateUser($data,$user->id);
            return $user;
        }
        return null;
    }

    function getOperateUser($user)
    {
        return $this->companyRepository->getOperateUser($user);
    }

    function getchildcompanyForReport($user){
        return $this->companyRepository->getchildcompanyForReport($user);
    }
}
