<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Credit;
use App\Models\Branch;
use App\Models\User;
use App\Models\WithdrawalApproval;
use App\Models\CreditBalance;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use App\Http\Controllers\API\CreditController;

class WithdrawalController extends Controller
{
    /**
     * Display a listing of the withdrawal requests.
     */
    public function index(Request $request)
    {
        // Support filtering by branch and status
        $query = Credit::query()->where('type', 'withdrawal');

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

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

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

        $withdrawals = $query->with(['branch', 'user', 'shareholder', 'withdrawalApprovals.shareholder'])
            ->orderBy('created_at', 'desc')
            ->get();

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

    /**
     * Store a newly created withdrawal request.
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'amount' => 'required|numeric|min:0',
            'branch_id' => 'required|exists:branches,id',
            'withdrawal_type' => 'required|in:branch,shareholder',
            'attachment' => 'nullable|file|mimes:jpeg,png,jpg,pdf|max:2048',
            'notes' => 'nullable|string|max:500',
        ]);

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

        // Verify the branch exists
        $branch = Branch::find($request->branch_id);
        if (!$branch) {
            return response()->json([
                'status' => false,
                'message' => 'Branch not found'
            ], 404);
        }

        // Check if the user is a shareholder of this branch
        $user = Auth::user();
        $isBranchShareholder = $user->checkThisBranchBelong($branch);

        if (!$isBranchShareholder) {
            return response()->json([
                'status' => false,
                'message' => 'You are not authorized to create withdrawal requests for this branch'
            ], 403);
        }

        // Handle branch wallet withdrawal
        if ($request->withdrawal_type === 'branch') {
            if ($request->amount > $branch->wallet) {
                return response()->json([
                    'status' => false,
                    'message' => 'Withdrawal amount exceeds available branch wallet balance',
                    'available_wallet' => $branch->wallet
                ], 422);
            }

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

            // Create withdrawal request with pending status
            DB::beginTransaction();
            try {
                $withdrawal = Credit::create([
                    'amount' => $request->amount,
                    'type' => 'withdrawal',
                    'withdrawal_type' => 'branch',
                    'status' => 'pending',
                    'active' => true,
                    'branch_id' => $request->branch_id,
                    'user_id' => Auth::id(),
                    'shareholder_id' => Auth::id(),
                    'attachment' => $attachmentPath,
                    'notes' => $request->notes,
                ]);

                // Get shareholders for this branch
                $shareholders = $branch->users()->role('shareholder')->get();

                // Create withdrawal approval records for each shareholder
                foreach ($shareholders as $shareholder) {
                    WithdrawalApproval::create([
                        'credit_id' => $withdrawal->id,
                        'shareholder_id' => $shareholder->id,
                        'branch_id' => $branch->id,
                        'status' => 'pending'
                    ]);
                }

                DB::commit();

                return response()->json([
                    'status' => true,
                    'message' => 'Branch withdrawal request created successfully and pending shareholder approval',
                    'data' => $withdrawal->load(['branch', 'user', 'withdrawalApprovals.shareholder'])
                ], 201);
            } catch (\Exception $e) {
                DB::rollBack();
                return response()->json([
                    'status' => false,
                    'message' => 'Failed to create branch withdrawal request',
                    'error' => $e->getMessage()
                ], 500);
            }
        }

        // Handle shareholder withdrawal
        $creditBalance = CreditBalance::where('shareholder_id', $user->id)
            ->where('branch_id', $request->branch_id)
            ->first();

        if (!$creditBalance) {
            return response()->json([
                'status' => false,
                'message' => 'No credit balance found for this branch'
            ], 404);
        }

        $userBalance = $creditBalance->balance;
        $userWallet = $creditBalance->wallet;

        // Check if there is sufficient wallet balance
        if ($request->amount > $userWallet) {
            return response()->json([
                'status' => false,
                'message' => 'Withdrawal amount exceeds your available wallet balance in this branch',
                'available_balance' => $userBalance,
                'available_wallet' => $userWallet
            ], 422);
        }

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

        // Create withdrawal request with pending status
        DB::beginTransaction();
        try {
            $withdrawal = Credit::create([
                'amount' => $request->amount,
                'type' => 'withdrawal',
                'withdrawal_type' => 'shareholder',
                'status' => 'pending',
                'active' => true,
                'branch_id' => $request->branch_id,
                'user_id' => Auth::id(),
                'shareholder_id' => Auth::id(),
                'attachment' => $attachmentPath,
                'notes' => $request->notes,
            ]);

            // Get shareholders for this branch
            $shareholders = $branch->users()->role('shareholder')->get();

            // Create withdrawal approval records for each shareholder
            foreach ($shareholders as $shareholder) {
                WithdrawalApproval::create([
                    'credit_id' => $withdrawal->id,
                    'shareholder_id' => $shareholder->id,
                    'branch_id' => $branch->id,
                    'status' => 'pending'
                ]);
            }

            DB::commit();

            return response()->json([
                'status' => true,
                'message' => 'Withdrawal request created successfully',
                'data' => $withdrawal->load(['branch', 'user', 'withdrawalApprovals.shareholder'])
            ], 201);
        } catch (\Exception $e) {
            DB::rollBack();

            // Delete the uploaded file if exists
            if ($attachmentPath) {
                Storage::disk('public')->delete($attachmentPath);
            }

            return response()->json([
                'status' => false,
                'message' => 'Failed to create withdrawal request',
                'error' => $e->getMessage()
            ], 500);
        }
    }

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

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

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

    /**
     * Update the specified withdrawal request.
     */
    public function update(Request $request, string $id)
    {
        $withdrawal = Credit::where('type', 'withdrawal')->find($id);

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

        // Only allow updates if status is pending
        if ($withdrawal->status !== 'pending') {
            return response()->json([
                'status' => false,
                'message' => 'Cannot update a withdrawal request that is not pending'
            ], 422);
        }

        // Check if the user is a shareholder of the branch
        $user = Auth::user();
        $isBranchShareholder = $user->checkThisBranchBelong($withdrawal->branch);

        if (!$isBranchShareholder) {
            return response()->json([
                'status' => false,
                'message' => 'You are not authorized to update withdrawal requests for this branch'
            ], 403);
        }

        $validator = Validator::make($request->all(), [
            'amount' => 'sometimes|required|numeric|min:0',
            'branch_id' => 'sometimes|required|exists:branches,id',
            'attachment' => 'nullable|file|mimes:jpeg,png,jpg,pdf|max:2048',
            'notes' => 'nullable|string|max:500',
        ]);

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

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

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

        // Check if amount is being updated and if it exceeds branch balance
        if ($request->has('amount') && $request->amount != $withdrawal->amount) {
            $branch = Branch::find($withdrawal->branch_id);
            if ($request->amount > $branch->credit_balance) {
                return response()->json([
                    'status' => false,
                    'message' => 'Withdrawal amount exceeds available branch balance',
                    'available_balance' => $branch->credit_balance
                ], 422);
            }

            // Check if withdrawal amount exceeds user's credit balance in this branch
            $creditBalance = CreditBalance::where('shareholder_id', $user->id)
                ->where('branch_id', $withdrawal->branch_id)
                ->first();

            $userBalance = $creditBalance ? $creditBalance->balance : 0;

            if ($request->amount > $userBalance) {
                return response()->json([
                    'status' => false,
                    'message' => 'Withdrawal amount exceeds your available credit balance in this branch',
                    'available_balance' => $userBalance
                ], 422);
            }

            // Get sum of user's other pending withdrawal requests for this branch
            $pendingWithdrawals = Credit::where('type', 'withdrawal')
                ->where('status', 'pending')
                ->where('shareholder_id', $user->id)
                ->where('branch_id', $withdrawal->branch_id)
                ->where('id', '!=', $withdrawal->id) // Exclude current withdrawal
                ->sum('amount');

            // Check if the total of pending withdrawals plus the updated withdrawal exceeds user's balance
            if (($pendingWithdrawals + $request->amount) > $userBalance) {
                return response()->json([
                    'status' => false,
                    'message' => 'Total of pending and updated withdrawal requests exceeds your available credit balance',
                    'available_balance' => $userBalance,
                    'pending_withdrawals' => $pendingWithdrawals,
                    'remaining_available' => $userBalance - $pendingWithdrawals
                ], 422);
            }
        }

        // Check if branch_id is being updated
        if ($request->has('branch_id') && $withdrawal->branch_id != $request->branch_id) {
            // Get the new branch and check balance
            $branch = Branch::find($request->branch_id);
            if (!$branch) {
                return response()->json([
                    'status' => false,
                    'message' => 'Branch not found'
                ], 404);
            }

            // Check if withdrawal amount exceeds new branch balance
            $amount = $request->has('amount') ? $request->amount : $withdrawal->amount;
            if ($amount > $branch->credit_balance) {
                return response()->json([
                    'status' => false,
                    'message' => 'Withdrawal amount exceeds available branch balance',
                    'available_balance' => $branch->credit_balance
                ], 422);
            }

            // Check if withdrawal amount exceeds user's credit balance in the new branch
            $creditBalance = CreditBalance::where('shareholder_id', $user->id)
                ->where('branch_id', $request->branch_id)
                ->first();

            $userBalance = $creditBalance ? $creditBalance->balance : 0;

            if ($amount > $userBalance) {
                return response()->json([
                    'status' => false,
                    'message' => 'Withdrawal amount exceeds your available credit balance in the new branch',
                    'available_balance' => $userBalance
                ], 422);
            }

            // Get sum of user's pending withdrawal requests for the new branch
            $pendingWithdrawals = Credit::where('type', 'withdrawal')
                ->where('status', 'pending')
                ->where('shareholder_id', $user->id)
                ->where('branch_id', $request->branch_id)
                ->where('id', '!=', $withdrawal->id) // Exclude current withdrawal
                ->sum('amount');

            // Check if the total of pending withdrawals plus the new withdrawal exceeds user's balance
            if (($pendingWithdrawals + $amount) > $userBalance) {
                return response()->json([
                    'status' => false,
                    'message' => 'Total of pending and new withdrawal requests exceeds your available credit balance in the new branch',
                    'available_balance' => $userBalance,
                    'pending_withdrawals' => $pendingWithdrawals,
                    'remaining_available' => $userBalance - $pendingWithdrawals
                ], 422);
            }

            // Check if the user is a shareholder of the new branch
            $isNewBranchShareholder = DB::table('user_branch')
                ->where('user_id', $user->id)
                ->where('branch_id', $branch->id)
                ->where('role', 'shareholder')
                ->exists();

            if (!$isNewBranchShareholder) {
                return response()->json([
                    'status' => false,
                    'message' => 'You are not authorized to move withdrawal requests to this branch'
                ], 403);
            }

            DB::beginTransaction();
            try {
                // Delete old withdrawal approvals
                WithdrawalApproval::where('credit_id', $withdrawal->id)->delete();

                // Get shareholders for the new branch
                $shareholders = $branch->users()->role('shareholder')->get();

                // Create new withdrawal approval records for each shareholder
                foreach ($shareholders as $shareholder) {
                    WithdrawalApproval::create([
                        'credit_id' => $withdrawal->id,
                        'shareholder_id' => $shareholder->id,
                        'branch_id' => $branch->id,
                        'status' => 'pending'
                    ]);
                }

                $withdrawal->branch_id = $request->branch_id;
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                return response()->json([
                    'status' => false,
                    'message' => 'Failed to update withdrawal request',
                    'error' => $e->getMessage()
                ], 500);
            }
        }

        // Update fields
        if ($request->has('amount')) $withdrawal->amount = $request->amount;
        if ($request->has('notes')) $withdrawal->notes = $request->notes;

        $withdrawal->save();

        return response()->json([
            'status' => true,
            'message' => 'Withdrawal request updated successfully',
            'data' => $withdrawal->load(['branch', 'user', 'withdrawalApprovals.shareholder'])
        ]);
    }

    /**
     * Remove the specified withdrawal request.
     */
    public function destroy(string $id)
    {
        $withdrawal = Credit::where('type', 'withdrawal')->find($id);

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

        // Only allow deletion if status is pending
        if ($withdrawal->status !== 'pending') {
            return response()->json([
                'status' => false,
                'message' => 'Cannot delete a withdrawal request that is not pending'
            ], 422);
        }

        // Check if the user is a shareholder of the branch
        $user = Auth::user();
        $isBranchShareholder = $user->checkThisBranchBelong($withdrawal->branch);

        if (!$isBranchShareholder) {
            return response()->json([
                'status' => false,
                'message' => 'You are not authorized to delete withdrawal requests for this branch'
            ], 403);
        }

        DB::beginTransaction();
        try {
            // Delete withdrawal approvals
            WithdrawalApproval::where('credit_id', $withdrawal->id)->delete();

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

            $withdrawal->delete();

            DB::commit();

            return response()->json([
                'status' => true,
                'message' => 'Withdrawal request deleted successfully'
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'status' => false,
                'message' => 'Failed to delete withdrawal request',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Approve a withdrawal request as a shareholder.
     * 
     * @param string $id Credit ID
     * @return \Illuminate\Http\JsonResponse
     */
    public function approveAsShareHolder(string $id)
    {
        $withdrawal = Credit::with(['branch', 'withdrawalApprovals'])
            ->where('type', 'withdrawal')
            ->find($id);

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

        // Check current status
        if ($withdrawal->status !== 'pending') {
            return response()->json([
                'status' => false,
                'message' => 'This withdrawal request is not pending'
            ], 422);
        }

        // Check user permissions
        $user = Auth::user();

        if (!$user->hasRole('shareholder')) {
            return response()->json([
                'status' => false,
                'message' => 'Unauthorized. Only shareholders can approve withdrawal requests.'
            ], 403);
        }

        // Check if user is a shareholder of the branch
        $isBranchShareholder = $user->checkThisBranchBelong($withdrawal->branch);

        if (!$isBranchShareholder) {
            return response()->json([
                'status' => false,
                'message' => 'You are not authorized to approve withdrawals for this branch'
            ], 403);
        }

        // Check if the user has already approved this withdrawal
        $approval = WithdrawalApproval::where('credit_id', $withdrawal->id)
            ->where('shareholder_id', $user->id)
            ->first();

        if (!$approval) {
            return response()->json([
                'status' => false,
                'message' => 'No approval record found for this withdrawal and shareholder'
            ], 404);
        }

        if ($approval->status === 'approved') {
            return response()->json([
                'status' => false,
                'message' => 'You have already approved this withdrawal request'
            ], 422);
        }
        try {
            DB::beginTransaction();

            // Check balance before approval based on withdrawal type
            if ($withdrawal->withdrawal_type === 'branch') {
                $branch = Branch::find($withdrawal->branch_id);
                if (!$branch || $withdrawal->amount > $branch->wallet) {
                    DB::rollBack();
                    return response()->json([
                        'status' => false,
                        'message' => 'Branch wallet balance is insufficient for this withdrawal',
                        'available_wallet' => $branch ? $branch->wallet : 0
                    ], 422);
                }
            } else {
                // Check shareholder wallet balance
                $creditBalance = CreditBalance::where('shareholder_id', $withdrawal->shareholder_id)
                    ->where('branch_id', $withdrawal->branch_id)
                    ->first();

                if (!$creditBalance || $withdrawal->amount > $creditBalance->wallet) {
                    DB::rollBack();
                    return response()->json([
                        'status' => false,
                        'message' => 'Shareholder wallet balance is insufficient for this withdrawal',
                        'available_wallet' => $creditBalance ? $creditBalance->wallet : 0
                    ], 422);
                }
            }

            // Update approval status
            $approval->status = 'approved';
            $approval->save();

            // Check if all shareholders have approved
            $allApproved = $withdrawal->withdrawalApprovals()
                ->where('status', '!=', 'approved')
                ->doesntExist();

            if ($allApproved) {
                // All shareholders have approved, update withdrawal status
                $withdrawal->status = 'approved';
                // Use the original withdrawal request's shareholder_id, not the last approving shareholder's ID
                $withdrawal->shareholder_id = $withdrawal->user_id;
                $withdrawal->save();

                // All shareholders have approved, now update balances based on withdrawal type
                if ($withdrawal->withdrawal_type === 'branch') {
                    // Update branch wallet for branch type withdrawal
                    $branch = Branch::find($withdrawal->branch_id);
                    if ($branch) {
                        $branch->wallet -= $withdrawal->amount;
                        $branch->save();
                    }
                } else {
                    // Update shareholder credit balance for shareholder type withdrawal
                    if ($withdrawal->shareholder_id) {
                        $creditBalance = CreditBalance::where('shareholder_id', $withdrawal->shareholder_id)
                            ->where('branch_id', $withdrawal->branch_id)
                            ->first();

                        if ($creditBalance) {
                            $creditBalance->wallet -= $withdrawal->amount;
                            $creditBalance->save();
                        }
                    }
                }
            }

            DB::commit();

            return response()->json([
                'status' => true,
                'message' => 'Withdrawal request has been approved by you',
                'all_approved' => $allApproved,
                'data' => $withdrawal->fresh()->load(['branch', 'user', 'shareholder', 'withdrawalApprovals.shareholder'])
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'status' => false,
                'message' => 'Error approving withdrawal: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Reject a withdrawal request as a shareholder.
     * 
     * @param Request $request
     * @param string $id Credit ID
     * @return \Illuminate\Http\JsonResponse
     */
    public function rejectAsShareHolder(Request $request, string $id)
    {
        $withdrawal = Credit::with(['branch', 'withdrawalApprovals'])
            ->where('type', 'withdrawal')
            ->find($id);

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

        // Check current status
        if ($withdrawal->status !== 'pending') {
            return response()->json([
                'status' => false,
                'message' => 'This withdrawal request is not pending'
            ], 422);
        }

        // Check user permissions
        $user = Auth::user();

        if (!$user->hasRole('shareholder')) {
            return response()->json([
                'status' => false,
                'message' => 'Unauthorized. Only shareholders can reject withdrawal requests.'
            ], 403);
        }

        // Check if user is a shareholder of the branch
        $isBranchShareholder = $user->checkThisBranchBelong($withdrawal->branch);

        if (!$isBranchShareholder) {
            return response()->json([
                'status' => false,
                'message' => 'You are not authorized to manage withdrawals for this branch'
            ], 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);
        }

        // Get the approval record for this user
        $approval = WithdrawalApproval::where('credit_id', $withdrawal->id)
            ->where('shareholder_id', $user->id)
            ->first();

        if (!$approval) {
            return response()->json([
                'status' => false,
                'message' => 'No approval record found for this withdrawal and shareholder'
            ], 404);
        }

        DB::beginTransaction();
        try {
            // Update approval status and notes
            $approval->status = 'rejected';
            $approval->notes = $request->reason;
            $approval->save();

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

            // Note: Since balance is only updated when all shareholders approve, it doesn't need to be updated here when rejected

            DB::commit();

            return response()->json([
                'status' => true,
                'message' => 'Withdrawal request has been rejected',
                'data' => $withdrawal->fresh()->load(['branch', 'user', 'shareholder', 'withdrawalApprovals.shareholder'])
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'status' => false,
                'message' => 'Failed to reject withdrawal request',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get withdrawal approval status for a given withdrawal request
     * 
     * @param string $id Credit ID
     * @return \Illuminate\Http\JsonResponse
     */
    public function getApprovalStatus(string $id)
    {
        $withdrawal = Credit::with(['withdrawalApprovals.shareholder'])
            ->where('type', 'withdrawal')
            ->find($id);

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

        // Count approvals by status
        $totalApprovals = $withdrawal->withdrawalApprovals->count();
        $approved = $withdrawal->withdrawalApprovals->where('status', 'approved')->count();
        $rejected = $withdrawal->withdrawalApprovals->where('status', 'rejected')->count();
        $pending = $withdrawal->withdrawalApprovals->where('status', 'pending')->count();

        // Get current user's approval status if they are a shareholder
        $user = Auth::user();
        $userApproval = null;

        if ($user && $user->hasRole('shareholder')) {
            $userApproval = $withdrawal->withdrawalApprovals
                ->where('shareholder_id', $user->id)
                ->first();
        }

        return response()->json([
            'status' => true,
            'message' => 'Withdrawal approval status retrieved successfully',
            'data' => [
                'withdrawal' => $withdrawal->only(['id', 'amount', 'status', 'created_at']),
                'branch' => $withdrawal->branch->only(['id', 'name']),
                'approval_stats' => [
                    'total' => $totalApprovals,
                    'approved' => $approved,
                    'rejected' => $rejected,
                    'pending' => $pending,
                ],
                'approvals' => $withdrawal->withdrawalApprovals->map(function ($approval) {
                    return [
                        'id' => $approval->id,
                        'shareholder_name' => $approval->shareholder->name,
                        'status' => $approval->status,
                        'notes' => $approval->notes,
                        'updated_at' => $approval->updated_at,
                    ];
                }),
                'user_approval' => $userApproval ? [
                    'id' => $userApproval->id,
                    'status' => $userApproval->status,
                ] : null,
            ]
        ]);
    }
}
