<?php

namespace App\Http\Controllers;

use App\Models\PurchaseBill;
use App\Services\PurchaseBillDocumentPresenter;
use App\Services\PurchaseBillPdfGenerator;
use Illuminate\Http\Request;

class PublicPurchaseBillController extends Controller
{
    public function __construct(
        private readonly PurchaseBillDocumentPresenter $presenter,
        private readonly PurchaseBillPdfGenerator $pdfGenerator,
    ) {}

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

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

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

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

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

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

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

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

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

        return $purchaseBill;
    }
}
