<?php

use App\Models\Order;
use App\Services\InvoiceService;
use App\Services\MailjetService;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\View;

// Test route to generate and view an invoice
// Usage: http://localhost:8000/test-invoice/{order_number}
Route::get('/test-invoice/{orderNumber}', function ($orderNumber) {
    $order = Order::where('order_number', $orderNumber)->first();
    
    if (!$order) {
        return response()->json(['error' => 'Order not found'], 404);
    }
    
    try {
        // Generate invoice
        $invoicePath = InvoiceService::generateInvoice($order);
        
        // Get the full path from public disk
        $fullPath = storage_path('app/public/' . $invoicePath);
        
        Log::info('Invoice test:', [
            'order_number' => $orderNumber,
            'stored_path' => $invoicePath,
            'full_path' => $fullPath,
            'file_exists' => file_exists($fullPath),
        ]);
        
        if (file_exists($fullPath)) {
            return response()->file($fullPath);
        } else {
            return response()->json([
                'error' => 'Invoice file not found',
                'path' => $invoicePath,
                'full_path' => $fullPath,
            ], 500);
        }
    } catch (\Exception $e) {
        Log::error('Invoice test error:', [
            'order_number' => $orderNumber,
            'error' => $e->getMessage(),
            'trace' => $e->getTraceAsString(),
        ]);
        
        return response()->json([
            'error' => 'Failed to generate invoice',
            'message' => $e->getMessage()
        ], 500);
    }
})->name('test-invoice');

// Test route to send an invoice email via Mailjet
// Usage: http://localhost:8000/test-email/{order_number}/{email}
Route::get('/test-email/{orderNumber}/{email}', function ($orderNumber, $email) {
    $order = Order::where('order_number', $orderNumber)->first();
    
    if (!$order) {
        return response()->json(['error' => 'Order not found'], 404);
    }
    
    try {
        // Generate invoice
        $invoicePath = InvoiceService::generateInvoice($order);
        $fullPath = storage_path('app/public/' . $invoicePath);
        
        if (!file_exists($fullPath)) {
            return response()->json([
                'error' => 'Invoice file not found',
                'path' => $invoicePath,
                'full_path' => $fullPath,
            ], 500);
        }
        
        // Send email directly via Mailjet (no queue needed)
        $mailjetService = new MailjetService();
        $customerName = $order->customer_name ?? explode('@', $email)[0];
        
        // Generate basic HTML for email
        $htmlContent = <<<HTML
        <html>
            <head>
                <style>
                    body { font-family: Arial, sans-serif; color: #333; }
                    .header { background-color: #f5f5f5; padding: 20px; text-align: center; }
                    .content { padding: 20px; }
                    .footer { background-color: #f5f5f5; padding: 20px; text-align: center; font-size: 12px; }
                    table { width: 100%; border-collapse: collapse; margin: 20px 0; }
                    th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
                    th { background-color: #f5f5f5; }
                </style>
            </head>
            <body>
                <div class="header">
                    <h1>Invoice #{$order->order_number}</h1>
                </div>
                <div class="content">
                    <p>Dear {$customerName},</p>
                    <p>Please find your invoice attached to this email.</p>
                    <h3>Order Details</h3>
                    <table>
                        <tr>
                            <th>Order Number</th>
                            <td>{$order->order_number}</td>
                        </tr>
                        <tr>
                            <th>Order Date</th>
                            <td>{$order->created_at->format('d M Y')}</td>
                        </tr>
                        <tr>
                            <th>Total Amount</th>
                            <td>R {$order->total}</td>
                        </tr>
                    </table>
                    <p>Thank you for your order!</p>
                </div>
                <div class="footer">
                    <p>&copy; 2025 ADDITIONAL DESIGN. All rights reserved.</p>
                </div>
            </body>
        </html>
        HTML;
        
        $success = $mailjetService->send(
            toEmail: $email,
            toName: $customerName,
            subject: 'Invoice #' . $order->order_number . ' - ADDITIONAL DESIGN',
            htmlContent: $htmlContent,
            attachments: [$fullPath]
        );
        
        if ($success) {
            Log::info('Test email sent successfully via Mailjet', [
                'order_number' => $orderNumber,
                'test_email' => $email,
                'invoice_path' => $invoicePath,
            ]);
            
            return response()->json([
                'success' => true,
                'message' => 'Email sent successfully to ' . $email,
                'order_number' => $orderNumber,
                'test_email' => $email,
                'invoice_path' => $invoicePath,
            ]);
        } else {
            Log::warning('Test email send returned false', [
                'order_number' => $orderNumber,
                'test_email' => $email,
            ]);
            
            return response()->json([
                'success' => false,
                'message' => 'Failed to send email - check logs',
                'order_number' => $orderNumber,
                'test_email' => $email,
            ], 500);
        }
    } catch (\Exception $e) {
        Log::error('Test email error', [
            'order_number' => $orderNumber,
            'email' => $email,
            'error' => $e->getMessage(),
            'trace' => $e->getTraceAsString(),
        ]);
        
        return response()->json([
            'error' => 'Failed to dispatch test email',
            'message' => $e->getMessage()
        ], 500);
    }
})->name('test-email');
