<?php

namespace App\Http\Controllers;

use App\Models\BankAccount;
use Illuminate\Http\Request;

class BankAccountController extends Controller
{
    public function index()
    {
        if (auth()->check() && auth()->user()->isSuperAdmin()) {
            $accounts = BankAccount::with('transactions')
                ->orderBy('is_active', 'desc')
                ->orderBy('bank_name')
                ->get();
        } else {
            $accounts = auth()->user()->bankAccounts()
                ->with('transactions')
                ->orderBy('is_active', 'desc')
                ->orderBy('bank_name')
                ->get();
        }

        return view('bank-accounts.index', compact('accounts'));
    }

    public function create()
    {
        return view('bank-accounts.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'account_name' => 'required|string|max:255',
            'account_number' => 'nullable|string|max:50',
            'bank_name' => 'required|string|max:255',
            'branch' => 'nullable|string|max:255',
            'initial_balance' => 'nullable|numeric|min:0',
        ]);

        $account = auth()->user()->bankAccounts()->create([
            'account_name' => $validated['account_name'],
            'account_number' => $validated['account_number'],
            'bank_name' => $validated['bank_name'],
            'branch' => $validated['branch'],
            'balance' => $validated['initial_balance'] ?? 0,
            'is_active' => true,
        ]);

        if ($validated['initial_balance'] > 0) {
            // Create initial balance transaction
            $account->user->transactions()->create([
                'date' => now(),
                'type' => 'income',
                'payment_method' => 'bank',
                'bank_account_id' => $account->id,
                'amount' => $validated['initial_balance'],
                'balance_before' => 0,
                'balance_after' => $validated['initial_balance'],
                'details' => 'Initial balance for ' . $account->account_name,
                'reference' => 'INITIAL',
            ]);
        }

        return redirect()->route('bank-accounts.index')
            ->with('success', 'Bank account created successfully.');
    }

    public function edit(BankAccount $bankAccount)
    {
        $this->authorize('update', $bankAccount);
        return view('bank-accounts.edit', compact('bankAccount'));
    }

    public function update(Request $request, BankAccount $bankAccount)
    {
        $this->authorize('update', $bankAccount);

        $validated = $request->validate([
            'account_name' => 'required|string|max:255',
            'account_number' => 'nullable|string|max:50',
            'bank_name' => 'required|string|max:255',
            'branch' => 'nullable|string|max:255',
            'is_active' => 'boolean',
        ]);

        $bankAccount->update($validated);

        return redirect()->route('bank-accounts.index')
            ->with('success', 'Bank account updated successfully.');
    }

    public function destroy(BankAccount $bankAccount)
    {
        $this->authorize('delete', $bankAccount);

        $bankAccount->delete();

        return redirect()->route('bank-accounts.index')
            ->with('success', 'Bank account deleted successfully.');
    }
}
