<?php

namespace App\Components;

use App\Models\Dsar\Dsar;
use App\Services\HistoryService;
use App\Services\PdfService;
use App\Services\PrintQueueService;
use Illuminate\Support\Facades\Storage;
use Livewire\Component;

class PrintQueueManager extends Component {

    public function mount(): void {
        $this->authorize('print-queue.view');
    }

    public function removeItem(PrintQueueService $service, int $id) {
        $this->authorize('print-queue.manage');
        $service->remove($id);
    }

    public function printAll(PrintQueueService $printQueue, PdfService $pdf, HistoryService $history) {
        $this->authorize('print-queue.manage');
        $items = $printQueue->all();

        $paths = $items->map(function ($item) {
            if ($item->file_path) {
                return $item->file_path;
            }

            return $item->document->owner->getDocumentStoragePath() . $item->document->file_name;
        })->filter()->values()->toArray();

        $outputPath = 'temp/print-queue-' . now()->format('YmdHis') . '.pdf';

        $pdf->merge($paths, $outputPath);

        $printQueue->clear();

        // Mark any DSAR owners with 'needs posting' status as posted
        $items->each(function ($item) use ($history) {
            $owner = $item->owner;
            if ($owner instanceof Dsar && $owner->status === 'needs posting') {
                $owner->update([
                    'status'    => 'sent',
                    'posted_at' => now(),
                ]);
                $history->add($owner, 'DSAR to "' . ($owner->institution?->display_name ?? 'Unknown') . '" marked as posted via print queue', [
                    'institution' => $owner->institution?->display_name,
                    'posted_at'   => now()->toDateTimeString(),
                ]);
            }
        });

        return response()->streamDownload(function () use ($outputPath) {
            echo Storage::get($outputPath);
            Storage::delete($outputPath);
        }, 'print-queue.pdf', ['Content-Type' => 'application/pdf']);
    }

    public function placeholder() {
        return <<<'HTML'
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-body">
                        <div class="placeholder-glow">
                            <span class="placeholder col-12 mb-2"></span>
                            <span class="placeholder col-12 mb-2"></span>
                            <span class="placeholder col-8"></span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        HTML;
    }

    public function render(PrintQueueService $service) {
        $queueItems = $service->all()->map(fn ($item) => [
            'id'        => $item->id,
            'file_path' => $item->file_path,
            'document'  => $item->document ? [
                'display_name' => $item->document->display_name,
                'file_name'    => $item->document->file_name,
                'type'         => $item->document->type ? ['display_name' => $item->document->type->display_name] : null,
                'owner'        => $item->document->owner ? ['display_name' => $item->document->owner->display_name ?? null] : null,
            ] : null,
            'owner'      => $item->owner ? ['display_name' => $item->owner->display_name ?? null] : null,
            'user'       => $item->user ? ['name' => $item->user->name] : null,
            'created_at' => $item->created_at?->format('d M Y H:i'),
        ])->all();

        return view('components.print-queue-manager', compact('queueItems'));
    }
}
