<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    /**
     * 登录
     */
    public function login(Request $request): JsonResponse
    {
        $request->validate([
            'username' => 'required|string',
            'password' => 'required|string',
        ]);

        $user = User::withoutGlobalScope('store')
            ->where('username', $request->username)
            ->first();

        if (!$user || !Hash::check($request->password, $user->password)) {
            return $this->error('用户名或密码错误', 40100, 401);
        }

        if ($user->status->value !== 1) {
            return $this->error('账号已被禁用或待审核', 40101, 403);
        }

        // 清除旧 token
        $user->tokens()->delete();

        $token = $user->createToken('admin')->plainTextToken;

        $user->update(['last_login_at' => now()]);

        return $this->success([
            'token' => $token,
            'user' => [
                'id' => $user->id,
                'username' => $user->username,
                'name' => $user->name,
                'avatar' => $user->avatar,
                'store_id' => $user->store_id,
                'is_super' => $user->is_super,
            ],
        ]);
    }

    /**
     * 退出登录
     */
    public function logout(Request $request): JsonResponse
    {
        $request->user()->currentAccessToken()->delete();
        return $this->success(null, '退出成功');
    }

    /**
     * 获取当前用户信息
     */
    public function me(Request $request): JsonResponse
    {
        $user = $request->user();
        $user->load(['department', 'position', 'roles']);

        return $this->success([
            'id' => $user->id,
            'username' => $user->username,
            'name' => $user->name,
            'phone' => $user->phone,
            'email' => $user->email,
            'avatar' => $user->avatar,
            'store_id' => $user->store_id,
            'is_super' => $user->is_super,
            'department' => $user->department?->name,
            'position' => $user->position?->name,
            'roles' => $user->roles->pluck('name'),
            'permissions' => $user->getAllPermissionCodes(),
            'menus' => $user->getMenuTree(),
        ]);
    }

    /**
     * 获取门店部门列表（公开接口，注册时使用）
     */
    public function departments(Request $request): JsonResponse
    {
        $storeId = $request->input('store_id');
        if (!$storeId) {
            return $this->error('请选择门店', 42200);
        }

        $departments = \App\Models\Department::withoutGlobalScope('store')
            ->where('store_id', $storeId)
            ->where('status', 1)
            ->orderBy('sort')
            ->get(['id', 'name', 'parent_id']);

        return $this->success($departments);
    }

    /**
     * 获取可用注册套餐列表（公开接口）
     */
    public function registrationPackages(Request $request): JsonResponse
    {
        $storeId = $request->input('store_id');
        if (!$storeId) {
            return $this->error('请选择门店', 42200);
        }

        $packages = \App\Models\System\RegistrationPackage::withoutGlobalScope('store')
            ->where('store_id', $storeId)
            ->where('status', 1)
            ->orderBy('sort')
            ->get(['id', 'name', 'description']);

        return $this->success($packages);
    }

    /**
     * 自助注册（公开接口）
     * 注册后 status=2(待审核)，需管理员审批后才能登录
     */
    public function register(Request $request): JsonResponse
    {
        $data = $request->validate([
            'store_id'                => 'required|exists:stores,id',
            'registration_package_id' => 'required|exists:registration_packages,id',
            'username'                => 'required|string|max:50|unique:users,username',
            'password'                => 'required|string|min:6',
            'name'                    => 'required|string|max:50',
            'phone'                   => 'required|string|max:20',
            'department_id'           => 'nullable|exists:departments,id',
        ]);

        // 验证套餐属于该门店
        $package = \App\Models\System\RegistrationPackage::withoutGlobalScope('store')
            ->where('id', $data['registration_package_id'])
            ->where('store_id', $data['store_id'])
            ->where('status', 1)
            ->firstOrFail();

        $user = \App\Models\User::create([
            'store_id'      => $data['store_id'],
            'username'      => $data['username'],
            'password'      => $data['password'],
            'name'          => $data['name'],
            'phone'         => $data['phone'],
            'department_id' => $data['department_id'] ?? null,
            'status'        => 2, // Pending
        ]);

        // 绑定套餐角色
        if (!empty($package->role_ids)) {
            $user->roles()->sync($package->role_ids);
        }

        return $this->success(null, '注册成功，请等待管理员审核后登录');
    }
}
