<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Account;

class LedgerController extends Controller
{
    public function index()
    {
        // Load all accounts ordered by code
        $accounts = Account::orderBy('code')->get();

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

    public function generate(Request $request)
    {
        $request->validate([
            'accounts' => 'required|array',
            'accounts.*' => 'exists:accounts,id',
        ]);

        $ledgers = Account::with(['journalTransactions' => function ($query) {
            $query->orderBy('created_at');
        }])->whereIn('id', $request->accounts)->get()->map(function ($account) {
            return [
                'account' => $account,
                'transactions' => $account->journalTransactions,
            ];
        });

        return view('admin.ledger.result', compact('ledgers'));
    }
}
