<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\Branch;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Database\Eloquent\ModelNotFoundException;

class BranchController extends Controller
{
    /**
     * Display a listing of all branches
     */
    public function index(Request $request)
    {
        if ($request->has('shareholder_id')) {
            $shareholderId = $request->shareholder_id;
            $branches = Branch::whereHas('users', function ($query) use ($shareholderId) {
                $query->where('users.id', $shareholderId);
            })->with(['credits'])->get();
        } else {
            $branches = Branch::with(['credits'])->get();
        }

        return response()->json([
            'status' => true,
            'data' => $branches
        ]);
    }

    /**
     * Store a newly created branch
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'address' => 'nullable|string|max:255',
            'contact_number' => 'nullable|string|max:20',
            'active' => 'nullable|boolean',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status' => false,
                'message' => 'Validation failed',
                'errors' => $validator->errors()
            ], 422);
        }

        $branch = Branch::create([
            'name' => $request->name,
            'description' => $request->description,
            'address' => $request->address,
            'contact_number' => $request->contact_number,
            'active' => $request->active ?? true,
            'created_by' => Auth::id(),
            'updated_by' => Auth::id(),
        ]);

        // // 获取当前用户
        // $currentUser = Auth::user();

        // // 获取当前用户角色
        // $userRole = $currentUser->role_name;

        // // 如果用户没有角色，设置默认值为'admin'（因为是创建者）
        // if (empty($userRole)) {
        //     $userRole = 'admin';
        // }

        // // 将当前用户添加到分支中
        // $branch->users()->attach($currentUser->id, [
        //     'role' => $userRole
        // ]);

        return response()->json([
            'status' => true,
            'message' => 'Branch created successfully',
            'data' => Branch::with(['users', 'credits'])->find($branch->id)
        ], 201);
    }

    /**
     * Display the specified branch
     */
    public function show(string $id)
    {
        try {
            $branch = Branch::with(['users', 'credits'])->findOrFail($id);

            return response()->json([
                'status' => true,
                'data' => $branch
            ]);
        } catch (ModelNotFoundException $e) {
            return response()->json([
                'status' => false,
                'message' => 'Branch not found'
            ], 404);
        }
    }

    /**
     * Update the specified branch
     */
    public function update(Request $request, string $id)
    {
        try {
            $branch = Branch::findOrFail($id);

            $validator = Validator::make($request->all(), [
                'name' => 'sometimes|required|string|max:255',
                'description' => 'nullable|string',
                'address' => 'nullable|string|max:255',
                'contact_number' => 'nullable|string|max:20',
                'active' => 'nullable|boolean',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'status' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 422);
            }

            $branch->update([
                'name' => $request->name ?? $branch->name,
                'description' => $request->description ?? $branch->description,
                'address' => $request->address ?? $branch->address,
                'contact_number' => $request->contact_number ?? $branch->contact_number,
                'active' => $request->has('active') ? $request->active : $branch->active,
                'updated_by' => Auth::id(),
            ]);

            return response()->json([
                'status' => true,
                'message' => 'Branch updated successfully',
                'data' => $branch
            ]);
        } catch (ModelNotFoundException $e) {
            return response()->json([
                'status' => false,
                'message' => 'Branch not found'
            ], 404);
        }
    }

    /**
     * Remove the specified branch
     */
    public function destroy(string $id)
    {
        try {
            $branch = Branch::findOrFail($id);
            $branch->delete();

            return response()->json([
                'status' => true,
                'message' => 'Branch deleted successfully'
            ]);
        } catch (ModelNotFoundException $e) {
            return response()->json([
                'status' => false,
                'message' => 'Branch not found'
            ], 404);
        }
    }

    /**
     * Add one or multiple users to the branch
     */
    public function addUser(Request $request, string $id)
    {
        try {
            $branch = Branch::with('users')->findOrFail($id);
            $userIds = [];
            // 检查是否有user_ids数组
            if (is_array($request->user_ids)) {
                $userIds = $request->user_ids;
            } elseif (is_string($request->user_ids)) {
                // 如果是逗号分隔的字符串，分割并转换为数组
                $idsFromString = array_map('trim', explode(',', $request->user_ids));
                $userIds = array_merge($userIds, $idsFromString);
            }

            // 验证所有用户ID
            if (empty($userIds)) {
                return response()->json([
                    'status' => false,
                    'message' => 'No user IDs provided',
                ], 422);
            }

            $addedUsers = 0;
            $alreadyInBranch = 0;

            foreach ($userIds as $userId) {
                $userId = (int) $userId;

                try {
                    // 获取用户及其角色信息
                    $user = User::findOrFail($userId);

                    // Check if user is already in the branch
                    if ($branch->users->contains($userId)) {
                        $alreadyInBranch++;
                        continue;
                    }

                    // 使用用户数据库中的role_name
                    $userRole = $user->role_name;

                    // 如果用户没有角色，设置默认值为'member'
                    if (empty($userRole)) {
                        $userRole = 'member';
                    }

                    $branch->users()->attach($userId, [
                        'role' => $userRole
                    ]);

                    $addedUsers++;
                } catch (ModelNotFoundException $e) {
                    // 忽略不存在的用户
                    continue;
                }
            }

            $message = $addedUsers . ' user(s) added to branch successfully';
            if ($alreadyInBranch > 0) {
                $message .= ', ' . $alreadyInBranch . ' user(s) already in branch';
            }

            return response()->json([
                'status' => true,
                'message' => $message,
                'data' => Branch::with(['users', 'credits'])->find($id)
            ]);
        } catch (ModelNotFoundException $e) {
            return response()->json([
                'status' => false,
                'message' => 'Branch not found'
            ], 404);
        }
    }

    /**
     * Remove a user from the branch
     */
    public function removeUser(Request $request, string $id, string $userId)
    {
        try {
            $branch = Branch::findOrFail($id);
            $user = User::findOrFail($userId);

            // Check if user is in the branch
            if (!$branch->users->contains($userId)) {
                return response()->json([
                    'status' => false,
                    'message' => 'User is not in the branch'
                ], 400);
            }

            $branch->users()->detach($userId);

            return response()->json([
                'status' => true,
                'message' => 'User removed from branch successfully',
                'data' => Branch::with(['users', 'credits'])->find($id)
            ]);
        } catch (ModelNotFoundException $e) {
            return response()->json([
                'status' => false,
                'message' => 'Branch or user not found'
            ], 404);
        }
    }

    /**
     * Get all users in the branch
     */
    public function users(string $id)
    {
        try {
            $branch = Branch::findOrFail($id);
            $users = $branch->users;

            return response()->json([
                'status' => true,
                'data' => $users
            ]);
        } catch (ModelNotFoundException $e) {
            return response()->json([
                'status' => false,
                'message' => 'Branch not found'
            ], 404);
        }
    }

    /**
     * Update user role in the branch
     */
    public function updateUserRole(Request $request, string $id, string $userId)
    {
        try {
            $branch = Branch::findOrFail($id);
            $user = User::findOrFail($userId);

            $validator = Validator::make($request->all(), [
                'role' => 'required|string|in:admin,member',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'status' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 422);
            }

            // Check if user is in the branch
            if (!$branch->users->contains($userId)) {
                return response()->json([
                    'status' => false,
                    'message' => 'User is not in the branch'
                ], 400);
            }

            $branch->users()->updateExistingPivot($userId, [
                'role' => $request->role
            ]);

            return response()->json([
                'status' => true,
                'message' => 'User role updated successfully',
                'data' => Branch::with(['users', 'credits'])->find($id)
            ]);
        } catch (ModelNotFoundException $e) {
            return response()->json([
                'status' => false,
                'message' => 'Branch or user not found'
            ], 404);
        }
    }
}
