<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\EmailVerifications;
use App\Models\Member;
use Auth;
use Illuminate\Support\Facades\Log;
use Exception;
use Mail;
use Str;
class EmailController extends Controller
{
    /**
     * 驗證電子郵件並更新會員狀態
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public $token;

    public function __construct()
    {

    }
    public function index(Request $request)
    {
        Log::info('Email verification request received:', $request->all());

        // 獲取當前登入的會員（若存在）
        $auth = Auth::guard('member')->user();

        // 驗證請求中是否包含 token
        $validatedData = $request->validate([
            'token' => 'required|string',
        ]);

        // 查詢對應的驗證記錄
        $check = EmailVerifications::where('token', $validatedData['token'])->first();

        if (!$check) {
            Log::warning('Invalid token provided for email verification:', ['token' => $validatedData['token']]);
            return response()->json(['status' => 'error', 'msg' => '無效的驗證連結或連結已過期'], 400);
        }

        Log::info(message: 'Email verification record found:', context: $check->toArray());

        // 查詢對應的會員
        $member = Member::where('email', $check->email)->orderBy('created_at', 'asc')->first();




        // 若當前登入用戶存在 line_id，則使用當前用戶更新
        if ($auth && isset($auth->line_id)) {
            $line_id = $auth->line_id;
        } else {
            $line_id = $member->line_id;
        }

        if ($auth && isset($auth->avatar)) {
            $avatar = $auth->avatar;
        } else {
            $avatar = $member->avatar;
        }


        // 更新會員的 Email 與驗證時間

        Log::info('Member email verification updated successfully:', $member->toArray());

        // 如果當前登入用戶與驗證的會員不同，登出當前用戶並重新登入
        if ($auth && $auth->id != $member->id) {
            // 在登出之前執行需要刪除或處理的操作
            $needdeletaccount = Auth::guard('member')->user();

            // 確保在登出前刪除帳號資料或執行其他操作
            if ($needdeletaccount) {
                $needdeletaccount->delete(); // 這會刪除登入用戶的資料
                $member->email_verified_at = now();
                $member->line_id = $line_id;
                $member->avatar = $avatar;
                Log::info('Deleted account after logout:', ['user_id' => $needdeletaccount->id]);
            }

            $member->save();

            // 登出並重新登入
            Auth::logout();
            Auth::guard('member')->loginUsingId($member->id);
            Log::info('Logged out previous user and logged in verified user:', ['user_id' => $member->id]);
        }


        // 刪除驗證記錄以防重複使用
        $check->delete();
        Log::info('Verification token record deleted successfully:', ['token' => $validatedData['token']]);

        // return response()->json(['status' => 'success', 'msg' => '電子郵件驗證成功']);

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



    }
    public function sendemail(Request $request)
    {
        Log::info('got send mail', ['function' => 'sendemail']);

        // 驗證請求數據
        $validatedData = $request->validate([
            'email' => 'required|email',
        ]);
        //判斷是否更新token

        $check = EmailVerifications::where('email', $request->email)->first();

        // 生成隨機 token
        $token = Str::random(32);

        if (!$check) {
            $check = new EmailVerifications;
        }

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

        Log::info('Generated token', ['token' => $token]);

        $subject = "卡菲姬系統-驗證email";

        // 使用 route 生成驗證鏈接
        $verificationLink = route('email.verify', ['token' => $token]);
        Log::info('Generated verification link', ['link' => $verificationLink]);

        try {
            // 郵件內容
            $message = "您好，\n\n請點擊以下鏈接以驗證您的電子郵件地址：\n\n" . $verificationLink . "\n\n如果您未請求此操作，請忽略此郵件。\n\n感謝您！";

            Log::info('Preparing to send mail', ['email' => $validatedData['email'], 'subject' => $subject, 'message' => $message]);

            // 發送電子郵件
            Mail::to($validatedData['email'])->send(new \App\Mail\CustomMail($subject, $message));

            Log::info('Mail sent successfully');

            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);
        }
    }

    /**
     * Summary of validemail ajax  驗證email 是否註冊過
     * @param \Illuminate\Http\Request $request
     * @return mixed|\Illuminate\Http\JsonResponse
     */
    public function validemail(Request $request)
    {
        // 構建郵件內容

        // 驗證輸入的數據
        $validatedData = $request->validate([
            'email' => 'required|email',
        ]);

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

        if ($user) {
            // 查找是否已有驗證記錄
            $vaild = EmailVerifications::where('email', $validatedData['email'])->first();

            return response()->json([
                'status' => 'error',
                'msg' => 'email 以使用 ,是否逕行合併,如果是 請先驗證email',
            ]);
        } else {
            return response()->json([
                'status' => 'success',

            ]);
        }

    }
    /**
     * Summary of checkEmail email 寄送  token 點擊後 驗證
     * @param \Illuminate\Http\Request $request
     * @return mixed|\Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     */
    public function checkEmail(Request $request)
    {
        Log::info('Email verification request received:', $request->all());

        // 獲取當前登入的會員（若存在）
        $auth = Auth::guard('member')->user();

        // 驗證請求中是否包含 token
        $validatedData = $request->validate([
            'token' => 'required|string',
        ]);

        // 查詢對應的驗證記錄
        $check = EmailVerifications::where('token', $validatedData['token'])->first();

        if (!$check) {
            Log::warning('Invalid token provided for email verification:', ['token' => $validatedData['token']]);
            return response()->json(['status' => 'error', 'msg' => '無效的驗證連結或連結已過期'], 400);
        }

        Log::info(message: 'Email verification record found:', context: $check->toArray());

        // 查詢對應的會員
        $member = Member::where('email', $check->email)->orderBy('created_at', 'asc')->first();




        // 若當前登入用戶存在 line_id，則使用當前用戶更新
        if ($auth && isset($auth->line_id)) {
            $line_id = $auth->line_id;
        } else {
            $line_id = $member->line_id;
        }

        // 更新會員的 Email 與驗證時間

        Log::info('Member email verification updated successfully:', $member->toArray());

        // 如果當前登入用戶與驗證的會員不同，登出當前用戶並重新登入
        if ($auth && $auth->id != $member->id) {
            // 在登出之前執行需要刪除或處理的操作
            $needdeletaccount = Auth::guard('member')->user();

            // 確保在登出前刪除帳號資料或執行其他操作
            if ($needdeletaccount) {
                $needdeletaccount->delete(); // 這會刪除登入用戶的資料
                $member->email_verified_at = now();
                $member->line_id = $line_id;
                Log::info('Deleted account after logout:', ['user_id' => $needdeletaccount->id]);
            }

            $member->save();

            // 登出並重新登入
            Auth::logout();
            Auth::guard('member')->loginUsingId($member->id);
            Log::info('Logged out previous user and logged in verified user:', ['user_id' => $member->id]);
        }


        // 刪除驗證記錄以防重複使用
        $check->delete();
        Log::info('Verification token record deleted successfully:', ['token' => $validatedData['token']]);

        // return response()->json(['status' => 'success', 'msg' => '電子郵件驗證成功']);

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

    }
}
