<?php

namespace App\Http\Controllers\Admin\Finance;

use App\Http\Controllers\Admin\PageController;
use App\Http\Requests\Finance\StoreReceiptRequest;
use App\Models\Account;
use App\Models\Invoice;
use App\Models\Receipt;
use App\Models\Student;
use App\Services\Finance\ReceiptService;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Response;
use Illuminate\View\View;

class ReceiptController extends PageController
{
    public function __construct(
        private readonly ReceiptService $receiptService,
    ) {}

    public function index(): View
    {
        $receipts = Receipt::query()
            ->with(['student', 'receivedBy'])
            ->latest('payment_date')
            ->paginate(20);

        return $this->page('admin.receipts.index', [
            'crumbTitle' => 'Receipts',
            'crumbSub' => 'Issue, store & re-send receipts',
            'receipts' => $receipts,
        ]);
    }

    public function create(): View
    {
        return $this->page('admin.receipts.create', [
            'crumbTitle' => 'Receipts',
            'crumbSub' => 'Record payment against invoice',
            'students' => Student::query()->orderBy('first_name')->get(),
            'invoices' => Invoice::query()
                ->where('balance_due', '>', 0)
                ->with('student')
                ->latest('issue_date')
                ->get(),
            'cashAccounts' => Account::query()
                ->where('code', 'like', '100%')
                ->orderBy('code')
                ->get(),
        ]);
    }

    public function store(StoreReceiptRequest $request): RedirectResponse
    {
        $validated = $request->validated();
        $invoice = Invoice::query()->findOrFail($validated['invoice_id']);

        try {
            $receipt = $this->receiptService->createAgainstInvoice($validated, $invoice);
        } catch (\Throwable $e) {
            return back()->withInput()->with('error', $e->getMessage());
        }

        return $this->redirectWithSuccess(
            'finance.receipts.index',
            "Receipt {$receipt->receipt_number} posted and allocated to invoice {$invoice->invoice_number}."
        );
    }

    public function pdf(Receipt $receipt): Response
    {
        $receipt->load(['student', 'account', 'receivedBy', 'paymentAllocations.invoice']);

        return Pdf::loadView('exports.receipt', [
            'receipt' => $receipt,
            'schoolName' => config('southend.app_name'),
        ])->download("receipt-{$receipt->receipt_number}.pdf");
    }
}
