<?php

namespace App\Services;

use App\Models\Order;
use App\Models\OrderPdf;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Support\Facades\Storage;
use Carbon\Carbon;

class PDFService
{
    /**
     * Generate PDF for order.
     */
    public function generateOrderPDF(Order $order): OrderPdf
    {
        $order->load(['items.product.brand']);

        // Generate filename
        $filename = 'order_' . $order->id . '_' . Carbon::now()->format('Y-m-d_His') . '.pdf';
        $filepath = 'orders/' . $filename;

        // Group items by brand for better presentation
        $itemsByBrand = $order->items->groupBy(function ($item) {
            return $item->getProductDetails()['brand_name'];
        });

        // Generate PDF
        $pdf = Pdf::loadView('pdf.order', [
            'order' => $order,
            'items' => $order->items,
            'itemsByBrand' => $itemsByBrand,
        ]);

        // Save PDF to storage
        $pdfContent = $pdf->output();
        Storage::put($filepath, $pdfContent);

        // Get file size
        $fileSize = Storage::size($filepath);

        // Delete old PDF if exists
        if ($order->pdf) {
            $order->pdf->delete();
        }

        // Create or update OrderPdf record
        $orderPdf = OrderPdf::create([
            'order_id' => $order->id,
            'file_path' => $filepath,
            'file_name' => $filename,
            'file_size' => $fileSize,
            'mime_type' => 'application/pdf',
            'expires_at' => Carbon::now()->addDays(30), // PDF expires in 30 days
        ]);

        return $orderPdf;
    }

    /**
     * Generate temporary PDF for download (not saved to database).
     */
    public function generateTempPDF(Order $order): string
    {
        $order->load(['items.product.brand']);

        $itemsByBrand = $order->items->groupBy(function ($item) {
            return $item->getProductDetails()['brand_name'];
        });

        $pdf = Pdf::loadView('pdf.order', [
            'order' => $order,
            'items' => $order->items,
            'itemsByBrand' => $itemsByBrand,
        ]);

        return $pdf->output();
    }

    /**
     * Cleanup expired PDFs.
     */
    public function cleanupExpiredPDFs(): int
    {
        $expiredPdfs = OrderPdf::expired()->get();
        $count = 0;

        foreach ($expiredPdfs as $pdf) {
            $pdf->delete(); // Will also delete file via model boot method
            $count++;
        }

        return $count;
    }

    /**
     * Get PDF download response.
     */
    public function downloadPDF(OrderPdf $orderPdf): \Symfony\Component\HttpFoundation\StreamedResponse
    {
        return Storage::download($orderPdf->file_path, $orderPdf->file_name);
    }
}
