<?php

namespace App\Http\Controllers\Admin\System;

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

class UserController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = User::with(['department', 'position', 'roles']);

        if ($request->keyword) {
            $query->where(function ($q) use ($request) {
                $q->where('name', 'like', "%{$request->keyword}%")
                  ->orWhere('phone', 'like', "%{$request->keyword}%")
                  ->orWhere('username', 'like', "%{$request->keyword}%");
            });
        }
        if ($request->department_id) {
            $query->where('department_id', $request->department_id);
        }
        if ($request->has('status')) {
            $query->where('status', $request->status);
        }

        $users = $query->orderByDesc('id')
            ->paginate($request->input('page_size', 20));

        return $this->paginate($users);
    }

    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'username' => 'required|string|max:50|unique:users,username',
            'password' => 'required|string|min:6',
            'name' => 'required|string|max:50',
            'phone' => 'nullable|string|max:20',
            'email' => 'nullable|email|max:100',
            'department_id' => 'nullable|exists:departments,id',
            'position_id' => 'nullable|exists:positions,id',
            'status' => 'in:0,1,2',
            'role_ids' => 'array',
            'role_ids.*' => 'exists:roles,id',
            'store_id' => 'nullable|exists:stores,id',
        ]);

        $roleIds = $data['role_ids'] ?? [];
        unset($data['role_ids']);

        $authUser = auth()->user();
        // 超级管理员可指定 store_id，普通管理员只能在自己门店下创建
        if ($authUser->is_super && !empty($data['store_id'])) {
            // use provided store_id
        } else {
            $data['store_id'] = $authUser->store_id;
        }

        $user = User::create($data);

        if ($roleIds) {
            $user->roles()->sync($roleIds);
        }

        return $this->success($user->load('roles'), '创建成功');
    }

    public function show(User $user): JsonResponse
    {
        $user->load(['department', 'position', 'roles']);
        return $this->success($user);
    }

    public function update(Request $request, User $user): JsonResponse
    {
        $data = $request->validate([
            'name' => 'string|max:50',
            'phone' => 'nullable|string|max:20',
            'email' => 'nullable|email|max:100',
            'department_id' => 'nullable|exists:departments,id',
            'position_id' => 'nullable|exists:positions,id',
            'role_ids' => 'array',
            'role_ids.*' => 'exists:roles,id',
        ]);

        $roleIds = $data['role_ids'] ?? null;
        unset($data['role_ids']);

        $user->update($data);

        if ($roleIds !== null) {
            $user->roles()->sync($roleIds);
        }

        return $this->success($user->load('roles'), '更新成功');
    }

    /**
     * 更新状态
     */
    public function updateStatus(Request $request, User $user): JsonResponse
    {
        $request->validate(['status' => 'required|in:0,1,2']);
        $user->update(['status' => $request->status]);
        return $this->success(null, '状态更新成功');
    }

    /**
     * 重置密码
     */
    public function resetPassword(Request $request, User $user): JsonResponse
    {
        $request->validate(['password' => 'required|string|min:6']);
        $user->update(['password' => $request->password]);
        return $this->success(null, '密码重置成功');
    }

    /**
     * 审核通过 — 激活待审核用户
     */
    public function approve(User $user): JsonResponse
    {
        if ($user->status->value !== 2) {
            return $this->error('该用户不在待审核状态');
        }
        $user->update(['status' => 1]);
        return $this->success(null, '已审核通过');
    }

    /**
     * 审核拒绝 — 禁用该用户
     */
    public function reject(User $user): JsonResponse
    {
        if ($user->status->value !== 2) {
            return $this->error('该用户不在待审核状态');
        }
        $user->update(['status' => 0]);
        return $this->success(null, '已拒绝注册');
    }

    public function destroy(User $user): JsonResponse
    {
        if ($user->is_super) {
            return $this->error('超级管理员不可删除');
        }
        $user->delete();
        return $this->success(null, '删除成功');
    }
}
