<?php

namespace app\api\controller\v1;

use app\api\ApiController;
use think\facade\Db;
use think\facade\Cache;

// use Lcobucci\JWT\Parser;
// use thans\jwt\facade\JWTAuth;

// use Firebase\JWT\JWT;
// use Firebase\JWT\Key;
use \asc\line\LineLogin;
use app\common\sms\Sms;
use app\common\lib\Token;
// use app\common\lib\Aes;

class Auth extends ApiController
{
    //帳號登入

    public function login()
    {
        $username = input('username');
        $password = input('password');

        //檢查帳號密碼
        $verify = Cache::get($username);
        if(!isset($verify) || $verify['code']!=$password){
            return $this->error('帳號或密碼錯誤', 401);
        }
        Cache::delete($username);
        
        $user = Db::name('user')
            ->where('phone', $username)
            ->find();

        if (!$user) {
            return $this->success('非會員', 201);
        }

        $payload = [
            'user_id' => $user['user_id'],
        ];

        $token = Token::genToken($payload);

        // if(empty($user['uniqid'])){
        //         return $this->success(['uid'=>$user['user_id'],'token'=>'Bearer '.$token],202);
        // }

        return $this->success(['uid' => $user['user_id'], 'token' => 'Bearer ' . $token]);
    }
    /**
     * Line 登入
     */
    public function lineLogin()
    {
        $id_token = input('token');
        $line_id = input('line_id');

        $line_res = LineLogin::verifyIdToken('1657876696', $id_token);

        if (!$line_res) {
            return $this->Error('發生錯誤，請重新執行', 401);
        }

        $user = Db::name('user')
            ->where('line_id', $line_res['sub'])
            ->find();

        if (!$user) {
            return $this->success('非會員', 201);
        }


        $payload = [
            'id' => $user['id'],
            'user_id' => $user['user_id'],
        ];

        $token = Token::genToken($payload);

        // if(empty($user['uniqid'])){
        //         return $this->success(['uid'=>$user['user_id'],'token'=>'Bearer '.$token],202);
        // }

        return $this->success(['uid' => $user['user_id'], 'token' => 'Bearer ' . $token]);
    }

    public function checkPhone(){
        $phone=input('phone');
        $id_token = input('token');
        
        $user = Db::name('user')
        ->where('phone',$phone)
        ->find();

        if(!$user){
            return $this->success('非會員',201);
        }

        if(strlen($user['line_id'])>0){
            return $this->success('已綁定Line',202);
        }

        //更新Line資料
        $line_res = LineLogin::verifyIdToken('1657876696', $id_token);
        if(!$line_res){
            return $this->Error('發生錯誤，請重新執行',401);
        }
        $data = [
            'line_id'=>$line_res['sub'],
            'line_name'=>$line_res['name'],
            'create_time'=>date('Y-m-d H:i:s')
        ];
        $avatar=isset($line_res['picture'])?$this->saveLineImage($line_res['picture'],$line_res['sub']):'';
        if(!empty($avatar)){
            $data['line_picture']= getUrl().'/storage/'.$user['user_id'].'/'.$avatar;
        }else{
            $data['line_picture']='';
        }

        if(empty($user['avatar'])){
            $data['avatar']=$data['line_picture'];
        }
        Db::name('user')
        ->where('phone',$phone)
        ->update($data);

        $payload = [
            'id' => $user['id'],
            'user_id' => $user['user_id'],
        ];

        $token = Token::genToken($payload);


        return $this->success(['uid' => $user['user_id'], 'token' => 'Bearer ' . $token]);

    }

    public function logout()
    {
        return $this->success('請求成功');
    }

    public function checkToken()
    {
        $token = input('token');
        $result = Token::check($token);
        if (!$result) {
            return $this->error('Token無效');
        }
        return $this->success('請求成功');
    }

    public function sendVerify()
    {
        $username = input('username');

        //在這裡檢查是否已經發送過驗證碼，如果已經發送過，則不再發送
        $verifyData = Cache::get($username);

        if ($verifyData) {
            if (time() - $verifyData['time'] < 60) {
                $countdown = 60 - (time() - $verifyData['time']);
                return $this->error(['countdown'=>$countdown], 201,'請求時間過短，請稍後再試');
            }
        }else{
            //清除舊的驗證碼
            Cache::delete($username);
        }

        // 驗證碼不存在或已過期
        // 重新生成驗證碼並存儲到Redis中
        $verification_code = mt_rand(100000, 999999);
        $message = '[SlashCard]' . $verification_code . '簡訊登入驗證碼，請於5分鐘內輸入驗證碼完成登入。';
        // 發送短信
        $debug = env('asc.sms_disable');
        $debug = false;
        if(!$debug){
            Sms::createSms(
                'smsking',
                [
                    'recipient' => $username,
                    'message' => $message
                ]
            );    
        }else{
            $verification_code = '123456';        
        }
        Cache::set($username, ['code' => $verification_code, 'time' => time()], 300);

        return $this->success('請求成功');
    }

    private function saveLineImage($pictureUrl,$uid)
    {
			if($pictureUrl){
		    	$curl = curl_init($pictureUrl);
		    	curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
		    	$imageData=curl_exec($curl);
		    	curl_close($curl);

		    	$filename=$uid."_line.jpg";
		    	$filedir=$_SERVER['DOCUMENT_ROOT'].'/storage/'.$uid;
			    if (!file_exists($filedir)) {
			        mkdir($filedir , 0777 , true);
			    }
		    	$fp=fopen($filedir.'/'.$filename,'a');
		    	fwrite($fp,$imageData);
		    	fclose($fp);

				return $filename;
			}else{
				return false;
			}
    }

}
