<?php

namespace App\Http\Controllers\SiteAdmin;

use App\Http\Controllers\Controller;
use App\Models\Admin;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\View\View;

class AuthController extends Controller
{
    public function showLogin(): View
    {
        return view('site_admin.auth.login');
    }

    public function login(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required', 'string'],
        ]);

        $admin = Admin::query()->with('merchant')->where('email', $data['email'])->first();
        if (! $admin || ! Hash::check($data['password'], $admin->password)) {
            return back()->withErrors(['email' => '账号或密码错误'])->withInput();
        }

        if (! $admin->isMerchantAdmin()) {
            return back()->withErrors(['email' => '当前账号不是站点管理员，不能登录站点后台'])->withInput();
        }

        $siteId = $admin->merchantId();

        $request->session()->put('admin_id', $admin->id);
        $request->session()->put('admin_name', $admin->name);
        $request->session()->put('admin_email', $admin->email);
        $request->session()->put('admin_role', $admin->role);
        $request->session()->put('admin_merchant_id', $siteId);
        $request->session()->put('admin_site_id', $siteId);
        $request->session()->put('admin_scope', 'site');
        $request->session()->put('site_name', $admin->merchant?->name);

        $admin->forceFill(['last_login_at' => now()])->save();

        return redirect('/site-admin');
    }

    public function logout(Request $request): RedirectResponse
    {
        $request->session()->forget(['admin_id', 'admin_name', 'admin_email', 'admin_role', 'admin_merchant_id', 'admin_site_id', 'admin_scope', 'site_name']);

        return redirect('/site-admin/login');
    }
}
