<?php

namespace App\Http\Controllers;

use App\Models\Account;
use App\Models\Currency;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AccountController extends Controller
{
    public function index()
    {
        $accounts = Account::with('currency')->orderBy('name')->get();
        $currencies = Currency::orderBy('code')->get();

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

    public function summary(Request $request)
    {
        $filters = $request->validate([
            'currency_id' => ['nullable', 'exists:currencies,id'],
            'type' => ['nullable', 'in:bank,cash'],
        ]);

        $accounts = Account::with('currency')
            ->join('currencies', 'accounts.currency_id', '=', 'currencies.id')
            ->when(! empty($filters['currency_id']), fn ($query) => $query->where('accounts.currency_id', $filters['currency_id']))
            ->when(! empty($filters['type']), fn ($query) => $query->where('accounts.type', $filters['type']))
            ->orderBy('currencies.code')
            ->orderBy('accounts.name')
            ->select('accounts.*')
            ->get();

        return view('accounts.summary', [
            'accounts' => $accounts,
            'currencies' => Currency::orderBy('code')->get(),
            'filters' => $filters,
        ]);
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'currency_id' => ['required', 'exists:currencies,id'],
            'type' => ['required', 'in:bank,cash'],
        ]);

        $data['balance'] = 0;

        Account::create($data);

        return redirect()
            ->route('accounts.index')
            ->with('success', 'Account added successfully.');
    }

    public function edit(Account $account)
    {
        return view('accounts.edit', [
            'account' => $account,
            'currencies' => Currency::orderBy('code')->get(),
        ]);
    }

    public function update(Request $request, Account $account)
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'currency_id' => ['required', 'exists:currencies,id'],
            'type' => ['required', 'in:bank,cash'],
        ]);

        $account->update($data);

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

    public function destroy(Account $account)
    {
        // 1. Check if the account has any "real" transactions (Buy, Sell, Borrow, Settlement)
        $hasRealTransactions = \App\Models\Transaction::where(function($query) use ($account) {
                $query->where('account_id', $account->id)
                      ->orWhere('payment_account_id', $account->id);
            })
            ->whereNotIn('type', [\App\Models\Transaction::TYPE_OPENING_BALANCE])
            ->exists();

        if ($hasRealTransactions) {
            return back()->with('error', 'Cannot delete account with transaction history (Buy/Sell/Borrow).');
        }

        // 2. Check if the balance is non-zero due to something OTHER than an opening balance?
        // Actually, if it has no real transactions, its balance MUST be from opening balance or 0.
        // We allow deleting if it's just an opening balance.

        DB::transaction(function () use ($account) {
            // Delete opening balance transactions first to avoid foreign key issues
            \App\Models\Transaction::where('account_id', $account->id)
                ->where('type', \App\Models\Transaction::TYPE_OPENING_BALANCE)
                ->delete();

            // Delete the account
            $account->delete();
        });

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