<?php

namespace App\Http\Controllers;

use App\Models\PurchaseOrder;
use App\Services\PurchaseOrderDocumentPresenter;
use App\Services\PurchaseOrderPdfGenerator;
use Illuminate\Http\Request;

class PublicPurchaseOrderController extends Controller
{
    public function __construct(
        private readonly PurchaseOrderDocumentPresenter $presenter,
        private readonly PurchaseOrderPdfGenerator $pdfGenerator,
    ) {}

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

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

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

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

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

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

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

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

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

        return $purchaseOrder;
    }
}
