<?php

namespace App\Http\Controllers;

use App\Models\Setting;
use App\Models\Business;
use Illuminate\Http\Request;

class SettingsController extends Controller
{
    /**
     * Display the settings edit form.
     */
    public function edit()
    {
        $businessId = Business::currentId();

        $templates = ['classic', 'elegant', 'slim'];
        $baseSettings = [
            'invoice_header_type' => 'standard',
            'invoice_show_letterhead' => '1',
            'invoice_show_footer_image' => '0',
            'invoice_show_watermark' => '0',
            'invoice_watermark_text' => 'DRAFT',
            'invoice_watermark_type' => 'text',
            'invoice_title_label' => 'Sales Tax Invoice',
            'field_hs_code_show' => '1',
            'field_hs_code_label' => 'HS Code',
            'field_qty_show' => '1',
            'field_qty_label' => 'Qty',
            'field_uom_show' => '1',
            'field_uom_label' => 'Unit',
            'field_rate_show' => '1',
            'field_rate_label' => 'Rate',
            'field_taxable_amt_show' => '1',
            'field_taxable_amt_label' => 'Taxable Amt',
            'field_sales_tax_show' => '1',
            'field_sales_tax_label' => 'Sales Tax',
            'field_total_show' => '1',
            'field_total_label' => 'Total',
        ];

        // Load Business settings
        $businessSettings = [
            'currency_precision' => Setting::get('currency_precision', '2', $businessId),
            'quantity_precision' => Setting::get('quantity_precision', '2', $businessId),
            'timezone' => Setting::get('timezone', 'Asia/Karachi', $businessId),
            'show_symbol_rs' => Setting::get('show_symbol_rs', '1', $businessId),
            'invoice_prefix' => Setting::get('invoice_prefix', 'INV-', $businessId),

            // Layout & Branding Preferences
            'invoice_layout_template' => Setting::get('invoice_layout_template', 'classic', $businessId),
            'invoice_logo_url' => Setting::get('invoice_logo_url', '', $businessId),
            'invoice_letterhead_image_url' => Setting::get('invoice_letterhead_image_url', '', $businessId),
            'invoice_footer_image_url' => Setting::get('invoice_footer_image_url', '', $businessId),
            'invoice_watermark_image_url' => Setting::get('invoice_watermark_image_url', '', $businessId),
        ];

        // Load global default values first
        foreach ($baseSettings as $key => $default) {
            $businessSettings[$key] = Setting::get($key, $default, $businessId);
        }

        // Load overrides for each template
        foreach ($templates as $t) {
            foreach ($baseSettings as $key => $default) {
                $fullKey = $t . '_' . $key;
                // Default value is the global setting's current value
                $businessSettings[$fullKey] = Setting::get($fullKey, $businessSettings[$key], $businessId);
            }
        }

        // Load SMTP settings (Global)
        $smtpSettings = [
            'mail_host' => Setting::get('mail_host', '', null),
            'mail_port' => Setting::get('mail_port', '587', null),
            'mail_username' => Setting::get('mail_username', '', null),
            'mail_password' => Setting::get('mail_password', '', null),
            'mail_encryption' => Setting::get('mail_encryption', 'tls', null),
            'mail_from_address' => Setting::get('mail_from_address', '', null),
            'mail_from_name' => Setting::get('mail_from_name', '', null),
        ];

        $lastCronRun = Setting::get('last_cron_run_at', null, null);

        return view('settings.edit', compact('businessSettings', 'smtpSettings', 'lastCronRun'));
    }

    /**
     * Update the settings in storage.
     */
    public function update(Request $request)
    {
        $businessId = Business::currentId();

        // NOTE: invoice_header_type / field_* / per-template (classic_/elegant_/slim_)
        // rules were removed from here — those belong to templateUpdate() only.
        // settings.edit form doesn't submit those fields at all.
        $rules = [
            'currency_precision' => 'required|integer|min:0|max:4',
            'quantity_precision' => 'required|integer|min:0|max:4',
            'timezone' => 'required|string',
            'show_symbol_rs' => 'required|boolean',
            'invoice_prefix' => 'nullable|string|max:10',
            'invoice_layout_template' => 'nullable|string|in:classic,elegant,slim',

            // Images/Logos
            'invoice_logo' => 'nullable|image|max:2048',
            'invoice_letterhead_image' => 'nullable|image|max:2048',
            'invoice_footer_image' => 'nullable|image|max:2048',
            'invoice_watermark_image' => 'nullable|image|max:4048',
        ];

        $businessData = $request->validate($rules);

        // Handle File Uploads
        if ($request->hasFile('invoice_logo')) {
            $path = $request->file('invoice_logo')->store('logos', 'public');
            Setting::set('invoice_logo_url', '/storage/' . $path, $businessId);
        }
        if ($request->hasFile('invoice_letterhead_image')) {
            $path = $request->file('invoice_letterhead_image')->store('letterheads', 'public');
            Setting::set('invoice_letterhead_image_url', '/storage/' . $path, $businessId);
        }
        if ($request->hasFile('invoice_footer_image')) {
            $path = $request->file('invoice_footer_image')->store('footers', 'public');
            Setting::set('invoice_footer_image_url', '/storage/' . $path, $businessId);
        }
        if ($request->hasFile('invoice_watermark_image')) {
            $path = $request->file('invoice_watermark_image')->store('watermarks', 'public');
            Setting::set('invoice_watermark_image_url', '/storage/' . $path, $businessId);
        }

        // Remove uploads from validation data array before saving loop
        unset($businessData['invoice_logo']);
        unset($businessData['invoice_letterhead_image']);
        unset($businessData['invoice_footer_image']);
        unset($businessData['invoice_watermark_image']);

        foreach ($businessData as $key => $value) {
            Setting::set($key, $value, $businessId);
        }

        // 2. Update SMTP Settings (Global)
        $smtpData = $request->validate([
            'mail_host' => 'nullable|string',
            'mail_port' => 'nullable|string|max:10',
            'mail_username' => 'nullable|string',
            'mail_password' => 'nullable|string',
            'mail_encryption' => 'nullable|string|max:10',
            'mail_from_address' => 'nullable|email',
            'mail_from_name' => 'nullable|string',
        ]);

        foreach ($smtpData as $key => $value) {
            Setting::set($key, $value ?? '', null);
        }

        // Proactively update mail configuration in-memory
        config([
            'mail.mailers.smtp.host' => $smtpData['mail_host'] ?? config('mail.mailers.smtp.host'),
            'mail.mailers.smtp.port' => $smtpData['mail_port'] ?? config('mail.mailers.smtp.port'),
            'mail.mailers.smtp.username' => $smtpData['mail_username'] ?? config('mail.mailers.smtp.username'),
            'mail.mailers.smtp.password' => $smtpData['mail_password'] ?? config('mail.mailers.smtp.password'),
            'mail.mailers.smtp.encryption' => $smtpData['mail_encryption'] ?? config('mail.mailers.smtp.encryption'),
            'mail.from.address' => $smtpData['mail_from_address'] ?? config('mail.from.address'),
            'mail.from.name' => $smtpData['mail_from_name'] ?? config('mail.from.name'),
        ]);

        return redirect()->route('settings.edit')->with('success', 'Settings updated successfully!');
    }

    /**
     * Display templates index gallery grid.
     */
    public function templatesIndex()
    {
        $businessId = Business::currentId();
        $defaultTemplate = Setting::get('invoice_layout_template', 'classic', $businessId);

        return view('settings.templates.index', compact('defaultTemplate'));
    }

    /**
     * Display customize screen for a single template.
     */
    public function templateEdit(string $template)
    {
        if (!in_array($template, ['classic', 'elegant', 'slim'])) {
            abort(404);
        }

        $businessId = Business::currentId();

        $baseSettings = [
            'invoice_header_type' => 'standard',
            'invoice_show_letterhead' => '1',
            'invoice_show_footer_image' => '0',
            'invoice_show_watermark' => '0',
            'invoice_watermark_text' => 'DRAFT',
            'invoice_watermark_type' => 'text',
            'invoice_title_label' => 'Sales Tax Invoice',
            'field_hs_code_show' => '1',
            'field_hs_code_label' => 'HS Code',
            'field_qty_show' => '1',
            'field_qty_label' => 'Qty',
            'field_uom_show' => '1',
            'field_uom_label' => 'Unit',
            'field_rate_show' => '1',
            'field_rate_label' => 'Rate',
            'field_taxable_amt_show' => '1',
            'field_taxable_amt_label' => 'Taxable Amt',
            'field_sales_tax_show' => '1',
            'field_sales_tax_label' => 'Sales Tax',
            'field_total_show' => '1',
            'field_total_label' => 'Total',
        ];

        $templateSettings = [];
        foreach ($baseSettings as $key => $default) {
            $fullKey = $template . '_' . $key;
            $globalVal = Setting::get($key, $default, $businessId);
            $templateSettings[$key] = Setting::get($fullKey, $globalVal, $businessId);
        }

        $businessSettings = [
            'invoice_logo_url' => Setting::get($template . '_invoice_logo_url', Setting::get('invoice_logo_url', '', $businessId), $businessId),
            'invoice_letterhead_image_url' => Setting::get($template . '_invoice_letterhead_image_url', Setting::get('invoice_letterhead_image_url', '', $businessId), $businessId),
            'invoice_footer_image_url' => Setting::get($template . '_invoice_footer_image_url', Setting::get('invoice_footer_image_url', '', $businessId), $businessId),
            'invoice_watermark_image_url' => Setting::get($template . '_invoice_watermark_image_url', Setting::get('invoice_watermark_image_url', '', $businessId), $businessId),
        ];

        return view('settings.templates.edit', compact('template', 'templateSettings', 'businessSettings'));
    }

    /**
     * Update configuration settings for a single template.
     */
    public function templateUpdate(Request $request, string $template)
    {
        if (!in_array($template, ['classic', 'elegant', 'slim'])) {
            abort(404);
        }

        $businessId = Business::currentId();

        $rules = [
            'invoice_header_type' => 'required|string|in:standard,letterhead_image',
            'invoice_show_letterhead' => 'required|boolean',
            'invoice_show_footer_image' => 'required|boolean',
            'invoice_show_watermark' => 'required|boolean',
            'invoice_watermark_text' => 'nullable|string|max:20',
            'invoice_watermark_type' => 'required|string|in:text,image',
            'invoice_title_label' => 'nullable|string|max:50',

            'field_hs_code_show' => 'required|boolean',
            'field_hs_code_label' => 'required|string|max:30',
            'field_qty_show' => 'required|boolean',
            'field_qty_label' => 'required|string|max:30',
            'field_uom_show' => 'required|boolean',
            'field_uom_label' => 'required|string|max:30',
            'field_rate_show' => 'required|boolean',
            'field_rate_label' => 'required|string|max:30',
            'field_taxable_amt_show' => 'required|boolean',
            'field_taxable_amt_label' => 'required|string|max:30',
            'field_sales_tax_show' => 'required|boolean',
            'field_sales_tax_label' => 'required|string|max:30',
            'field_total_show' => 'required|boolean',
            'field_total_label' => 'required|string|max:30',

            'invoice_logo' => 'nullable|image|max:2048',
            'invoice_letterhead_image' => 'nullable|image|max:2048',
            'invoice_footer_image' => 'nullable|image|max:2048',
            'invoice_watermark_image' => 'nullable|image|max:4048',
        ];

        $data = $request->validate($rules);

        // Handle File Uploads (prefixed by template key for separation)
        if ($request->hasFile('invoice_logo')) {
            $path = $request->file('invoice_logo')->store('logos', 'public');
            Setting::set($template . '_invoice_logo_url', '/storage/' . $path, $businessId);
        }
        if ($request->hasFile('invoice_letterhead_image')) {
            $path = $request->file('invoice_letterhead_image')->store('letterheads', 'public');
            Setting::set($template . '_invoice_letterhead_image_url', '/storage/' . $path, $businessId);
        }
        if ($request->hasFile('invoice_footer_image')) {
            $path = $request->file('invoice_footer_image')->store('footers', 'public');
            Setting::set($template . '_invoice_footer_image_url', '/storage/' . $path, $businessId);
        }
        if ($request->hasFile('invoice_watermark_image')) {
            $path = $request->file('invoice_watermark_image')->store('watermarks', 'public');
            Setting::set($template . '_invoice_watermark_image_url', '/storage/' . $path, $businessId);
        }

        unset($data['invoice_logo'], $data['invoice_letterhead_image'], $data['invoice_footer_image'], $data['invoice_watermark_image']);

        foreach ($data as $key => $value) {
            Setting::set($template . '_' . $key, $value, $businessId);
        }

        return redirect()->route('settings.templates.index')->with('success', ucfirst($template) . ' Template layout updated successfully!');
    }

    /**
     * Mark a single template layout as global default.
     */
    public function templateSetDefault(string $template)
    {
        if (!in_array($template, ['classic', 'elegant', 'slim'])) {
            abort(404);
        }

        $businessId = Business::currentId();
        Setting::set('invoice_layout_template', $template, $businessId);

        return redirect()->route('settings.templates.index')->with('success', ucfirst($template) . ' Template set as default layout!');
    }


    public function preview(string $template)
    {
        if (!in_array($template, ['classic', 'elegant', 'slim'])) {
            abort(404);
        }

        $businessId = \App\Models\Business::currentId();
        $invoice = \App\Models\Invoice::where('business_id', $businessId)
            ->with(['customer', 'items.item', 'business'])
            ->latest()
            ->first();

        // Fallback to any invoice if none in current business
        if (!$invoice) {
            $invoice = \App\Models\Invoice::with(['customer', 'items.item', 'business'])->latest()->first();
        }

        if (!$invoice) {
            return response('No invoice found to generate preview. Please create at least one invoice first.', 400);
        }

        $layoutData = \App\Helpers\InvoicePdfHelper::getLayoutData($invoice);

        // Force the previewed template layout
        $layoutData['template'] = $template;
        $layoutData['headerType'] = \App\Helpers\InvoicePdfHelper::getTemplateSetting('invoice_header_type', 'standard', $businessId, $template);
        $layoutData['showLetterhead'] = (bool) \App\Helpers\InvoicePdfHelper::getTemplateSetting('invoice_show_letterhead', '1', $businessId, $template);
        $layoutData['showFooterImage'] = (bool) \App\Helpers\InvoicePdfHelper::getTemplateSetting('invoice_show_footer_image', '0', $businessId, $template);
        $layoutData['showWatermark'] = (bool) \App\Helpers\InvoicePdfHelper::getTemplateSetting('invoice_show_watermark', '0', $businessId, $template);
        $layoutData['watermarkText'] = \App\Helpers\InvoicePdfHelper::getTemplateSetting('invoice_watermark_text', 'DRAFT', $businessId, $template);
        $layoutData['watermarkType'] = \App\Helpers\InvoicePdfHelper::getTemplateSetting('invoice_watermark_type', 'text', $businessId, $template);
        $layoutData['titleLabel'] = \App\Helpers\InvoicePdfHelper::getTemplateSetting('invoice_title_label', 'Sales Tax Invoice', $businessId, $template);

        $logoUrl = Setting::get('invoice_logo_url', '', $businessId);
        $letterheadUrl = Setting::get('invoice_letterhead_image_url', '', $businessId);
        $footerUrl = Setting::get('invoice_footer_image_url', '', $businessId);
        $watermarkUrl = Setting::get('invoice_watermark_image_url', '', $businessId);
        $layoutData['businessLogoSrc'] = \App\Helpers\InvoicePdfHelper::getBase64Image($logoUrl);
        $layoutData['letterheadImgSrc'] = \App\Helpers\InvoicePdfHelper::getBase64Image($letterheadUrl);
        $layoutData['footerImgSrc'] = \App\Helpers\InvoicePdfHelper::getBase64Image($footerUrl);
        $layoutData['watermarkImgSrc'] = \App\Helpers\InvoicePdfHelper::getBase64Image($watermarkUrl) ?: \App\Helpers\InvoicePdfHelper::getBase64Image($logoUrl);

        $layoutData['columns'] = [
            'hs' => [
                'show' => (bool) \App\Helpers\InvoicePdfHelper::getTemplateSetting('field_hs_code_show', '1', $businessId, $template),
                'label' => \App\Helpers\InvoicePdfHelper::getTemplateSetting('field_hs_code_label', 'HS Code', $businessId, $template),
            ],
            'qty' => [
                'show' => (bool) \App\Helpers\InvoicePdfHelper::getTemplateSetting('field_qty_show', '1', $businessId, $template),
                'label' => \App\Helpers\InvoicePdfHelper::getTemplateSetting('field_qty_label', 'Qty', $businessId, $template),
            ],
            'uom' => [
                'show' => (bool) \App\Helpers\InvoicePdfHelper::getTemplateSetting('field_uom_show', '1', $businessId, $template),
                'label' => \App\Helpers\InvoicePdfHelper::getTemplateSetting('field_uom_label', 'Unit', $businessId, $template),
            ],
            'rate' => [
                'show' => (bool) \App\Helpers\InvoicePdfHelper::getTemplateSetting('field_rate_show', '1', $businessId, $template),
                'label' => \App\Helpers\InvoicePdfHelper::getTemplateSetting('field_rate_label', 'Rate', $businessId, $template),
            ],
            'taxable' => [
                'show' => (bool) \App\Helpers\InvoicePdfHelper::getTemplateSetting('field_taxable_amt_show', '1', $businessId, $template),
                'label' => \App\Helpers\InvoicePdfHelper::getTemplateSetting('field_taxable_amt_label', 'Taxable Amt', $businessId, $template),
            ],
            'tax' => [
                'show' => (bool) \App\Helpers\InvoicePdfHelper::getTemplateSetting('field_sales_tax_show', '1', $businessId, $template),
                'label' => \App\Helpers\InvoicePdfHelper::getTemplateSetting('field_sales_tax_label', 'Sales Tax', $businessId, $template),
            ],
            'total' => [
                'show' => (bool) \App\Helpers\InvoicePdfHelper::getTemplateSetting('field_total_show', '1', $businessId, $template),
                'label' => \App\Helpers\InvoicePdfHelper::getTemplateSetting('field_total_label', 'Total', $businessId, $template),
            ]
        ];

        $currencyPrecision = $layoutData['currencyPrecision'];
        $quantityPrecision = $layoutData['quantityPrecision'];
        $layoutData['formatted']['items'] = $invoice->items->map(function ($item) use ($currencyPrecision, $quantityPrecision) {
            return [
                'id' => $item->id,
                'sku' => $item->item->sku ?? ('SKU-' . $item->id),
                'product_description' => $item->product_description,
                'hs_code' => $item->hs_code,
                'uom' => $item->uom,
                'quantity' => number_format($item->quantity, $quantityPrecision),
                'rate' => $item->rate,
                'unit_price' => number_format((float) $item->value_sales_excluding_st, $currencyPrecision),
                'value_sales_excluding_st' => number_format($item->value_sales_excluding_st * (float) $item->quantity, $currencyPrecision),
                'sales_tax_applicable' => number_format($item->sales_tax_applicable, $currencyPrecision),
                'total_values' => number_format($item->total_values, $currencyPrecision),
            ];
        })->toArray();

        $html = view('invoices.invoice_pdf', [
            'invoice' => $invoice,
            'layoutData' => $layoutData,
            'invoices' => collect([$invoice]),
            'invoicesLayoutData' => [$invoice->id => $layoutData]
        ])->render();

        $pdf = \App\Helpers\InvoicePdfHelper::makeBrowsershot($html)
            ->format('A4')
            ->showBackground()
            ->margins(0, 0, 0, 0)
            ->pdf();

        return response($pdf, 200, [
            'Content-Type' => 'application/pdf',
            'Content-Disposition' => "inline; filename=\"preview-{$template}.pdf\"",
        ]);
    }


    /**
     * Generate a lightweight image thumbnail of the invoice preview (first page look)
     * Cached per template so it doesn't regenerate on every page load.
     */
    public function previewThumbnail(string $template)
    {
        if (!in_array($template, ['classic', 'elegant', 'slim'])) {
            abort(404);
        }

        $businessId = \App\Models\Business::currentId();
        $cacheKey = "invoice_preview_thumb_{$businessId}_{$template}";

        $image = \Illuminate\Support\Facades\Cache::remember($cacheKey, now()->addMinutes(30), function () use ($template, $businessId) {
            $invoice = \App\Models\Invoice::where('business_id', $businessId)
                ->with(['customer', 'items.item', 'business'])
                ->latest()
                ->first();

            if (!$invoice) {
                $invoice = \App\Models\Invoice::with(['customer', 'items.item', 'business'])->latest()->first();
            }

            if (!$invoice) {
                return null;
            }

            $layoutData = \App\Helpers\InvoicePdfHelper::getLayoutData($invoice);
            $layoutData['template'] = $template;
            $layoutData['headerType'] = \App\Helpers\InvoicePdfHelper::getTemplateSetting('invoice_header_type', 'standard', $businessId, $template);
            $layoutData['showLetterhead'] = (bool) \App\Helpers\InvoicePdfHelper::getTemplateSetting('invoice_show_letterhead', '1', $businessId, $template);
            $layoutData['showFooterImage'] = (bool) \App\Helpers\InvoicePdfHelper::getTemplateSetting('invoice_show_footer_image', '0', $businessId, $template);
            $layoutData['showWatermark'] = (bool) \App\Helpers\InvoicePdfHelper::getTemplateSetting('invoice_show_watermark', '0', $businessId, $template);
            $layoutData['watermarkText'] = \App\Helpers\InvoicePdfHelper::getTemplateSetting('invoice_watermark_text', 'DRAFT', $businessId, $template);
            $layoutData['watermarkType'] = \App\Helpers\InvoicePdfHelper::getTemplateSetting('invoice_watermark_type', 'text', $businessId, $template);
            $layoutData['titleLabel'] = \App\Helpers\InvoicePdfHelper::getTemplateSetting('invoice_title_label', 'Sales Tax Invoice', $businessId, $template);

            $logoUrl = Setting::get('invoice_logo_url', '', $businessId);
            $letterheadUrl = Setting::get('invoice_letterhead_image_url', '', $businessId);
            $footerUrl = Setting::get('invoice_footer_image_url', '', $businessId);
            $watermarkUrl = Setting::get('invoice_watermark_image_url', '', $businessId);
            $layoutData['businessLogoSrc'] = \App\Helpers\InvoicePdfHelper::getBase64Image($logoUrl);
            $layoutData['letterheadImgSrc'] = \App\Helpers\InvoicePdfHelper::getBase64Image($letterheadUrl);
            $layoutData['footerImgSrc'] = \App\Helpers\InvoicePdfHelper::getBase64Image($footerUrl);
            $layoutData['watermarkImgSrc'] = \App\Helpers\InvoicePdfHelper::getBase64Image($watermarkUrl) ?: \App\Helpers\InvoicePdfHelper::getBase64Image($logoUrl);

            $layoutData['columns'] = [
                'hs' => ['show' => (bool) \App\Helpers\InvoicePdfHelper::getTemplateSetting('field_hs_code_show', '1', $businessId, $template), 'label' => \App\Helpers\InvoicePdfHelper::getTemplateSetting('field_hs_code_label', 'HS Code', $businessId, $template)],
                'qty' => ['show' => (bool) \App\Helpers\InvoicePdfHelper::getTemplateSetting('field_qty_show', '1', $businessId, $template), 'label' => \App\Helpers\InvoicePdfHelper::getTemplateSetting('field_qty_label', 'Qty', $businessId, $template)],
                'uom' => ['show' => (bool) \App\Helpers\InvoicePdfHelper::getTemplateSetting('field_uom_show', '1', $businessId, $template), 'label' => \App\Helpers\InvoicePdfHelper::getTemplateSetting('field_uom_label', 'Unit', $businessId, $template)],
                'rate' => ['show' => (bool) \App\Helpers\InvoicePdfHelper::getTemplateSetting('field_rate_show', '1', $businessId, $template), 'label' => \App\Helpers\InvoicePdfHelper::getTemplateSetting('field_rate_label', 'Rate', $businessId, $template)],
                'taxable' => ['show' => (bool) \App\Helpers\InvoicePdfHelper::getTemplateSetting('field_taxable_amt_show', '1', $businessId, $template), 'label' => \App\Helpers\InvoicePdfHelper::getTemplateSetting('field_taxable_amt_label', 'Taxable Amt', $businessId, $template)],
                'tax' => ['show' => (bool) \App\Helpers\InvoicePdfHelper::getTemplateSetting('field_sales_tax_show', '1', $businessId, $template), 'label' => \App\Helpers\InvoicePdfHelper::getTemplateSetting('field_sales_tax_label', 'Sales Tax', $businessId, $template)],
                'total' => ['show' => (bool) \App\Helpers\InvoicePdfHelper::getTemplateSetting('field_total_show', '1', $businessId, $template), 'label' => \App\Helpers\InvoicePdfHelper::getTemplateSetting('field_total_label', 'Total', $businessId, $template)],
            ];

            $currencyPrecision = $layoutData['currencyPrecision'];
            $quantityPrecision = $layoutData['quantityPrecision'];
            $layoutData['formatted']['items'] = $invoice->items->map(function ($item) use ($currencyPrecision, $quantityPrecision) {
                return [
                    'id' => $item->id,
                    'sku' => $item->item->sku ?? ('SKU-' . $item->id),
                    'product_description' => $item->product_description,
                    'hs_code' => $item->hs_code,
                    'uom' => $item->uom,
                    'quantity' => number_format($item->quantity, $quantityPrecision),
                    'rate' => $item->rate,
                    'unit_price' => number_format((float) $item->value_sales_excluding_st, $currencyPrecision),
                    'value_sales_excluding_st' => number_format($item->value_sales_excluding_st * (float) $item->quantity, $currencyPrecision),
                    'sales_tax_applicable' => number_format($item->sales_tax_applicable, $currencyPrecision),
                    'total_values' => number_format($item->total_values, $currencyPrecision),
                ];
            })->toArray();

            $html = view('invoices.invoice_pdf', [
                'invoice' => $invoice,
                'layoutData' => $layoutData,
                'invoices' => collect([$invoice]),
                'invoicesLayoutData' => [$invoice->id => $layoutData]
            ])->render();

            // Screenshot instead of pdf() — gives us a raster image of the first page
            $img = \App\Helpers\InvoicePdfHelper::makeBrowsershot($html)
                ->windowSize(794, 1123) // approx A4 @ 96dpi
                ->setScreenshotType('jpeg', 80)
                ->screenshot();

            return base64_encode($img);
        });

        if (!$image) {
            abort(404, 'No invoice found to generate preview.');
        }

        return response(base64_decode($image), 200, [
            'Content-Type' => 'image/jpeg',
            'Cache-Control' => 'public, max-age=1800',
        ]);
    }

    public function testSmtp(Request $request)
    {
        $request->validate([
            'test_email' => 'required|email',
            'mail_host' => 'required|string',
            'mail_port' => 'required|string|max:10',
            'mail_username' => 'nullable|string',
            'mail_password' => 'nullable|string',
            'mail_encryption' => 'nullable|string|max:10',
            'mail_from_address' => 'required|email',
            'mail_from_name' => 'required|string',
        ]);

        // Dynamically configure mailer in-memory
        config([
            'mail.default' => 'smtp',
            'mail.mailers.smtp.host' => $request->input('mail_host'),
            'mail.mailers.smtp.port' => $request->input('mail_port'),
            'mail.mailers.smtp.username' => $request->input('mail_username'),
            'mail.mailers.smtp.password' => $request->input('mail_password'),
            'mail.mailers.smtp.encryption' => $request->input('mail_encryption'),
            'mail.from.address' => $request->input('mail_from_address'),
            'mail.from.name' => $request->input('mail_from_name'),
        ]);

        try {
            \Illuminate\Support\Facades\Mail::raw("Hello! This is a test email confirming that your SMTP connection settings on FBR Digital Invoicing are configured correctly.", function ($message) use ($request) {
                $message->to($request->input('test_email'))
                    ->subject('FBR Invoicing SMTP Test Email');
            });

            return response()->json([
                'success' => true,
                'message' => 'Test email sent successfully!'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'SMTP Connection failed: ' . $e->getMessage()
            ], 500);
        }
    }
}
