<?php

namespace App\Http\Controllers\front;

use App\Http\Controllers\Controller;
use App\Models\Member;
use App\Models\Promocode;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class MemberController extends Controller
{
    /**
     * Summary of index member 首頁
     * @return mixed  arrray promocode
     * @return mixed|\Illuminate\Contracts\View\View|\Illuminate\Http\RedirectResponse
     */
    public function index()
    {
        $user = Auth::guard('member')->user();

        if (! $user) {
            Auth::guard('member')->logout();
            return redirect()->route('login');
        }

        $user_id = $user->id;
        $today   = Carbon::today()->format('Y-m-d');

        // 建立一個回傳符合條件的 Promocode 的 function
        $getAvailableCode = function ($from) use ($today) {
            return Promocode::where('used_count', 0)
                ->where('from', $from)
                ->whereDate('valid_from', '<=', $today)
                ->whereDate('valid_to', '>=', $today)
                ->latest()
                ->first();
        };

        // 試著找一個未使用的
        $code    = $getAvailableCode('cafeg');
        $teacode = $getAvailableCode('teamaster');

        // 如果找不到，就再次找一個未使用的然後標記成首次給予
        if (! $code) {
            $code = $getAvailableCode('cafeg');
            if ($code) {
                $code->give_to    = '首次';
                $code->used_count = $user_id;
                $code->save();
            }
        }

        if (! $teacode) {
            $teacode = $getAvailableCode('teacode');
            if ($teacode) {
                $teacode->give_to    = '首次';
                $teacode->used_count = $user_id;
                $teacode->save();
            }
        }

        return view('front.member.index', [
            'code'    => $code,
            'teacode' => $teacode,
        ]);
    }

    /**
     * Summary of profile 登入後個人資訊沒有menu
     * @return \Illuminate\Contracts\View\View
     */
    public function profile()
    {
        return view('front.member.profile');
    }
    /**
     * Summary of profileUpdate
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\RedirectResponse
     * @todo  目前沒有錢包與購買方案與report 以後要 一起下壓
     * @method put
     */
    public function profileUpdate(Request $request)
    {
        // 驗證輸入的數據
        $validatedData = $request->validate([
            'email'    => 'required|email',
            'password' => 'nullable|min:6', // password 與 password_confirmation 必須匹配
            'phone'    => 'nullable|string|max:15',
        ]);

        $auth = Member::find(Auth::guard('member')->id());

        // 檢查是否已有其他會員使用相同的 email
        $user = Member::where('email', $validatedData['email'])->first();

        if ($user && $user->id != $auth->id) {
            // 如果該 Email 已被其他用戶使用，返回錯誤信息
            return response()->json(['status' => 'error', 'msg' => '該 Email 已被其他帳戶使用'], 422);
        }

        // 更新當前用戶的資料
        $auth->email = $validatedData['email'];
        if ($request->has('password')) {
            $auth->password = Hash::make($validatedData['password']);
        }
        $auth->phone = $validatedData['phone'] ?? $auth->phone;

        // 保存更改
        $auth->save();

        return response()->json(['status' => 'success', 'msg' => '更新成功']);
    }
    /**
     * Summary of pageProfile 個人資訊 has menu
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Contracts\View\View
     */
    public function pageProfile(Request $request)
    {

        return view('front.member.page-profile');
    }

    public function checkPhone(Request $request)
    {
        $validatedData = $request->validate([
            'phone' => 'required|string|max:15',
        ]);
        \Log::info('checkPhone', []);
        $user = Member::where('phone', $validatedData['phone'])->first();

        if ($user) {
            return response()->json(['status' => 'error', 'msg' => '該電話號碼已被其他帳戶使用']);
        }

        return response()->json(['status' => 'success', 'msg' => '該電話號碼可用']);
    }

    public function checkEmail(Request $request)
    {

        $user = Member::where('email', $request->email)->first();

        if ($user) {
            return response()->json(['status' => 'error', 'msg' => '該email已被其他帳戶使用']);
        }

        return response()->json(['status' => 'success', 'msg' => '該email號碼可用']);
    }

    public function changeLevel(Request $request)
    {
        $user        = Member::find($request->id);
        $user->level = $request->level;
        $user->save();
        return response()->json(['status' => 'success', '成功', 'level' => $request->level, 'name' => $user->level_name]);
    }
}
