<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Member;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;
use Log;
use session;

class LoginController extends Controller
{
    public $redirectTo = '';
    //
    public function index(Request $request)
    {
        return view('front.login');
    }

    public function adminIndex(Request $request)
    {
        return view('admin.login');
    }

    /** line 跳轉 由line登入
     * @return [type]
     */
    public function redirectToProvider(Request $request)
    {
        $redirectTo = $request->is('admin/*') ? 'admin' : 'member';
        session(['redirect_to' => $redirectTo]); // 将值存入 Session
        return Socialite::driver('line')->redirect();
    }

    /**
     * Summary of handleProviderCallback
     * line 登入後查詢
     * @return void
     */
    public function handleProviderCallback(Request $request)
    {
        // 如果用户取消了授权
        if ($request->has('error') && $request->get('error') === 'access_denied') {
            $redirectTo = session('redirect_to', 'member');

            if ($redirectTo === 'admin') {
                return redirect()->route('admin.login')->with('error', '您已取消 LINE 授权');
            } else {
                return redirect()->route('login')->with('error', '您已取消 LINE 授权');
            }
        }

        try {
            // 获取 LINE 用户信息
            $user = Socialite::driver('line')->user();
            Log::info('line', ['user' => $user]);

            $lineId = $user->getId();
            $name = $user->getName();
            $avatar = $user->getAvatar() ?? '';
            $email = $user->getEmail() ?? '';

            Log::info('email', [$email]);

            // 从 Session 获取跳转路径
            $redirectTo = session('redirect_to', 'member');

            if ($redirectTo === 'admin') {
                // Admin 登录逻辑
                $existingUser = User::where('line_id', $lineId)
                    ->orWhere('email', $email)
                    ->first();

                if ($existingUser) {
                    Auth::guard('web')->login($existingUser);
                } else {
                    $newUser = User::create([
                        'name' => $name,
                        'line_id' => $lineId,
                        'password' => bcrypt(env('DEFAULT_PASSWORD')),
                        'avatar' => $avatar,
                        'source' => 'cafeg',
                        'email' => $email,
                        'can_login' => 0,
                    ]);
                    Auth::guard('web')->login($newUser);
                }

                $user = Auth::guard('web')->user();
                return $user->email
                    ? redirect()->route('admin.index')
                    : redirect()->route('admin.profile');
            } else {
                // Member 登录逻辑
                $existingUser = Member::where('line_id', $lineId)
                    ->orWhere('email', $email)
                    ->first();
                if ($existingUser) {
                    Auth::guard('member')->login($existingUser);
                } else {
                    $newUser = Member::create([
                        'name' => $name,
                        'line_id' => $lineId,
                        'password' => bcrypt(env('DEFAULT_PASSWORD')),
                        'source' => 'cafeg',
                        'avatar' => $avatar,
                        'email' => $email,
                    ]);
                    Auth::guard('member')->login($newUser);
                }

                $user = Auth::guard('member')->user();
                return $user->email
                    ? redirect()->route('member.index')
                    : redirect()->route('member.profile');
            }
        } catch (\Exception $e) {
            Log::error('LINE 登录失败: ' . $e->getMessage());

            // 发生异常时，返回登录页面并提示错误
            return redirect()->route('login')->with('error', 'LINE 登录失败，请稍后再试');
        }
    }


    public function adminLogout()
    {
        Auth::guard('web')->logout();
        return redirect()->route('admin.login');
    }

    public function memberLogout()
    {
        Auth::guard('member')->logout();
        return redirect()->route('login');
    }

    public function adminNormalLogin(Request $request)
    {

        $credentials = $request->only('email', 'password');

        if (Auth::guard('web')->attempt($credentials)) {
            return redirect()->route('admin.index');
        }
        return redirect()->route('admin.login');
    }

    public function memberNormalLogin(Request $request)
    {
        $credentials = $request->only('email', 'password');

        if (Auth::guard('member')->attempt($credentials)) {
            return redirect()->route('member.index');
        } else {

            return redirect()->route('login')->with('error', '帳號密碼錯誤');
        }
    }

    // 重定向到 Google
    public function redirectToGoogle()
    {
        return Socialite::driver('google')->redirect();
    }

    // 處理 Google 回調
    public function handleGoogleCallback()
    {
        try {
            $googleUser = Socialite::driver('google')->stateless()->user();

            // 查找或創建用戶
            $user = Member::firstOrCreate(
                ['email' => $googleUser->getEmail()],
                [
                    'name' => $googleUser->getName(),
                    'google_id' => $googleUser->getId(),
                    'avatar' => $googleUser->getAvatar(),
                    'password' => bcrypt(env('DEFAULT_PASSWORD')),
                    'source' => 'cafeg',
                ]
            );
            Log::info('google Oauth :', [$user]);


            // 登入用戶
            Auth::guard('member')->login($user, true);

            return redirect()->route('member.index'); // 登入後跳轉的路徑
        } catch (\Exception $e) {
            return redirect('/')->with('error', '無法進行 Google 登入');
        }
    }
}
