<?php

namespace App\Http\Controllers;

use Carbon\Carbon;
use App\Models\Tag;
use App\Models\Survey;
use Illuminate\Http\Request;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class HealthyPassPortController extends Controller
{
    private $api_header = array();
    private $tag_set = array();

    public function __construct()
    {
        $this->api_header = [
            'Authorization' => 'Bearer ' . config('botApi.botToken'),
            'Accept'        => 'application/json'
        ];
    }
    public function sticker(Request $request){
        $headSticker = $request->headSticker; //頭貼
        $profile = Survey::where('line_user_id',$request->lineUserId)->first();
        $profile->head_sticker = $headSticker;
        $profile->save();
        return response()->json(["data" => $profile] );
    }

    public function profile(Request $request){
        $profile = Survey::where('line_user_id',$request->lineUserId)->first();
        if(!empty($profile->id)){
            $profile->filler_content = json_decode($profile->filler_content, true);
            $this->botActionsSend($request->lineUserId,[$this->buildActionsRequest("setMenu", config("botApi.setMenuDoneSurvey"))]);
        }
        return response()->json(["data" => $profile] );
    }

    /**
     * 送出問卷
     *
     */
    public function post(Request $request){
        $lineUserId = $request->lineUserId; //line UID
        $headSticker = $request->headSticker ?? ""; //頭貼
        $healthAction = $request->healthAction; //平常你有什麼健康行動（複選）
        $healthTopic = $request->healthTopic; //你對什麼健康話題有興趣（複選）
        $healthStatus = $request->healthStatus; //你覺得自己的身體狀況如何
        $healthAdapt = $request->healthAdapt; //面對疫情趨緩，以下哪一個敘述最符合你的應對
        $healthThought = $request->healthThought; //下列哪一個敘述最符合你的想法
        $healthAge = $request->healthAge; //你的年齡
        $healthNickname = $request->healthNickname; //暱稱
        $healthGender = $request->healthGender; //性別
        $healthGenderRole = $request->healthGenderRole;//性別 male or female

        $survey_fill_content = ["healthAction" => $healthAction,
                                "healthTopic" => $healthTopic,
                                "healthStatus" => $healthStatus,
                                "healthAdapt" => $healthAdapt,
                                "healthThought" => $healthThought,
                                "healthAge" => $healthAge,
                                "healthGender" => $healthGender,
        ];
        $survey_data = Survey::where('line_user_id',$lineUserId)->first();
        if(!empty($survey_data->id)){
            $filler_content = json_decode($survey_data->filler_content, true);
            $clearAction = [];
            foreach($filler_content as $key => $content){
                array_push($clearAction, $this->buildActionsRequest("removeTag", $content));
            }
            $statusCode = $this->botActionsSend($lineUserId,$clearAction);
        }

        //準備將填寫內容過API寫入 botbonnie 後台
        $buildActions = [];
        array_push($buildActions, $this->buildActionsRequest("addTag", $healthAction));
        array_push($buildActions, $this->buildActionsRequest("addTag", $healthTopic));
        array_push($buildActions, $this->buildActionsRequest("addTag", $healthStatus));
        array_push($buildActions, $this->buildActionsRequest("addTag", $healthAdapt));
        array_push($buildActions, $this->buildActionsRequest("addTag", $healthThought));
        array_push($buildActions, $this->buildActionsRequest("addTag", $healthAge));
        array_push($buildActions, $this->buildActionsRequest("addTag", $healthGender));
        if($healthGenderRole != "")array_push($buildActions, $this->buildActionsRequest("saveParams", $healthGenderRole, "demographics", "gender"));

        $statusCode = $this->botActionsSend($lineUserId,$buildActions);
        if($statusCode == 200){
            //確認完成填寫問卷後，建立完成問券標籤
            $buildActions = [];
            array_push($buildActions, $this->buildActionsRequest("addTag", config("botApi.doneSurvey")));
            array_push($buildActions, $this->buildActionsRequest("setMenu", config("botApi.setMenuDoneSurvey")));
            $this->botActionsSend($lineUserId,$buildActions);

            //儲存填寫資料
            if(empty($survey_data->id)){
                $survey_data = new Survey();
            }
            $survey_data->line_user_id = $lineUserId;
            $survey_data->head_sticker = $headSticker;
            $survey_data->nickname = $healthNickname;
            $survey_data->filler_content = json_encode($survey_fill_content);
            $survey_data->save();
            return  response()->json(["result" => 'successed']);
        }else{
            return response()->json(["result" => 'failed'] );
        }
    }
    public function clearProfile(Request $request){
        $lineUserId = $request->lineUserId; //line UID
        $survey_data = Survey::where('line_user_id',$lineUserId)->first();
        if(!empty($survey_data->id)){
            $filler_content = json_decode($survey_data->filler_content, true);
            $clearAction = [];
            foreach($filler_content as $key => $content){
                array_push($clearAction, $this->buildActionsRequest("removeTag", $content));
            }
            array_push($clearAction, $this->buildActionsRequest("removeTag", config("botApi.doneSurvey")));
            array_push($clearAction, $this->buildActionsRequest("setMenu", "default"));

            $statusCode = $this->botActionsSend($lineUserId,$clearAction);
            if($statusCode == 200){
                $survey_data->delete();
            }
        }
    }

    function buildActionsRequest($type, $values, $groupId = null, $paramName = ""){
        if($type == "addTag" || $type == "removeTag"){
            if(is_array($values)){
                $tags = $values;
            }else{
                $tags = [$values];
            }
            return [
                "type" => $type,
                "value" => $tags
            ];
        }elseif($type == "saveParams"){
            return [
                "type" => $type,
                "groupId" => $groupId,
                "values" => [
                    [
                        "name" => $paramName,
                        "value" => $values
                    ]
                ]
            ];
        }elseif($type == "setMenu"){
            return [
                "type" => $type,
                "platform" => 1,
                "value" => $values
            ];
        }
    }

    function botActionsSend($lineUserId, $actions){

        $tagType = [];
        foreach ($actions as $k => $action) {
            if (!isset($tagType[$action['type']])) {
                $tagType[$action['type']] = [];
            }
            switch ($action['type']) {
                case "addTag":
                case "removeTag":
                    foreach ($action['value'] as $value) {
                        $tagType[$action['type']]['value'][] = $value;
                    }
                    unset($actions[$k]);
                    break;
            }
        }

        $mergeData = [];
        if (isset($tagType['addTag'])) {
            $mergeData[] = [
                'type' => 'addTag',
                'value' => $tagType['addTag']['value']
            ];
        }
        if (isset($tagType['removeTag'])) {
            $mergeData[] = [
                'type' => 'removeTag',
                'value' => $tagType['removeTag']['value']
            ];
        }

        $actions = array_merge($actions, $mergeData);

        $actions = array_values($actions);

        $client = new Client();
        $res_users = $client->request('POST', config('botApi.botActions'),[
            'headers'=>$this->api_header,
            'json' => [
                'userId' => $lineUserId,
                'pageId' => config('botApi.lineOAId'),
                'platform' => 1,
                'actions' => $actions
            ]
        ]);
        $statusCode = $res_users->getStatusCode();

        return $statusCode;
    }
}
