<?php

namespace App\Services;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Facades\JWTAuth;
use App\Models\User;
use App\Models\UserPlan;
use App\Models\SubSystem;
use App\Models\UserPlanRecord;

class SubSystemService
{
    private $UserService;

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

    public function getParentId($user_id)
    {
        $user = User::with(['belongsParent', 'belongsParent.belongsParent'])->where('id', $user_id)->first();

        switch ($user->permission) {
            // case '999':
            //     $result = SubSystem::select('name', DB::raw('true as state'))->where('type', 1)->get();
            //     return $result;
            case '100':
                $parent_id = $user_id;
                break;
            case '010':
                $parent_id = optional($user->belongsParent)->id;
                break;
            case '001':
                $parent = optional($user->belongsParent);
                if ($parent->permission == '100') {
                    $parent_id = $parent->id;
                } else {
                    $parent_id = optional($parent->belongsParent)->id;
                }
                break;
        }

        return $parent_id;
    }

    public function getOneUserSubSystemState($user_id)
    {
        $user = User::with(['belongsParent', 'belongsParent.belongsParent'])->where('id', $user_id)->first();

        switch ($user->permission) {
            // case '999':
            //     $result = SubSystem::select('name', DB::raw('true as state'))->where('type', 1)->get();
            //     return $result;
            case '100':
                $parent_id = $user_id;
                break;
            case '010':
                $parent_id = optional($user->belongsParent)->id;
                break;
            case '001':
                $parent = optional($user->belongsParent);
                if ($parent->permission == '100') {
                    $parent_id = $parent->id;
                } else {
                    $parent_id = optional($parent->belongsParent)->id;
                }
                break;
        }
        
        // 建立子查詢
        $subQuery = UserPlan::where('user_plans.user_id', $parent_id)->where('user_plans.state', 1);
            
        // 主查詢
        $result = SubSystem::select('sub_systems.*', 'plan.id as user_plan_id', 'years', 'open_date', 'expiry_date')
            ->leftJoinSub($subQuery, 'plan', function ($join) {
                $join->on('plan.sub_system_id', '=', 'sub_systems.id');
            })
            ->where('type', 1)
            ->get();

        // TODO 登入子系統，並取得其token
        $tokens = $this->UserService->getSubsystemToken($user);
        $hotbee_token = $tokens['hotbee_token'];
        if ($hotbee_token) {
            $hotbeeLoginUrl = config('services.hotbee.base_url') . '/thermal/file_count';
            $response = Http::withToken($hotbee_token)->get($hotbeeLoginUrl);
            if ($response->successful()) {
                $hbFileCount = $response->json();
            }
        }
        
        // 計算加購總量
        foreach ($result as $system) {
            $items = UserPlanRecord::with('addons.item')
                ->where('user_plan_id', $system->user_plan_id)
                ->get();

            $addonTotal = [];
            foreach ($items as $item) {
                foreach ($item->addons as $addon) {
                    if (isset($addonTotal[$addon->item_id])) {
                        // $addonTotal[$addon->item_id] += $addon->amount;
                        $addonTotal[$addon->item->item_id]['amount'] += $addon->amount;
                    } else {
                        // $addonTotal[$addon->item_id] = $addon->amount;
                        $addonTotal[$addon->item->item_id] = [
                            'id' => $addon->item_id,
                            'amount' => $addon->amount
                        ];
                    }
                }
            }
            $system->addonTotal = $addonTotal;

            $system->user_plan = UserPlan::with(['items' => function ($query) {
                $query->whereHas('item', function ($subQuery) {
                    $subQuery->where('item', '!=', '手機數量');
                });
            }, 'items.item'])->where('id', $system->user_plan_id)->first();

            if ($system->user_plan) {
                if ($system->name == "HotBee") {
                    foreach ($system->user_plan->items as $item) {
                        switch ($item->item->item) {
                            case "上傳空間":
                                $item["usaged"] = $hbFileCount["data"]["gb"] ?? 0;
                                $item["unit"] = "G";
                                break;
                            case "上傳數量":
                                $item["usaged"] = $hbFileCount["data"]["qty"] ?? 0;
                                $item["unit"] = "張";
                                break;
                        }
                    }
                }else{
                    foreach ($system->user_plan->items as $item) {
                        switch ($item->item->item) {
                            case "自訂表單":
                                $item["usaged"] = 0;
                                $item["unit"] = "個";
                                break;
                            case "題數":
                                $item["usaged"] = 0;
                                $item["unit"] = "題";
                                break;
                            case "派工次數":
                                $item["usaged"] = 0;
                                $item["unit"] = "次";
                                break;
                        }
                    }
                }
            }
        }
    
        return $result;
    }
}
