<?php

namespace App\Http\Controllers;

use App\Models\Quotation;
use App\Services\QuotationDocumentPresenter;
use App\Services\QuotationPdfGenerator;
use Illuminate\Http\Request;

class PublicQuotationController extends Controller
{
    public function __construct(
        private readonly QuotationDocumentPresenter $presenter,
        private readonly QuotationPdfGenerator $pdfGenerator,
    ) {}

    public function show(string $token, Request $request)
    {
        $quotation = $this->resolveByToken($token);
        $data = $this->presenter->displayData($quotation);
        $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.quotations.show', $data);
    }

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

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

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

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

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

    private function resolveByToken(string $token): Quotation
    {
        $quotation = Quotation::with(['items', 'customer'])
            ->where('share_token', $token)
            ->first();

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

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

        return $quotation;
    }
}
