<?php
namespace App\Http\Controllers\front;

use App\Http\Controllers\Controller;
use App\Models\Member;
use Illuminate\Http\Request;
use Exception;
use App\Models\EmailVerifications;
use Mail;
use Log;
use Auth;
use Str;
class RegisterController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        return view('front.member.auth-register');
    }

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

        $newUser = Member::create([
            'name' => $request->name,
            'password' => bcrypt($request->password),
            'avatar' => $request->avatar ?? '',
            'email' => $request->email ?? '',
            'source' => 'cafeg',
            'phone' => $request->phone ?? '',
        ]);

            return redirect()->route('login')->with('sucess', '完成註冊,請登入');


    }


    /**
     * Summary of forgotPassword 設定密碼頁面
     * @param mixed $id
     * @param mixed $token
     * @param \Illuminate\Http\Request $request
     * @return mixed
     */
    public function forgotPassword(Request $request)
    {

        return view('front.auth.forgot-password');
    }

    public function sendForgotPassword(Request $request)
    {
        Log::info('sendForgotPassword', []);
        $subject = "卡菲姬系統-密碼重新設定";
        $token = Str::random(32);
        $result = Member::where('email', $request->email)->firstOrFail();

        try {
            if (!isset($result)) {
                throw new Exception("找不到帳號", 404);
            } else {
                $verificationLink = route('change.password', ['token' => $token, 'id' => $result->id]);

                Log::info('sendForgotPassword go EmailVerifications', []);
                $res = EmailVerifications::where('email', $request->email)->first();
                if ($res) {

                    $res->email = $request->email;
                    $res->token = $token;
                    $res->save();

                } else {
                    EmailVerifications::create([
                        'email' => $request->email,
                        'token' => $token,
                    ]);

                }


            }
            // 郵件內容
            $message = "您好，\n\n請點擊以下鏈更換您的電子郵件地址：\n\n" . $verificationLink . "\n\n如果您未請求此操作，請忽略此郵件。\n\n感謝您！";
            // 發送電子郵件
            Mail::to($request->input('email'))->send(new \App\Mail\CustomMail($subject, $message));
            return response()->json(['status' => 'success', 'msg' => '郵件發送成功']);
        } catch (Exception $e) {
            Log::error('Failed to send mail', ['error' => $e->getMessage()]);
            return response()->json(['status' => 'error', 'msg' => '郵件發送失敗，請稍後再試！', 'error' => $e->getMessage()], 500);
        }
    }

    public function resetPassword(Request $request)
    {
        $valid = true;
        $request->validate([
            'token' => 'required',
        ]);

        $emailVerification = EmailVerifications::where('token', $request->token)->first();

        if (!$emailVerification) {
            $valid = false;
        }

        $member = Member::where('email', $emailVerification->email)->firstOrFail();

        if (!$member) {
            $valid = false;
        }

        // 刪除使用過的令牌
        $emailVerification->delete();

        if ($valid == true) {

            return redirect()->route('change.password', ['id', $member->id]);


        } else {

            return redirect()->route('login')->with('error', '驗證密碼token 失敗');
        }


    }
    /**
     * Summary of changePassword view
     * @param   $id
     * @param \Illuminate\Http\Request $request
     * @return mixed
     */
    public function changePassword(Request $request)
    {

        Log::info('request on changePassword : ', $request->all());

        return view('front.auth.confirmpassword', ['id' => $request->id]);
    }


    /**
     * Summary of resetPasswordProcess
     * @param mixed $id
     * @method put
     * @param \Illuminate\Http\Request $request
     * @return mixed
     */
    public function resetPasswordProcess(Request $request)
    {

        if ($request->has('id')) {
            $member = Member::where('id', $request->id)->first();
            $member->password = bcrypt($request->password);
            $member->save();
            if ($member) {
                EmailVerifications::where('email', $member->email)->delete();
            }

            Auth::guard('member')->login($member);

        }

        return redirect()->route('member.index');

    }

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

    }

    /**
     * Display the specified resource.
     */
    public function show(Member $member)
    {
        //
    }

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

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

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