<?php

namespace App\Services;

use App\Models\Order;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Barryvdh\DomPDF\Facade\Pdf;

class InvoiceService
{

    /**
     * Generate an invoice PDF for an order
     * 
     * @param Order $order
     * @return string The file path to the stored PDF
     */
    public static function generateInvoice(Order $order): string
    {


        // Create directory structure: invoices/{year}/{month}/
        $year = $order->created_at->year;
        $month = str_pad($order->created_at->month, 2, '0', STR_PAD_LEFT);
        $directory = "invoices/{$year}/{$month}";

        // Ensure directory exists in public disk
        if (!Storage::disk('public')->exists($directory)) {
            Storage::disk('public')->makeDirectory($directory, 0755, true);
        }

        // Verify directory was created
        if (!Storage::disk('public')->exists($directory)) {
            throw new \Exception('Failed to create directory: ' . $directory);
        }

        // Create filename: INV-{order_number}.pdf
        $filename = 'INV-' . $order->order_number . '.pdf';
        $path = "{$directory}/{$filename}";

        try {
            // Generate PDF from blade template with font configuration
            $pdf = Pdf::loadView('invoices.order-invoice', [
    'order' => $order,
]);

            // Get PDF output as string
            $pdfContent = $pdf->output();

            if (empty($pdfContent)) {
                throw new \Exception('PDF generation produced empty output');
            }

            // Store PDF to disk (using public disk)
            $stored = Storage::disk('public')->put($path, $pdfContent);

            if (!$stored) {
                throw new \Exception('Storage::put() returned false for path: ' . $path);
            }

            // Verify file was created
            if (!Storage::disk('public')->exists($path)) {
                throw new \Exception('File does not exist after being stored: ' . $path);
            }

            // Update order with invoice path (include storage prefix for retrieval)
            $order->update(['invoice_path' => 'storage/' . $path]);

            return $path;
        } catch (\Exception $e) {
            Log::error('Invoice generation failed', [
                'order_uuid' => $order->uuid,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);
            throw $e;
        }
    }

    /**
     * Get the full path to an invoice PDF
     * 
     * @param string $invoicePath
     * @return string
     */
    public static function getInvoicePath(string $invoicePath): string
    {
        return Storage::path($invoicePath);
    }

    /**
     * Check if an invoice exists for an order
     * 
     * @param Order $order
     * @return bool
     */
    public static function invoiceExists(Order $order): bool
    {
        return !empty($order->invoice_path) && Storage::disk('public')->exists($order->invoice_path);
    }

    /**
     * Delete an invoice PDF
     * 
     * @param Order $order
     * @return bool
     */
    public static function deleteInvoice(Order $order): bool
    {
        if ($order->invoice_path && Storage::disk('public')->exists($order->invoice_path)) {
            Storage::disk('public')->delete($order->invoice_path);
            $order->update(['invoice_path' => null]);
            return true;
        }
        return false;
    }
}
