<?php

namespace App\Controllers;

use App\Models\FolioLineItemModel;
use App\Models\FolioModel;
use App\Models\FolioPaymentModel;
use App\Models\GuestModel;

class InvoiceController extends BaseController
{
    /**
     * Itemized PDF invoice for one folio, branded with the tenant's logo/
     * colors (from the control DB — see TenantRecordModel). Available to
     * front desk from the folio page regardless of whether the folio is
     * still open or already closed.
     */
    public function folioInvoice(int $folioId)
    {
        $pdf = $this->renderFolioInvoicePdf($folioId);

        if ($pdf === null) {
            return redirect()->to('/')->with('error', 'Folio not found.');
        }

        $this->logActivity('folio', "Generated invoice PDF for folio #{$folioId}.");

        return $this->response
            ->setHeader('Content-Type', 'application/pdf')
            ->setHeader('Content-Disposition', "inline; filename=\"invoice-folio-{$folioId}.pdf\"")
            ->setBody($pdf);
    }

    /**
     * Same PDF bytes folioInvoice() streams inline — factored out so
     * FolioController::emailInvoice() can attach the exact same document
     * instead of re-rendering a second, potentially-drifting copy.
     */
    public function renderFolioInvoicePdf(int $folioId): ?string
    {
        $folios = new FolioModel();
        $folio  = $folios->find($folioId);

        if ($folio === null) {
            return null;
        }

        $guest     = (new GuestModel())->find($folio->guest_id);
        $lineItems = (new FolioLineItemModel())->forFolio($folioId);
        $payments  = (new FolioPaymentModel())->forFolio($folioId);
        $tenant    = service('tenantContext')->getTenant();

        $html = view('invoices/folio_invoice', [
            'folio'     => $folio,
            'guest'     => $guest,
            'lineItems' => $lineItems,
            'payments'  => $payments,
            'total'     => $folios->totalCharges($folioId),
            'paid'      => $folios->totalPaid($folioId),
            'balance'   => $folios->balanceDue($folioId),
            'tenant'    => $tenant,
            'issuedAt'  => date('Y-m-d H:i'),
        ]);

        return service('pdfService')->renderHtml($html);
    }
}
