<?php

namespace App\Http\Controllers;

use App\Models\DebitNote;
use App\Services\DebitNoteDocumentPresenter;
use App\Services\DebitNotePdfGenerator;
use Illuminate\Http\Request;

class PublicDebitNoteController extends Controller
{
    public function __construct(
        private readonly DebitNoteDocumentPresenter $presenter,
        private readonly DebitNotePdfGenerator $pdfGenerator,
    ) {}

    public function show(string $token, Request $request)
    {
        $debitNote = $this->resolveByToken($token);
        $data = $this->presenter->displayData($debitNote);
        $copies = $data['documentCopies'];
        $copyKey = $request->query('copy', 'original');
        $data['documentCopyLabel'] = $copies[$copyKey] ?? $copies['original'] ?? 'Original Copy';
        $data['forPublic'] = true;
        $data['shareToken'] = $token;

        return view('public.debit-notes.show', $data);
    }

    public function pdf(string $token, Request $request)
    {
        $debitNote = $this->resolveByToken($token);
        $data = $this->presenter->displayData($debitNote);
        $copies = $data['documentCopies'];
        $copyKey = $request->query('copy', 'original');
        $copyLabel = $copies[$copyKey] ?? $copies['original'] ?? 'Original Copy';

        if ($request->boolean('inline')) {
            return $this->pdfGenerator->stream($debitNote, $data, $copyLabel);
        }

        return $this->pdfGenerator->download($debitNote, $data, $copyLabel);
    }

    public function print(string $token, Request $request)
    {
        $debitNote = $this->resolveByToken($token);
        $copyKey = $request->query('copy', 'original');

        return view('admin.debit-notes.print-pdf', [
            'debitNote' => $debitNote,
            'copyKey' => $copyKey,
            'autoprint' => $request->boolean('autoprint', true),
            'backUrl' => route('public.debit-notes.show', $token),
            'pdfUrl' => route('public.debit-notes.pdf', [
                'token' => $token,
                'copy' => $copyKey,
                'inline' => 1,
            ]),
        ]);
    }

    private function resolveByToken(string $token): DebitNote
    {
        $debitNote = DebitNote::with(['items', 'customer', 'vendor', 'invoice', 'purchaseBill'])
            ->where('share_token', $token)
            ->first();

        if (! $debitNote) {
            abort(404, 'This debit note link is invalid or has expired.');
        }

        if ($debitNote->status === 'draft') {
            abort(404, 'This debit note is not available for viewing.');
        }

        return $debitNote;
    }
}
