<?php

namespace App\Http\Controllers\Admin\Accounting;

use App\Http\Controllers\Admin\PageController;
use App\Models\Account;
use App\Exports\GeneralLedgerExport;
use App\Services\Accounting\GeneralLedgerService;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\View\View;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

class GeneralLedgerController extends PageController
{
    public function __construct(
        private readonly GeneralLedgerService $generalLedgerService,
    ) {}

    public function index(Request $request): View
    {
        $accounts = Account::query()->orderBy('code')->get();
        $accountId = $request->integer('account_id') ?: $accounts->first()?->id;
        $account = $accountId ? Account::query()->find($accountId) : null;

        $from = $request->filled('from') ? Carbon::parse($request->input('from')) : null;
        $to = $request->filled('to') ? Carbon::parse($request->input('to')) : null;

        $ledger = $account
            ? $this->generalLedgerService->forAccount($account, $from, $to)
            : null;

        return $this->page('admin.general-ledger.index', [
            'crumbTitle' => 'General Ledger',
            'crumbSub' => 'All entries reorganized by account',
            'accounts' => $accounts,
            'selectedAccountId' => $accountId,
            'ledger' => $ledger,
            'from' => $request->input('from'),
            'to' => $request->input('to'),
        ]);
    }

    public function export(Request $request, string $format): BinaryFileResponse|\Illuminate\Http\Response
    {
        $validated = $request->validate([
            'account_id' => ['required', 'exists:accounts,id'],
            'from' => ['nullable', 'date'],
            'to' => ['nullable', 'date'],
        ]);

        $account = Account::query()->findOrFail($validated['account_id']);
        $from = isset($validated['from']) ? Carbon::parse($validated['from']) : null;
        $to = isset($validated['to']) ? Carbon::parse($validated['to']) : null;
        $ledger = $this->generalLedgerService->forAccount($account, $from, $to);

        $filename = 'general-ledger-'.$account->code.'-'.now()->format('Y-m-d');

        return match ($format) {
            'csv', 'xlsx' => Excel::download(
                new GeneralLedgerExport($ledger),
                "{$filename}.{$format}",
                $format === 'csv' ? \Maatwebsite\Excel\Excel::CSV : \Maatwebsite\Excel\Excel::XLSX,
            ),
            'pdf' => Pdf::loadView('exports.general-ledger', ['ledger' => $ledger])
                ->download("{$filename}.pdf"),
            default => abort(404),
        };
    }
}
