<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\SuperAdminBankAccount;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SuperAdminBankAccountController extends Controller
{
    public function index(Request $request)
    {
        \Log::info('SuperAdminBankAccountController::index called', [
            'user_id' => $request->user()?->id,
            'user_role' => $request->user()?->role
        ]);
        
        $accounts = SuperAdminBankAccount::latest()->get();
        
        \Log::info('SuperAdminBankAccount query result', [
            'count' => $accounts->count(),
            'accounts' => $accounts->toArray()
        ]);
        
        return response()->json(['data' => $accounts]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'account_name' => 'required|string|max:255',
            'bank_name' => 'required|string|max:255',
            'account_number' => 'required|string|max:50|unique:super_admin_bank_accounts,account_number',
            'account_type' => 'required|in:current,savings,domiciliary',
            'currency' => 'required|string|max:3',
            'opening_balance' => 'required|numeric|min:0',
            'is_primary' => 'boolean',
            'is_active' => 'boolean',
            'notes' => 'nullable|string',
        ]);

        // If setting as primary, remove primary from other accounts
        if ($validated['is_primary'] ?? false) {
            SuperAdminBankAccount::where('is_primary', true)->update(['is_primary' => false]);
        }

        $account = SuperAdminBankAccount::create([
            'account_name' => $validated['account_name'],
            'bank_name' => $validated['bank_name'],
            'account_number' => $validated['account_number'],
            'account_type' => $validated['account_type'],
            'currency' => $validated['currency'],
            'opening_balance' => $validated['opening_balance'],
            'current_balance' => $validated['opening_balance'],
            'is_primary' => $validated['is_primary'] ?? false,
            'is_active' => $validated['is_active'] ?? true,
            'notes' => $validated['notes'] ?? null,
        ]);

        return response()->json(['data' => $account, 'message' => 'Super Admin bank account created successfully'], 201);
    }

    public function show($id)
    {
        $account = SuperAdminBankAccount::findOrFail($id);
        return response()->json(['data' => $account]);
    }

    public function update(Request $request, $id)
    {
        $account = SuperAdminBankAccount::findOrFail($id);

        $validated = $request->validate([
            'account_name' => 'sometimes|string|max:255',
            'bank_name' => 'sometimes|string|max:255',
            'account_number' => 'sometimes|string|max:50|unique:super_admin_bank_accounts,account_number,' . $id,
            'account_type' => 'sometimes|in:current,savings,domiciliary',
            'currency' => 'sometimes|string|max:3',
            'opening_balance' => 'sometimes|numeric|min:0',
            'is_primary' => 'sometimes|boolean',
            'is_active' => 'sometimes|boolean',
            'notes' => 'nullable|string',
        ]);

        // If setting as primary, remove primary from other accounts
        if (isset($validated['is_primary']) && $validated['is_primary']) {
            SuperAdminBankAccount::where('id', '!=', $id)->where('is_primary', true)->update(['is_primary' => false]);
        }

        $account->update($validated);

        return response()->json(['data' => $account->fresh(), 'message' => 'Bank account updated successfully']);
    }

    public function destroy($id)
    {
        $account = SuperAdminBankAccount::findOrFail($id);

        // Prevent deletion if account has transactions
        $hasLoans = \App\Models\IntercompanyLoan::where('super_admin_bank_account_id', $id)->count() > 0;
        $hasSweeps = \App\Models\ProfitSweepTransaction::where('super_admin_bank_account_id', $id)->count() > 0;

        if ($hasLoans || $hasSweeps) {
            return response()->json(['message' => 'Cannot delete account with existing transactions. Deactivate instead.'], 400);
        }

        $account->delete();

        return response()->json(['message' => 'Bank account deleted successfully']);
    }

    // Get active accounts for dropdown
    public function list(Request $request)
    {
        $accounts = SuperAdminBankAccount::where('is_active', true)
            ->select('id', 'account_name', 'bank_name', 'account_number', 'currency', 'is_primary', 'current_balance')
            ->orderBy('is_primary', 'desc')
            ->orderBy('account_name')
            ->get();

        return response()->json(['data' => $accounts]);
    }

    // Public list for company users to select holding accounts when repaying loans
    public function publicList(Request $request)
    {
        $accounts = SuperAdminBankAccount::where('is_active', true)
            ->select('id', 'account_name', 'bank_name', 'account_number', 'currency', 'is_primary')
            ->orderBy('is_primary', 'desc')
            ->orderBy('account_name')
            ->get();

        return response()->json(['data' => $accounts]);
    }
}
