<?php

namespace App\Http\Controllers;

use App\Models\DeliveryChallan;
use App\Services\DeliveryChallanDocumentPresenter;
use App\Services\DeliveryChallanPdfGenerator;
use Illuminate\Http\Request;

class PublicDeliveryChallanController extends Controller
{
    public function __construct(
        private readonly DeliveryChallanDocumentPresenter $presenter,
        private readonly DeliveryChallanPdfGenerator $pdfGenerator,
    ) {}

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

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

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

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

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

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

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

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

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

        return $challan;
    }
}
