<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Credit;
use App\Models\Branch;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use App\Models\CreditBalance;
use Illuminate\Support\Facades\DB;
use Intervention\Image\Facades\Image;
use Imagick;

class CreditController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        // Support filtering by branch and type
        $query = Credit::query();

        // Get current authenticated user
        $user = Auth::user();


        // If user is a shareholder, only show credits from branches they belong to
        // if ($user->hasRole('shareholder') && !$user->hasRole('admin')) {
        //     // Get the branches that the shareholder belongs to

        //     if (!empty($branchIds)) {
        //         $query->whereIn('branch_id', $branchIds);
        //     } else {
        //         // If shareholder has no branches, return empty result
        //         return response()->json([
        //             'status' => true,
        //             'message' => 'No branches assigned to this shareholder',
        //             'data' => []
        //         ]);
        //     }
        // }

        // Filter by branch
        if ($request->has('branch_id')) {
            $query->where('branch_id', $request->branch_id);
        }

        // Filter by single type
        if ($request->has('type')) {
            $query->where('type', $request->type);
        }

        // Filter by single user
        if ($request->has('shareholder_id')) {
            $query->where(function ($q) use ($request) {
                $q->where('shareholder_id', $request->shareholder_id)
                    ->orWhereNull('shareholder_id');
            });
        }

        // Filter by multiple types
        if ($request->has('types') && is_array($request->types)) {
            $query->whereIn('type', $request->types);
        }

        // Filter by status
        if ($request->has('status')) {
            $query->where('status', $request->status);
        }

        // Filter by active status
        if ($request->has('active')) {
            $query->where('active', $request->active);
        }

        // Filter by date range
        if ($request->has('start_date')) {
            $query->whereDate('created_at', '>=', $request->start_date);
        }

        if ($request->has('end_date')) {
            $query->whereDate('created_at', '<=', $request->end_date);
        }

        // Filter by user name (searches in users table)
        if ($request->has('user_name')) {
            $query->whereHas('user', function ($q) use ($request) {
                $q->where('name', 'like', '%' . $request->user_name . '%');
            });
        }

        // Determine page size
        $perPage = 20; // Default page size
        if ($request->has('per_page') && is_numeric($request->per_page) && $request->per_page > 0) {
            $perPage = $request->per_page;
        }

        $credits = $query->with(['branch', 'user', 'shareholder'])->orderBy('created_at', 'desc')->paginate($perPage);

        return response()->json([
            'status' => true,
            'message' => 'Credits retrieved successfully',
            'data' => $credits,
        ]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'amount' => 'required|numeric|min:0',
            'type' => 'required|in:deposit,withdrawal',
            'deposit_type' => 'required_if:type,deposit|in:branch,shareholder',
            'branch_id' => 'required|exists:branches,id',
            'shareholder_id' => 'required_if:deposit_type,shareholder|exists:users,id',
            'attachment' => 'nullable|file|mimetypes:image/*,application/pdf|max:10240',
            'notes' => 'nullable|string|max:500',
        ]);

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

        // Get current authenticated user
        $user = Auth::user();

        // If user is a shareholder (but not admin), verify they can access the branch
        if ($user->hasRole('shareholder') && !$user->hasRole('admin')) {
            $branchIds = $user->branches()->pluck('branches.id')->toArray();
            if (!in_array($request->branch_id, $branchIds)) {
                return response()->json([
                    'status' => false,
                    'message' => 'You do not have permission to create credit for this branch'
                ], 403);
            }
        }

        // Handle attachment upload
        $attachmentPath = null;
        if ($request->hasFile('attachment')) {
            $attachmentPath = $request->file('attachment')->store('attachments', 'public');
        }

        $status = $request->type === 'deposit' ? 'approved' : 'pending';

        // Determine shareholder_id based on type and deposit_type
        $shareholderId = null;
        if ($request->type === 'withdrawal') {
            $shareholderId = Auth::id();
        } else if ($request->deposit_type === 'shareholder' && $request->has('shareholder_id')) {
            $shareholderId = $request->shareholder_id;
        }

        try {
            DB::beginTransaction();

            $credit = Credit::create([
                'amount' => $request->amount,
                'type' => $request->type,
                'deposit_type' => $request->deposit_type,
                'status' => $status,
                'active' => true,
                'branch_id' => $request->branch_id,
                'shareholder_id' => $shareholderId,
                'user_id' => Auth::id(),
                'attachment' => $attachmentPath,
                'notes' => $request->notes,
            ]);

            // 如果是存款且状态为approved
            if ($request->type === 'deposit' && $status === 'approved') {
                if ($request->deposit_type === 'shareholder' && $shareholderId) {
                    // 更新shareholder的balance
                    $this->updateCreditBalance($shareholderId, $request->branch_id, $request->amount, 'add');
                    $branch = Branch::find($request->branch_id);
                    $branch->wallet += round($request->amount * 0.9, 2);
                    $branch->total_deposit +=  round($request->amount * 0.9, 2);
                    $branch->save();
                } else if ($request->deposit_type === 'branch') {
                    // 更新branch的wallet和total_deposit
                    $branch = Branch::find($request->branch_id);
                    $branch->wallet += $request->amount;
                    $branch->total_deposit += $request->amount;
                    $branch->save();
                }
            }

            DB::commit();

            return response()->json([
                'status' => true,
                'message' => 'Credit created successfully',
                'data' => $credit->load(['branch', 'user', 'shareholder'])
            ], 201);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'status' => false,
                'message' => 'Error creating credit: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        $credit = Credit::with(['branch', 'user', 'shareholder'])->find($id);

        if (!$credit) {
            return response()->json([
                'status' => false,
                'message' => 'Credit not found'
            ], 404);
        }

        // Get current authenticated user
        $user = Auth::user();

        // If user is a shareholder (but not admin), verify they can access this credit
        if ($user->hasRole('shareholder') && !$user->hasRole('admin')) {
            // Get the branches that the shareholder belongs to
            $branchIds = $user->branches()->pluck('branches.id')->toArray();

            // Check if the credit's branch is in the user's branches
            if (!in_array($credit->branch_id, $branchIds)) {
                return response()->json([
                    'status' => false,
                    'message' => 'You do not have permission to view this credit'
                ], 403);
            }
        }

        return response()->json([
            'status' => true,
            'message' => 'Credit retrieved successfully',
            'data' => $credit
        ]);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        $credit = Credit::find($id);

        if (!$credit) {
            return response()->json([
                'status' => false,
                'message' => 'Credit not found'
            ], 404);
        }

        // Get current authenticated user
        $user = Auth::user();

        // If user is a shareholder (but not admin), verify they can access this credit
        if ($user->hasRole('shareholder') && !$user->hasRole('admin')) {
            // Get the branches that the shareholder belongs to
            $branchIds = $user->branches()->pluck('branches.id')->toArray();

            // Check if the credit's branch is in the user's branches
            if (!in_array($credit->branch_id, $branchIds)) {
                return response()->json([
                    'status' => false,
                    'message' => 'You do not have permission to update this credit'
                ], 403);
            }
        }

        $validator = Validator::make($request->all(), [
            'amount' => 'sometimes|required|numeric|min:0',
            'type' => 'sometimes|required|in:deposit,withdrawal',
            'status' => 'sometimes|required|in:pending,approved,rejected',
            'active' => 'sometimes|required|boolean',
            'branch_id' => 'sometimes|required|exists:branches,id',
            'attachment' => 'nullable|file|mimetypes:image/*,application/pdf|max:10240',
            'notes' => 'nullable|string|max:500',
        ]);

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

        // If user is a shareholder and trying to change branch_id, verify new branch is accessible
        if ($user->hasRole('shareholder') && !$user->hasRole('admin') && $request->has('branch_id')) {
            $branchIds = $user->branches()->pluck('branches.id')->toArray();
            if (!in_array($request->branch_id, $branchIds)) {
                return response()->json([
                    'status' => false,
                    'message' => 'You do not have permission to assign credit to this branch'
                ], 403);
            }
        }

        // Handle attachment upload
        if ($request->hasFile('attachment')) {
            // Delete previous attachment
            if ($credit->attachment) {
                Storage::disk('public')->delete($credit->attachment);
            }

            $attachmentPath = $request->file('attachment')->store('attachments', 'public');
            $credit->attachment = $attachmentPath;
        }

        // Update fields
        if ($request->has('amount')) $credit->amount = $request->amount;
        if ($request->has('type')) $credit->type = $request->type;
        if ($request->has('status')) $credit->status = $request->status;
        if ($request->has('active')) $credit->active = $request->active;
        if ($request->has('branch_id')) $credit->branch_id = $request->branch_id;
        if ($request->has('notes')) $credit->notes = $request->notes;

        $credit->save();

        return response()->json([
            'status' => true,
            'message' => 'Credit updated successfully',
            'data' => $credit->load(['branch', 'user', 'shareholder'])
        ]);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        $credit = Credit::find($id);

        if (!$credit) {
            return response()->json([
                'status' => false,
                'message' => 'Credit not found'
            ], 404);
        }

        // Get current authenticated user
        $user = Auth::user();

        // If user is a shareholder (but not admin), verify they can access this credit
        if ($user->hasRole('shareholder') && !$user->hasRole('admin')) {
            // Get the branches that the shareholder belongs to
            $branchIds = $user->branches()->pluck('branches.id')->toArray();

            // Check if the credit's branch is in the user's branches
            if (!in_array($credit->branch_id, $branchIds)) {
                return response()->json([
                    'status' => false,
                    'message' => 'You do not have permission to delete this credit'
                ], 403);
            }
        }

        // Delete attachment
        if ($credit->attachment) {
            Storage::disk('public')->delete($credit->attachment);
        }

        $credit->delete();

        return response()->json([
            'status' => true,
            'message' => 'Credit deleted successfully'
        ]);
    }

    /**
     * Update credit status
     */
    public function updateStatus(Request $request, string $id)
    {
        $credit = Credit::find($id);

        if (!$credit) {
            return response()->json([
                'status' => false,
                'message' => 'Credit not found'
            ], 404);
        }

        // Get current authenticated user
        $user = Auth::user();

        // If user is a shareholder (but not admin), verify they can access this credit
        if ($user->hasRole('shareholder') && !$user->hasRole('admin')) {
            $branchIds = $user->branches()->pluck('branches.id')->toArray();
            if (!in_array($credit->branch_id, $branchIds)) {
                return response()->json([
                    'status' => false,
                    'message' => 'You do not have permission to update status for this credit'
                ], 403);
            }
        }

        $validator = Validator::make($request->all(), [
            'status' => 'required|in:pending,approved,rejected',
        ]);

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

        // Check if request status is "approved"
        if ($request->status === 'approved') {
            if (!($user->hasRole('admin') || $user->hasRole('shareholder'))) {
                return response()->json([
                    'status' => false,
                    'message' => 'Unauthorized. Only admin and shareholder can approve credit requests.',
                ], 403);
            }

            if (!$user->hasPermissionTo('approve_credits')) {
                return response()->json([
                    'status' => false,
                    'message' => 'You do not have permission to approve credit requests.',
                ], 403);
            }

            $credit->shareholder_id = $user->id;
        }

        try {
            DB::beginTransaction();

            $oldStatus = $credit->status;
            $credit->status = $request->status;
            $credit->save();

            // 如果状态从pending变为approved
            if ($oldStatus === 'pending' && $request->status === 'approved') {
                if ($credit->type === 'deposit') {
                    if ($credit->deposit_type === 'shareholder' && $credit->shareholder_id) {
                        // 更新shareholder的balance
                        $this->updateCreditBalance($credit->shareholder_id, $credit->branch_id, $credit->amount, 'add');
                    } else if ($credit->deposit_type === 'branch') {
                        // 更新branch的wallet和total_deposit
                        $branch = Branch::find($credit->branch_id);
                        $branch->wallet += $credit->amount;
                        $branch->total_deposit += $credit->amount;
                        $branch->save();
                    }
                } else if ($credit->type === 'withdrawal' && $credit->shareholder_id) {
                    // 更新shareholder的balance
                    $this->updateCreditBalance($credit->shareholder_id, $credit->branch_id, $credit->amount, 'subtract');
                }
            }
            // 如果状态从approved变为rejected
            else if ($oldStatus === 'approved' && $request->status === 'rejected') {
                if ($credit->type === 'deposit') {
                    if ($credit->deposit_type === 'shareholder' && $credit->shareholder_id) {
                        // 回滚shareholder的balance
                        $this->updateCreditBalance($credit->shareholder_id, $credit->branch_id, $credit->amount, 'subtract');
                    } else if ($credit->deposit_type === 'branch') {
                        // 回滚branch的wallet和total_deposit
                        $branch = Branch::find($credit->branch_id);
                        $branch->wallet -= $credit->amount;
                        $branch->total_deposit -= $credit->amount;
                        $branch->save();
                    }
                } else if ($credit->type === 'withdrawal' && $credit->shareholder_id) {
                    // 回滚shareholder的balance
                    $this->updateCreditBalance($credit->shareholder_id, $credit->branch_id, $credit->amount, 'add');
                }
            }

            DB::commit();

            return response()->json([
                'status' => true,
                'message' => 'Credit status updated successfully',
                'data' => $credit->load(['branch', 'user', 'shareholder'])
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'status' => false,
                'message' => 'Error updating credit status: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Toggle credit active status
     */
    public function toggleActive(string $id)
    {
        $credit = Credit::find($id);

        if (!$credit) {
            return response()->json([
                'status' => false,
                'message' => 'Credit not found'
            ], 404);
        }

        // Get current authenticated user
        $user = Auth::user();

        // If user is a shareholder (but not admin), verify they can access this credit
        if ($user->hasRole('shareholder') && !$user->hasRole('admin')) {
            // Get the branches that the shareholder belongs to
            $branchIds = $user->branches()->pluck('branches.id')->toArray();

            // Check if the credit's branch is in the user's branches
            if (!in_array($credit->branch_id, $branchIds)) {
                return response()->json([
                    'status' => false,
                    'message' => 'You do not have permission to toggle active status for this credit'
                ], 403);
            }
        }

        $credit->active = !$credit->active;
        $credit->save();

        return response()->json([
            'status' => true,
            'message' => 'Credit active status toggled successfully',
            'data' => $credit->load(['branch', 'user', 'shareholder'])
        ]);
    }

    /**
     * Approve a credit deposit or withdrawal request
     * 
     * @param string $id Credit ID
     * @return \Illuminate\Http\JsonResponse
     */
    public function approveRequest(string $id)
    {
        $credit = Credit::with(['branch', 'user'])->find($id);

        if (!$credit) {
            return response()->json([
                'status' => false,
                'message' => 'Credit request not found'
            ], 404);
        }

        // Get current authenticated user
        $user = Auth::user();

        // If user is a shareholder (but not admin), verify they can access this credit
        if ($user->hasRole('shareholder') && !$user->hasRole('admin')) {
            // Get the branches that the shareholder belongs to
            $branchIds = $user->branches()->pluck('branches.id')->toArray();

            // Check if the credit's branch is in the user's branches
            if (!in_array($credit->branch_id, $branchIds)) {
                return response()->json([
                    'status' => false,
                    'message' => 'You do not have permission to approve this credit request'
                ], 403);
            }
        }

        // Check current status
        if ($credit->status === 'approved') {
            return response()->json([
                'status' => false,
                'message' => 'This request is already approved'
            ], 422);
        }

        if ($credit->status === 'rejected') {
            return response()->json([
                'status' => false,
                'message' => 'Cannot approve a rejected request'
            ], 422);
        }

        // Check user permissions
        if (!($user->hasRole('admin') || $user->hasRole('shareholder'))) {
            return response()->json([
                'status' => false,
                'message' => 'Unauthorized. Only admin and shareholder can approve credit requests.'
            ], 403);
        }

        if (!$user->hasPermissionTo('approve_credits')) {
            return response()->json([
                'status' => false,
                'message' => 'You do not have permission to approve credit requests.'
            ], 403);
        }

        // Update status to approved
        $credit->status = 'approved';
        $credit->shareholder_id = $user->id;
        $credit->save();

        // Record who approved this request
        $actionType = $credit->type === 'deposit' ? 'Deposit' : 'Withdrawal';

        return response()->json([
            'status' => true,
            'message' => $actionType . ' request has been successfully approved',
            'data' => $credit->load(['branch', 'user', 'shareholder'])
        ]);
    }

    /**
     * Reject a credit deposit or withdrawal request
     * 
     * @param Request $request
     * @param string $id Credit ID
     * @return \Illuminate\Http\JsonResponse
     */
    public function rejectRequest(Request $request, string $id)
    {
        $credit = Credit::with(['branch', 'user'])->find($id);

        if (!$credit) {
            return response()->json([
                'status' => false,
                'message' => 'Credit request not found'
            ], 404);
        }

        // Get current authenticated user
        $user = Auth::user();

        // If user is a shareholder (but not admin), verify they can access this credit
        if ($user->hasRole('shareholder') && !$user->hasRole('admin')) {
            // Get the branches that the shareholder belongs to
            $branchIds = $user->branches()->pluck('branches.id')->toArray();

            // Check if the credit's branch is in the user's branches
            if (!in_array($credit->branch_id, $branchIds)) {
                return response()->json([
                    'status' => false,
                    'message' => 'You do not have permission to reject this credit request'
                ], 403);
            }
        }

        // Check current status
        if ($credit->status === 'approved') {
            return response()->json([
                'status' => false,
                'message' => 'Cannot reject an already approved request'
            ], 422);
        }

        if ($credit->status === 'rejected') {
            return response()->json([
                'status' => false,
                'message' => 'This request is already rejected'
            ], 422);
        }

        // Check user permissions
        if (!($user->hasRole('admin') || $user->hasRole('shareholder'))) {
            return response()->json([
                'status' => false,
                'message' => 'Unauthorized. Only admin and shareholder can reject credit requests.'
            ], 403);
        }

        if (!$user->hasPermissionTo('approve_credits')) {
            return response()->json([
                'status' => false,
                'message' => 'You do not have permission to manage credit requests.'
            ], 403);
        }

        // Validate rejection reason
        $validator = Validator::make($request->all(), [
            'reason' => 'required|string|max:500',
        ]);

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

        // Update status to rejected
        $credit->status = 'rejected';
        $credit->notes = $credit->notes ? $credit->notes . "\n\nRejection reason: " . $request->reason : "Rejection reason: " . $request->reason;
        $credit->save();

        $actionType = $credit->type === 'deposit' ? 'Deposit' : 'Withdrawal';

        return response()->json([
            'status' => true,
            'message' => $actionType . ' request has been rejected',
            'data' => $credit->load(['branch', 'user', 'shareholder'])
        ]);
    }

    /**
     * Get credit balance for a shareholder in a branch
     */
    public function getBalance(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'shareholder_id' => 'nullable|exists:users,id',
            'branch_id' => 'nullable|exists:branches,id',
        ]);

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

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

        // 查询所有shareholder的余额
        if (!$request->has('shareholder_id')) {
            // 如果指定了特定branch
            if ($request->has('branch_id')) {
                $balances = CreditBalance::where('branch_id', $request->branch_id)
                    ->with(['shareholder', 'branch'])
                    ->get();

                $totalBalance = $balances->sum('balance');
                $totalWallet = $balances->sum('wallet');

                // 获取分支名称
                $branch = Branch::find($request->branch_id);
                $branchName = $branch ? $branch->name : '';

                return response()->json([
                    'status' => true,
                    'message' => 'Balances retrieved successfully',
                    'data' => [
                        'total_balance' => $totalBalance,
                        'total_wallet' => $totalWallet,
                        'branch_id' => $request->branch_id,
                        'branch_name' => $branchName,
                        'shareholder_balances' => $balances->map(function ($item) {
                            return [
                                'shareholder_id' => $item->shareholder_id,
                                'shareholder_name' => $item->shareholder ? $item->shareholder->name : '',
                                'balance' => $item->balance,
                                'wallet' => $item->wallet
                            ];
                        })
                    ]
                ]);
            }

            // 如果没有指定branch，返回所有branch的总余额
            $balances = CreditBalance::with(['shareholder', 'branch'])->get();

            $totalBalance = $balances->sum('balance');
            $totalWallet = $balances->sum('wallet');

            // 按branch分组的余额
            $branchBalances = [];
            foreach ($balances as $balance) {
                $branchId = $balance->branch_id;
                if (!isset($branchBalances[$branchId])) {
                    $branchBalances[$branchId] = [
                        'branch_id' => $branchId,
                        'branch_name' => $balance->branch ? $balance->branch->name : '',
                        'balance' => 0,
                        'wallet' => 0
                    ];
                }
                $branchBalances[$branchId]['balance'] += $balance->balance;
                $branchBalances[$branchId]['wallet'] += $balance->wallet;
            }

            return response()->json([
                'status' => true,
                'message' => 'All balances retrieved successfully',
                'data' => [
                    'total_balance' => $totalBalance,
                    'total_wallet' => $totalWallet,
                    'branch_balances' => array_values($branchBalances)
                ]
            ]);
        }

        // 单个shareholder的余额查询
        $shareholderId = $request->shareholder_id;

        // 如果指定了特定branch
        if ($request->has('branch_id')) {
            $balance = CreditBalance::where('shareholder_id', $shareholderId)
                ->where('branch_id', $request->branch_id)
                ->first();

            // 获取分支名称
            $branch = Branch::find($request->branch_id);
            $branchName = $branch ? $branch->name : '';

            return response()->json([
                'status' => true,
                'message' => 'Balance retrieved successfully',
                'data' => [
                    'balance' => $balance ? $balance->balance : 0,
                    'wallet' => $balance ? $balance->wallet : 0,
                    'branch_id' => $request->branch_id,
                    'branch_name' => $branchName
                ]
            ]);
        }

        // 如果没有指定branch，返回所有branch的余额和总余额
        $balances = CreditBalance::where('shareholder_id', $shareholderId)
            ->with('branch')
            ->get();

        $totalBalance = $balances->sum('balance');
        $totalWallet = $balances->sum('wallet');

        $branchBalances = $balances->map(function ($item) {
            return [
                'branch_id' => $item->branch_id,
                'branch_name' => $item->branch->name ?? '',
                'balance' => $item->balance,
                'wallet' => $item->wallet
            ];
        });

        // 如果没有余额记录，获取用户有权限的所有分支
        if ($branchBalances->isEmpty()) {
            if ($user->hasRole('admin')) {
                // 管理员可以看到所有分支
                $branches = Branch::all();
            } else {
                // 普通用户只能看到自己所属的分支
                $branches = $user->branches;
            }

            $branchBalances = $branches->map(function ($branch) use ($shareholderId) {
                return [
                    'branch_id' => $branch->id,
                    'branch_name' => $branch->name,
                    'balance' => 0,
                    'wallet' => 0
                ];
            });
        }

        return response()->json([
            'status' => true,
            'message' => 'Balances retrieved successfully',
            'data' => [
                'total_balance' => $totalBalance,
                'total_wallet' => $totalWallet,
                'branch_balances' => $branchBalances
            ]
        ]);
    }

    /**
     * Verify and recalculate credit balances
     */
    public function verifyBalances()
    {
        // Get current authenticated user
        $user = Auth::user();

        // Only admin can verify balances
        if (!$user->hasRole('admin')) {
            return response()->json([
                'status' => false,
                'message' => 'Unauthorized. Only admin can verify balances.'
            ], 403);
        }

        try {
            DB::beginTransaction();

            // Get all unique shareholder-branch combinations
            $combinations = Credit::select('shareholder_id', 'branch_id')
                ->whereNotNull('shareholder_id')
                ->distinct()
                ->get();

            foreach ($combinations as $combination) {
                // Calculate actual balance from credits
                $actualBalance = Credit::where('shareholder_id', $combination->shareholder_id)
                    ->where('branch_id', $combination->branch_id)
                    ->where('status', 'approved')
                    ->where('active', true)
                    ->sum(DB::raw('CASE WHEN type = "deposit" THEN amount ELSE -amount END'));

                // Update or create credit balance record
                CreditBalance::updateOrCreate(
                    [
                        'shareholder_id' => $combination->shareholder_id,
                        'branch_id' => $combination->branch_id,
                    ],
                    [
                        'balance' => $actualBalance,
                    ]
                );
            }

            DB::commit();

            return response()->json([
                'status' => true,
                'message' => 'Credit balances verified and updated successfully'
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'status' => false,
                'message' => 'Error verifying balances: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Update credit balance for a shareholder in a branch
     */
    public function updateCreditBalance($shareholderId, $branchId, $amount, $operation)
    {
        $balance = CreditBalance::where('shareholder_id', $shareholderId)
            ->where('branch_id', $branchId)
            ->first();

        if ($balance) {
            if ($operation === 'add') {
                $balance->balance = $balance->balance + $amount;
                // For deposits, add 10% of the deposit amount to existing wallet
                $balance->wallet = $balance->wallet + round($amount * 0.1, 2);
            } else {
                $balance->balance = $balance->balance - $amount;
                // For withdrawals, directly subtract the same amount from wallet
                $balance->wallet = $balance->wallet - $amount;
            }
            $balance->save();
        } else {
            CreditBalance::create([
                'shareholder_id' => $shareholderId,
                'branch_id' => $branchId,
                'balance' => $operation === 'add' ? $amount : -$amount,
                'wallet' => $operation === 'add' ? round($amount * 0.1, 2) : -$amount,
            ]);
        }
    }

    /**
     * 检查并对比计算出的余额与存储的余额
     */
    public function checkBalance(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'shareholder_id' => 'nullable|exists:users,id',
            'branch_id' => 'nullable|exists:branches,id',
        ]);

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

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

        // 只有管理员可以检查余额
        if (!$user->hasRole('admin')) {
            return response()->json([
                'status' => false,
                'message' => 'Unauthorized. Only admin can check balance accuracy.'
            ], 403);
        }

        $query = Credit::query()
            ->where('status', 'approved')
            ->where('active', true);

        if ($request->has('shareholder_id')) {
            $query->where('shareholder_id', $request->shareholder_id);
        }

        if ($request->has('branch_id')) {
            $query->where('branch_id', $request->branch_id);
        }

        // 获取所有已审核的活动credits
        $credits = $query->get();

        // 按shareholder_id和branch_id分组，计算每组的余额
        $calculatedBalances = [];
        foreach ($credits as $credit) {
            $key = $credit->shareholder_id . '_' . $credit->branch_id;
            if (!isset($calculatedBalances[$key])) {
                $calculatedBalances[$key] = [
                    'shareholder_id' => $credit->shareholder_id,
                    'branch_id' => $credit->branch_id,
                    'calculated_balance' => 0,
                    'stored_balance' => 0,
                    'is_match' => true
                ];
            }

            $amount = $credit->type === 'deposit' ? $credit->amount : -$credit->amount;
            $calculatedBalances[$key]['calculated_balance'] += $amount;
        }

        // 获取存储的余额
        $storedBalances = CreditBalance::when($request->has('shareholder_id'), function ($query) use ($request) {
            return $query->where('shareholder_id', $request->shareholder_id);
        })
            ->when($request->has('branch_id'), function ($query) use ($request) {
                return $query->where('branch_id', $request->branch_id);
            })
            ->get();

        // 比较计算出的余额和存储的余额
        foreach ($storedBalances as $balance) {
            $key = $balance->shareholder_id . '_' . $balance->branch_id;
            if (isset($calculatedBalances[$key])) {
                $calculatedBalances[$key]['stored_balance'] = $balance->balance;
                $calculatedBalances[$key]['is_match'] = abs($calculatedBalances[$key]['calculated_balance'] - $balance->balance) < 0.01;
            } else {
                $calculatedBalances[$key] = [
                    'shareholder_id' => $balance->shareholder_id,
                    'branch_id' => $balance->branch_id,
                    'calculated_balance' => 0,
                    'stored_balance' => $balance->balance,
                    'is_match' => abs($balance->balance) < 0.01
                ];
            }
        }

        $results = array_values($calculatedBalances);
        $allMatch = !in_array(false, array_column($results, 'is_match'));

        return response()->json([
            'status' => true,
            'message' => $allMatch ? 'All balances match' : 'Some balances do not match',
            'data' => [
                'all_match' => $allMatch,
                'balances' => $results
            ]
        ]);
    }
}
