<?php

namespace App\Http\Controllers;

use App\Services\InvoicePdfService;
use App\Modules\Invoices\Invoice;
use App\Modules\Invoices\Sale;
use Illuminate\Support\Facades\Log;

class GenerateInvoicePdfController extends BaseController
{
    /**
     * Generate PDF for invoice or sale
     * Works with both invoice IDs and invoice numbers
     *
     * @param int $id Invoice ID, invoice number, or sale ID
     * @return \Illuminate\Http\Response PDF response
     */
    public function generate($id)
    {
        try {
            // Try by ID first (to match invoice detail page behavior)
            $invoice = Sale::find($id);
            if (!$invoice) {
                $invoice = Invoice::find($id);
            }
            if (!$invoice) {
                // Try to find the invoice by invoice_number as fallback
                $invoice = Sale::where('invoice_number', $id)->first();
                if (!$invoice) {
                    $invoice = Invoice::where('invoice_number', $id)->first();
                }
            }
            
            if (!$invoice) {
                return response()->json(['error' => 'Invoice not found'], 404);
            }
            
            $pdfService = new InvoicePdfService();
            
            // Generate and stream the PDF directly
            return $pdfService->generatePdf($invoice, false);
            
        } catch (\Exception $e) {
            Log::error('PDF generation error for invoice ' . $id . ': ' . $e->getMessage(), [
                'exception' => $e,
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'trace' => $e->getTraceAsString()
            ]);
            return response()->json([
                'error' => 'Failed to generate PDF', 
                'details' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine()
            ], 500);
        }
    }
    
    /**
     * Legacy compatibility method for existing KashFlow API calls
     * Returns PDF URL for JavaScript compatibility
     *
     * @param int $id Invoice number or ID
     * @return \Illuminate\Http\Response
     */
    public function getPrintInvoice($id)
    {
        try {
            // Try by ID first (to match invoice detail page behavior)
            $invoice = Sale::find($id);
            if (!$invoice) {
                $invoice = Invoice::find($id);
            }
            if (!$invoice) {
                // Try to find the invoice by invoice_number as fallback
                $invoice = Sale::where('invoice_number', $id)->first();
                if (!$invoice) {
                    $invoice = Invoice::where('invoice_number', $id)->first();
                }
            }
            
            if (!$invoice) {
                return response()->json(['error' => 'Invoice not found'], 404);
            }
            
            // Return the new PDF generation URL
            $pdfUrl = url('generate-invoice/' . ($invoice->invoice_number ?? $invoice->id));
            
            // Return the URL as a plain string for compatibility with existing JS
            return response($pdfUrl, 200)
                ->header('Content-Type', 'text/plain');
            
        } catch (\Exception $e) {
            Log::error('Legacy KashFlow PDF route error: ' . $e->getMessage());
            return response()->json(['error' => 'Failed to generate PDF'], 500);
        }
    }
}