<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Plan;
use App\Models\User;
use App\Models\UserPlan;
use App\Models\UserPlanAddon;
use App\Models\UserPlanItem;
use App\Models\UserPlanRecord;
use App\Models\UserPlanRecordItem;
use App\Models\UserPlanRecordAddon;
use App\Models\UserSystemRole;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Exception;
use App\Services\UserService;

class UserPlanController extends Controller
{
    private $UserService;

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

    public function userPlanActivate(Request $request)
    {
        // TODO 方案開通也需要去判斷之前有沒有開通過，如果有，則需要還原其底下的使用者狀態！！可以直接更新狀態為true，因為如果之前沒有則不會有角色紀錄
        DB::beginTransaction();
        try {
            $data = $request->all();
            $plan = Plan::with('items')->find($data['plan_id']);
            
            // order_number
            $num = UserPlan::where('sub_system_id', $plan->sub_system_id)->whereDate('created_at', '=', date("Y-m-d"))->count() + 1;
            $system_name = $plan->sub_system_id == 1 ? "PB" : "HB";
            $num_padded = str_pad($num, 2, '0', STR_PAD_LEFT);
            $order_number = $system_name.date("ymd").$num_padded;

            $user_plan = UserPlan::create([
                'user_id' => $data['user_id'],
                'sub_system_id' => $plan->sub_system_id,
                'plan_name' => $plan->name,
                'years' => $plan->years,
                'price' => $plan->price,
                'state' => $data['state'],
                'open_date' => $data['open_date'],
                'expiry_date' => $data['expiry_date'],
                'order_number' => $order_number,
            ]);

            foreach ($data['total'] as $total) {
                UserPlanItem::create([
                    'user_plan_id' => $user_plan->id,
                    'item_id' => $total['id'],
                    'amount' => $total['amount'],
                ]);
            }

            $user_plan_record_id = UserPlanRecord::create([
                'user_plan_id' => $user_plan->id,
                'sub_system_id' => $plan->sub_system_id,
                'plan_name' => $plan->name,
                'years' => $plan->years,
                'price' => $plan->price,
                'type' => 0,
                'open_date' => $data['open_date'],
                'expiry_date' => $data['expiry_date'],
                'creator' => Auth::user()->id,
            ])->id;

            foreach ($plan->items as $item) {
                UserPlanRecordItem::create([
                    'user_plan_record_id' => $user_plan_record_id,
                    'item_id' => $item->item_id,
                    'amount' => $item->amount,
                ]);
            }

            foreach ($data['addon'] as $addon) {
                UserPlanAddon::create([
                    'user_plan_id' => $user_plan->id,
                    'item_id' => $addon['id'],
                    'amount' => $addon['amount'],
                    'price' => $addon['price'],
                ]);

                UserPlanRecordAddon::create([
                    'user_plan_record_id' => $user_plan_record_id,
                    'item_id' => $addon['id'],
                    'amount' => $addon['amount'],
                    'price' => $addon['price'],
                ]);
            }

            // =======================================
            // 寫入角色及狀態
            // TODO 有個問題，當新系統導入時，原有的使用者會因為當初沒有建置新系統的角色，從而無法更新子系統角色，這邊可能需要調整

            UserSystemRole::updateOrCreate([
                'user_id' => $data['user_id'],
                'sub_system_id' => $user_plan->sub_system_id,
            ], [
                'role' => 'main',
                'state' => true,
            ]);

            $this->updaterUserSystemRole($user_plan, true);

            // TODO 這邊可以去抓子系統token以事先創建資料
            // $user = User::find($data['user_id']);
            // $this->UserService->tryLoginSubSystem($user);

            DB::commit();
        } catch (Exception $e) {
            DB::rollback();
            throw $e;
        }
    }

    public function userPlanUpdate(Request $request)
    {
        DB::beginTransaction();
        try {
            $userPlan = json_decode($request->user_plan, true);

            // dd($data);

            // type: 開通0、加購1、編輯2、續約3、取消4、過期5
            // state: 取消0、已開通1、已過期2、待開通3

            // 編輯，可以改方案&開通日期，將會重置並覆蓋當前方案，但加購項與其紀錄皆保留
            // 續約，不可以改方案與日期，僅能依當前方案直接續約

            $years = $userPlan['years'];
            $open_date = $userPlan['open_date'];

            // switch ($data['type']) {
            //     case 2:
            //         UserPlan::where('id', $data['id'])->update([
            //             'plan_id' => $data['plan_id'],
            //             'years' => $years,
            //             'open_date' => $open_date,
            //             'expiry_date' => $data['expiry_date'],
            //         ]);

            //         break;
            //     case 3:
            //         UserPlan::where('id', $data['user_plan_id'])->update([
            //             'plan_id' => $data['plan_id'],
            //             'expiry_date' => $data['expiry_date'],
            //         ]);

            //         UserPlan::where('id', $data['user_plan_id'])
            //             ->increment('years', $years);

            //         $updatedUserPlan = UserPlan::find($data['user_plan_id']);

            //         $years = $updatedUserPlan->years;
            //         $open_date = $updatedUserPlan->open_date;

            //         break;
            // }

            $user_plan = UserPlan::find($userPlan['id']);
            
            if (is_file($request->file_upload)) {
                $path = Storage::disk('public')->put('invoice', $request->file_upload);

                $user_plan->invoice = $path;
                $user_plan->save();
            }

            if ($userPlan['invoice'] == null) {
                if ($user_plan->invoice != null) {
                    Storage::delete("public/".$user_plan->invoice);
                }
                $user_plan->invoice = null;
                $user_plan->save();
            }

            $user_plan->update([
                'price' => $userPlan['price'],
                'open_date' => $open_date,
                'expiry_date' => $userPlan['expiry_date'],
            ]);

            UserPlanItem::where('user_plan_id', $userPlan['id'])->delete();
            foreach ($userPlan['total'] as $total) {
                UserPlanItem::create([
                    'user_plan_id' => $userPlan['id'],
                    'item_id' => $total['id'],
                    'amount' => $total['amount'],
                ]);
            }

            $user_plan_record_id = UserPlanRecord::create([
                'user_plan_id' => $userPlan['id'],
                'sub_system_id' => $userPlan['sub_system_id'],
                'plan_name' => $userPlan['plan_name'],
                'years' => $years,
                'price' => $userPlan['price'],
                'type' => $userPlan['type'],
                'open_date' => $open_date,
                'expiry_date' => $userPlan['expiry_date'],
                'creator' => Auth::user()->id,
            ])->id;
        
            foreach ($userPlan['items'] as $item) {
                UserPlanRecordItem::create([
                    'user_plan_record_id' => $user_plan_record_id,
                    'item_id' => $item['item_id'],
                    'amount' => $item['amount'],
                ]);
            }

            UserPlanAddon::where('user_plan_id', $userPlan['id'])->delete();
            foreach ($userPlan['addon'] as $addon) {
                UserPlanAddon::create([
                    'user_plan_id' => $userPlan['id'],
                    'item_id' => $addon['item_id'],
                    'amount' => $addon['amount'],
                    'price' => $addon['price'],
                ]);

                UserPlanRecordAddon::create([
                    'user_plan_record_id' => $user_plan_record_id,
                    'item_id' => $addon['item_id'],
                    'amount' => $addon['amount'],
                    'price' => $addon['price'],
                ]);
            }

            DB::commit();
        } catch (Exception $e) {
            DB::rollback();
            throw $e;
        }
    }

    public function userPlanCancel($user_plan_id)
    {
        // TODO 方案取消也要將底層的用戶狀態改為false
        $user_plan = UserPlan::where('id', $user_plan_id)->first();
        // $user_plan->state = 0;
        // $user_plan->save();

        // UserSystemRole::updateOrCreate([
        //     'user_id' => $user_plan->user_id,
        //     'sub_system_id' => $user_plan->plan->sub_system_id,
        // ], [
        //     'state' => false,
        // ]);
        if ($user_plan->state == 1) {
            $this->updaterUserSystemRole($user_plan, false);
        }

        $user_plan->state = 0;
        $user_plan->save();

        UserPlanRecord::create([
            'user_plan_id' => $user_plan_id,
            'sub_system_id' => $user_plan->sub_system_id,
            'plan_name' => $user_plan->plan_name,
            'years' => $user_plan->years,
            'price' => $user_plan->price,
            'type' => 4,
            'open_date' => $user_plan->open_date,
            'expiry_date' => $user_plan->expiry_date,
            'creator' => Auth::user()->id,
        ]);
    }

    public function getUserPlanRecord($user_plan_id)
    {
        $result = UserPlan::with('creator', 'subsystem', 'records.creator', 'records.items.item', 'records.addons.item')->find($user_plan_id);
        // $result = UserPlan::with('creator', 'plan.subsystem', 'records.creator', 'records.plan.items.item', 'records.items.item.item', 'records.addons.item.item')->where('id', $user_plan_id)->first();

        return response()->json(['data' => $result], 200);
    }

    public function checkUserPlanExpiry()
    {
        // 檢查方案是否過期，這一步通常為母公司階段，需要將過期的子系統狀態更新到子公司及子帳號role -> 完成
        // 看到時候要寫進去排程還是寫在某個時機點！！ -> "已經寫在排程中了"

        $user_plans = UserPlan::where('expiry_date', '<', date("Y-m-d"))
                ->where('state', 1)
                ->get();

        foreach ($user_plans as $plan) {
            $this->updaterUserSystemRole($plan, false);

            UserPlan::where('id', $plan->id)->update(['state' => 2]);

            UserPlanRecord::create([
                'user_plan_id' => $plan->id,
                'sub_system_id' => $plan->sub_system_id,
                'plan_name' => $plan->plan_name,
                'years' => $plan->years,
                'price' => $plan->price,
                'type' => 5,
                'open_date' => $plan->open_date,
                'expiry_date' => $plan->expiry_date,
                'creator' => Auth::user()->id ?? 1,
            ]);
        }
    }

    public function updaterUserSystemRole($plan, $state)
    {
        $user_ids = collect([$plan->user_id]);

        $user_ids = $user_ids->merge($plan->creator->sub->pluck('id'))
                            ->merge($plan->creator->sub->flatMap(function ($sub) {
                                return $sub->subUser->pluck('id');
                            }))
                            ->merge($plan->creator->subUser->pluck('id'));

        // UserSystemRole::whereIn('user_id', $user_ids)
        //             ->where('sub_system_id', $plan->sub_system_id)
        //             ->where('role', '<>', '')
        //             ->update(['state' =>  $state]);

        foreach ($user_ids as $user_id) {
            $user_info = User::find($user_id);

            $role = "";
            if ($user_info->permission == "010") {
                $role = "sub";
            }

            $record = UserSystemRole::where('user_id', $user_id)
                        ->where('sub_system_id', $plan->sub_system_id)
                        // ->where('role', '<>', '')
                        ->first();
        
            if ($record) {
                // 如果找到記錄，則更新 state
                if ($record->role == "") $state = false;

                $record->update(['state' => $state]);
            } else {
                // 否則新增記錄
                if ($role == "") $state = false;

                UserSystemRole::create([
                    'user_id' => $user_id,
                    'sub_system_id' => $plan->sub_system_id,
                    'role' => $role,
                    'state' => $state,
                ]);
            }

            $this->UserService->tryLoginSubSystem($user_info);
        }
    }

    public function getOneUserPlan($user_plan_id)
    {
        $result = UserPlan::with('creator', 'subsystem', 'items.item', 'addon.item', 'firstRecord.items.item')->find($user_plan_id);

        return response()->json(['data' => $result], 200);
    }

    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     */
    public function show(UserPlan $userPlan)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(UserPlan $userPlan)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, UserPlan $userPlan)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(UserPlan $userPlan)
    {
        //
    }
}
