<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\JointAccount;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class JointAccountApprovalController extends Controller
{
    public function pendingAccounts(): JsonResponse
    {
        try {
            $pendingAccounts = JointAccount::where('status', 'pending')
                ->with(['members.user', 'creator'])
                ->withCount('activeMembers')
                ->latest()
                ->get();

            return response()->json([
                'status' => 'success',
                'pending_accounts' => $pendingAccounts
            ]);
        } catch (\Exception $e) {
            \Log::error('Admin Joint Account Approval Error: ' . $e->getMessage());
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to fetch pending joint accounts',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    public function approveAccount(Request $request, $id): JsonResponse
    {
        try {
            $jointAccount = JointAccount::find($id);

            if (!$jointAccount) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Joint account not found'
                ], 404);
            }

            if ($jointAccount->status !== 'pending') {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Joint account is not pending approval'
                ], 400);
            }

            DB::beginTransaction();

            // Update joint account status to active
            $jointAccount->update([
                'status' => 'active'
            ]);

            // Activate all pending members
            $jointAccount->members()->where('status', 'pending')->update([
                'status' => 'active',
                'joined_at' => now()
            ]);

            DB::commit();

            return response()->json([
                'status' => 'success',
                'message' => 'Joint account approved successfully',
                'joint_account' => $jointAccount->load(['members.user', 'creator'])
            ]);

        } catch (\Exception $e) {
            DB::rollBack();
            \Log::error('Admin Joint Account Approval Error: ' . $e->getMessage());
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to approve joint account',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    public function rejectAccount(Request $request, $id): JsonResponse
    {
        try {
            $jointAccount = JointAccount::find($id);

            if (!$jointAccount) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Joint account not found'
                ], 404);
            }

            if ($jointAccount->status !== 'pending') {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Joint account is not pending approval'
                ], 400);
            }

            DB::beginTransaction();

            // Update joint account status to closed
            $jointAccount->update([
                'status' => 'closed'
            ]);

            // Remove all pending members
            $jointAccount->members()->where('status', 'pending')->delete();

            DB::commit();

            return response()->json([
                'status' => 'success',
                'message' => 'Joint account rejected successfully'
            ]);

        } catch (\Exception $e) {
            DB::rollBack();
            \Log::error('Admin Joint Account Rejection Error: ' . $e->getMessage());
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to reject joint account',
                'error' => $e->getMessage()
            ], 500);
        }
    }
}
